From 2f412de0a867ffffe70909d9bb69434e3ac6b16b Mon Sep 17 00:00:00 2001 From: "nathan.sweet" Date: Sun, 14 Aug 2011 01:40:36 +0000 Subject: [PATCH] [updated] Everything to use the latest source formatter. Yay! Use it, love it! --- .../backends/android/AndroidApplication.java | 537 ++-- .../AndroidApplicationConfiguration.java | 39 +- .../gdx/backends/android/AndroidAudio.java | 52 +- .../backends/android/AndroidAudioDevice.java | 27 +- .../android/AndroidAudioRecorder.java | 14 +- .../backends/android/AndroidFileHandle.java | 6 +- .../gdx/backends/android/AndroidFiles.java | 28 +- .../gdx/backends/android/AndroidGL10.java | 280 +- .../gdx/backends/android/AndroidGL11.java | 155 +- .../gdx/backends/android/AndroidGL20.java | 1 + .../gdx/backends/android/AndroidGLU.java | 28 +- .../gdx/backends/android/AndroidGraphics.java | 246 +- .../gdx/backends/android/AndroidInput.java | 140 +- .../android/AndroidMultiTouchHandler.java | 62 +- .../gdx/backends/android/AndroidMusic.java | 35 +- .../backends/android/AndroidPreferences.java | 89 +- .../android/AndroidSingleTouchHandler.java | 16 +- .../gdx/backends/android/AndroidSound.java | 9 +- .../backends/android/AndroidTouchHandler.java | 5 +- .../surfaceview/DefaultGLSurfaceView.java | 30 +- .../surfaceview/FillResolutionStrategy.java | 23 +- .../surfaceview/FixedResolutionStrategy.java | 28 +- .../surfaceview/GLBaseSurfaceView.java | 227 +- .../android/surfaceview/GLDebugHelper.java | 37 +- .../android/surfaceview/GLErrorWrapper.java | 6 +- .../android/surfaceview/GLException.java | 8 +- .../android/surfaceview/GLLogWrapper.java | 19 +- .../android/surfaceview/GLSurfaceView20.java | 419 ++- .../surfaceview/GLSurfaceViewCupcake.java | 211 +- .../android/surfaceview/GLWrapperBase.java | 4 +- .../surfaceview/GdxEglConfigChooser.java | 77 +- .../surfaceview/RatioResolutionStrategy.java | 58 +- .../surfaceview/ResolutionStrategy.java | 35 +- .../gdx/backends/jogl/JoglAnimator.java | 46 +- .../gdx/backends/jogl/JoglApplication.java | 171 +- .../jogl/JoglApplicationConfiguration.java | 43 +- .../gdx/backends/jogl/JoglFileHandle.java | 6 +- .../badlogic/gdx/backends/jogl/JoglFiles.java | 28 +- .../badlogic/gdx/backends/jogl/JoglGL10.java | 280 +- .../badlogic/gdx/backends/jogl/JoglGL11.java | 155 +- .../badlogic/gdx/backends/jogl/JoglGL20.java | 455 ++- .../badlogic/gdx/backends/jogl/JoglGLU.java | 18 +- .../gdx/backends/jogl/JoglGraphics.java | 246 +- .../gdx/backends/jogl/JoglGraphicsBase.java | 59 +- .../badlogic/gdx/backends/jogl/JoglInput.java | 255 +- .../gdx/backends/jogl/JoglNativesLoader.java | 7 +- .../gdx/backends/jogl/JoglPreferences.java | 125 +- .../gdx/backends/lwjgl/LwjglApplet.java | 16 +- .../gdx/backends/lwjgl/LwjglApplication.java | 115 +- .../lwjgl/LwjglApplicationConfiguration.java | 53 +- .../gdx/backends/lwjgl/LwjglCanvas.java | 1 - .../gdx/backends/lwjgl/LwjglFileHandle.java | 6 +- .../gdx/backends/lwjgl/LwjglFiles.java | 28 +- .../gdx/backends/lwjgl/LwjglFrame.java | 1 - .../gdx/backends/lwjgl/LwjglGL10.java | 19 +- .../gdx/backends/lwjgl/LwjglGL11.java | 8 +- .../gdx/backends/lwjgl/LwjglGL20.java | 20 +- .../badlogic/gdx/backends/lwjgl/LwjglGLU.java | 54 +- .../gdx/backends/lwjgl/LwjglGraphics.java | 118 +- .../gdx/backends/lwjgl/LwjglInput.java | 427 ++- .../backends/lwjgl/LwjglNativesLoader.java | 8 +- .../gdx/backends/lwjgl/LwjglPreferences.java | 125 +- .../gdx/backends/angle/AngleApplication.java | 101 +- .../gdx/backends/angle/AngleAudio.java | 20 +- .../gdx/backends/angle/AngleAudioDevice.java | 11 +- .../backends/angle/AngleAudioRecorder.java | 8 +- .../gdx/backends/angle/AngleFileHandle.java | 6 +- .../gdx/backends/angle/AngleFiles.java | 22 +- .../gdx/backends/angle/AngleGLES0.java | 1 + .../badlogic/gdx/backends/angle/AngleGLU.java | 56 +- .../gdx/backends/angle/AngleGraphics.java | 96 +- .../gdx/backends/angle/AngleInput.java | 359 ++- .../gdx/backends/angle/AngleMusic.java | 28 +- .../gdx/backends/angle/AnglePreferences.java | 127 +- .../gdx/backends/angle/AngleSound.java | 16 +- .../gdx/backends/angle/PNGDecoder.java | 12 +- .../badlogic/gdx/backends/gwt/GdxGwtTest.java | 19 +- .../gdx/backends/gwt/GwtApplication.java | 82 +- .../gwt/GwtApplicationConfiguration.java | 5 +- .../badlogic/gdx/backends/gwt/GwtGL20.java | 617 ++-- .../gdx/backends/gwt/GwtGraphics.java | 83 +- .../badlogic/gdx/backends/gwt/PlainTest.java | 10 +- .../com/badlogic/gdx/files/FileHandle.java | 1 + .../emu/com/badlogic/gdx/graphics/Pixmap.java | 3 +- .../com/badlogic/gdx/graphics/Texture.java | 3 +- .../com/badlogic/gdx/utils/NumberUtils.java | 21 +- .../gwt/corp/compatibility/Compatibility.java | 104 +- .../corp/compatibility/CompatibilityImpl.java | 53 +- .../compatibility/ConsolePrintStream.java | 53 +- .../gwt/corp/compatibility/Endianness.java | 2 +- .../gwt/corp/compatibility/Numbers.java | 163 +- .../compatibility/StringToByteBuffer.java | 9 +- .../gwt/emu/java/nio/BaseByteBuffer.java | 97 +- .../gdx/backends/gwt/emu/java/nio/Buffer.java | 474 ++- .../gwt/emu/java/nio/BufferFactory.java | 315 +- .../emu/java/nio/BufferOverflowException.java | 25 +- .../java/nio/BufferUnderflowException.java | 25 +- .../backends/gwt/emu/java/nio/ByteBuffer.java | 1953 +++++------- .../gwt/emu/java/nio/ByteBufferWrapper.java | 5 +- .../backends/gwt/emu/java/nio/ByteOrder.java | 89 +- .../gwt/emu/java/nio/CharArrayBuffer.java | 125 +- .../backends/gwt/emu/java/nio/CharBuffer.java | 1423 ++++----- .../gwt/emu/java/nio/CharSequenceAdapter.java | 247 +- .../emu/java/nio/CharToByteBufferAdapter.java | 365 ++- .../gwt/emu/java/nio/DirectByteBuffer.java | 421 ++- .../java/nio/DirectReadOnlyByteBuffer.java | 247 +- .../nio/DirectReadOnlyFloatBufferAdapter.java | 229 +- .../nio/DirectReadOnlyIntBufferAdapter.java | 230 +- .../nio/DirectReadOnlyShortBufferAdapter.java | 226 +- .../java/nio/DirectReadWriteByteBuffer.java | 390 ++- .../DirectReadWriteFloatBufferAdapter.java | 264 +- .../nio/DirectReadWriteIntBufferAdapter.java | 260 +- .../DirectReadWriteShortBufferAdapter.java | 265 +- .../gwt/emu/java/nio/DoubleArrayBuffer.java | 103 +- .../gwt/emu/java/nio/DoubleBuffer.java | 962 +++--- .../java/nio/DoubleToByteBufferAdapter.java | 343 +- .../gwt/emu/java/nio/FloatArrayBuffer.java | 100 +- .../gwt/emu/java/nio/FloatBuffer.java | 961 +++--- .../java/nio/FloatToByteBufferAdapter.java | 341 +- .../gwt/emu/java/nio/HasArrayBufferView.java | 6 +- .../gwt/emu/java/nio/HeapByteBuffer.java | 439 ++- .../gwt/emu/java/nio/IntArrayBuffer.java | 101 +- .../backends/gwt/emu/java/nio/IntBuffer.java | 946 +++--- .../emu/java/nio/IntToByteBufferAdapter.java | 346 +- .../emu/java/nio/InvalidMarkException.java | 24 +- .../gwt/emu/java/nio/LongArrayBuffer.java | 99 +- .../backends/gwt/emu/java/nio/LongBuffer.java | 955 +++--- .../emu/java/nio/LongToByteBufferAdapter.java | 341 +- .../emu/java/nio/ReadOnlyBufferException.java | 24 +- .../emu/java/nio/ReadOnlyCharArrayBuffer.java | 145 +- .../java/nio/ReadOnlyDoubleArrayBuffer.java | 134 +- .../java/nio/ReadOnlyFloatArrayBuffer.java | 132 +- .../emu/java/nio/ReadOnlyHeapByteBuffer.java | 217 +- .../emu/java/nio/ReadOnlyIntArrayBuffer.java | 131 +- .../emu/java/nio/ReadOnlyLongArrayBuffer.java | 131 +- .../java/nio/ReadOnlyShortArrayBuffer.java | 132 +- .../java/nio/ReadWriteCharArrayBuffer.java | 179 +- .../java/nio/ReadWriteDoubleArrayBuffer.java | 186 +- .../java/nio/ReadWriteFloatArrayBuffer.java | 186 +- .../emu/java/nio/ReadWriteHeapByteBuffer.java | 344 +- .../emu/java/nio/ReadWriteIntArrayBuffer.java | 180 +- .../java/nio/ReadWriteLongArrayBuffer.java | 180 +- .../java/nio/ReadWriteShortArrayBuffer.java | 185 +- .../gwt/emu/java/nio/ShortArrayBuffer.java | 101 +- .../gwt/emu/java/nio/ShortBuffer.java | 948 +++--- .../java/nio/ShortToByteBufferAdapter.java | 345 +- .../gwt/emu/java/nio/StringByteBuffer.java | 391 +-- .../backends/openal/JavaSoundAudioDevice.java | 10 +- .../openal/JavaSoundAudioRecorder.java | 5 +- .../com/badlogic/gdx/backends/openal/Mp3.java | 11 +- .../com/badlogic/gdx/backends/openal/Ogg.java | 5 +- .../gdx/backends/openal/OggInputStream.java | 40 +- .../gdx/backends/openal/OpenALAudio.java | 6 +- .../gdx/backends/openal/OpenALSound.java | 7 +- .../com/badlogic/gdx/backends/openal/Wav.java | 1 + .../src/com/badlogic/cuboc/Cuboc.java | 23 +- .../cuboc/src/com/badlogic/cubocy/Bob.java | 123 +- .../cuboc/src/com/badlogic/cubocy/Cube.java | 173 +- .../cuboc/src/com/badlogic/cubocy/Cubocy.java | 10 +- .../src/com/badlogic/cubocy/Dispenser.java | 7 +- .../src/com/badlogic/cubocy/EndDoor.java | 5 +- .../cuboc/src/com/badlogic/cubocy/Laser.java | 146 +- .../cuboc/src/com/badlogic/cubocy/Map.java | 70 +- .../src/com/badlogic/cubocy/MapRenderer.java | 170 +- .../src/com/badlogic/cubocy/MovingSpikes.java | 74 +- .../cubocy/OnscreenControlRenderer.java | 41 +- .../cuboc/src/com/badlogic/cubocy/Rocket.java | 61 +- .../badlogic/cubocy/screens/CubocScreen.java | 26 +- .../cubocy/screens/GameOverScreen.java | 22 +- .../badlogic/cubocy/screens/GameScreen.java | 34 +- .../badlogic/cubocy/screens/IntroScreen.java | 24 +- .../com/badlogic/cubocy/screens/MainMenu.java | 24 +- .../com/badlogic/gdx/HelloWorldAndroid.java | 5 +- .../badlogic/gdx/helloworld/HelloWorld.java | 44 +- .../gdx/helloworld/HelloWorldDesktop.java | 1 + .../gdxinvaders/GdxInvadersAndroid.java | 7 +- .../com/badlogic/gdxinvaders/GdxInvaders.java | 20 +- .../gdxinvaders/GdxInvadersDesktop.java | 9 +- .../com/badlogic/gdxinvaders/Renderer.java | 23 +- .../gdxinvaders/screens/GameLoop.java | 18 +- .../gdxinvaders/screens/GameOver.java | 25 +- .../gdxinvaders/screens/MainMenu.java | 29 +- .../badlogic/gdxinvaders/screens/Screen.java | 29 +- .../com/badlogic/metagun/MetagunAndroid.java | 15 +- .../src/com/mojang/metagun/Art.java | 50 +- .../src/com/mojang/metagun/Input.java | 207 +- .../src/com/mojang/metagun/Metagun.java | 45 +- .../com/mojang/metagun/MetagunDesktop.java | 3 +- .../src/com/mojang/metagun/Sound.java | 55 +- .../src/com/mojang/metagun/Stats.java | 105 +- .../src/com/mojang/metagun/entity/Boss.java | 157 +- .../com/mojang/metagun/entity/BossNeck.java | 131 +- .../com/mojang/metagun/entity/BossPart.java | 14 +- .../src/com/mojang/metagun/entity/Bullet.java | 126 +- .../src/com/mojang/metagun/entity/Entity.java | 175 +- .../com/mojang/metagun/entity/Explosion.java | 95 +- .../src/com/mojang/metagun/entity/Gore.java | 69 +- .../com/mojang/metagun/entity/Gremlin.java | 201 +- .../src/com/mojang/metagun/entity/Gunner.java | 295 +- .../src/com/mojang/metagun/entity/Hat.java | 128 +- .../com/mojang/metagun/entity/HeadGore.java | 91 +- .../mojang/metagun/entity/Jabberwocky.java | 147 +- .../src/com/mojang/metagun/entity/Player.java | 449 +-- .../com/mojang/metagun/entity/PlayerGore.java | 89 +- .../src/com/mojang/metagun/entity/Sign.java | 73 +- .../src/com/mojang/metagun/entity/Spark.java | 69 +- .../src/com/mojang/metagun/level/Camera.java | 15 +- .../src/com/mojang/metagun/level/Level.java | 21 +- .../metagun/screen/ExpositionScreen.java | 99 +- .../com/mojang/metagun/screen/GameScreen.java | 22 +- .../metagun/screen/LevelTransitionScreen.java | 27 +- .../mojang/metagun/screen/PauseScreen.java | 137 +- .../src/com/mojang/metagun/screen/Screen.java | 2 +- .../mojang/metagun/screen/SignReadScreen.java | 272 +- .../mojang/metagun/screen/TitleScreen.java | 71 +- .../com/mojang/metagun/screen/WinScreen.java | 121 +- .../rtm-android/src/com/badlogic/rtm/Rtm.java | 4 +- .../src/com/badlogic/rtm/LevelRenderer.java | 23 +- .../rtm/src/com/badlogic/rtm/RtmDesktop.java | 1 + .../superjumper/SuperJumperAndroid.java | 16 +- .../badlogicgames/superjumper/Animation.java | 44 +- .../com/badlogicgames/superjumper/Assets.java | 177 +- .../com/badlogicgames/superjumper/Bob.java | 119 +- .../com/badlogicgames/superjumper/Castle.java | 12 +- .../com/badlogicgames/superjumper/Coin.java | 27 +- .../superjumper/DynamicGameObject.java | 17 +- .../com/badlogicgames/superjumper/Game.java | 29 +- .../badlogicgames/superjumper/GameObject.java | 15 +- .../badlogicgames/superjumper/GameScreen.java | 55 +- .../badlogicgames/superjumper/HelpScreen.java | 127 +- .../superjumper/HelpScreen2.java | 126 +- .../superjumper/HelpScreen3.java | 126 +- .../superjumper/HelpScreen4.java | 125 +- .../superjumper/HelpScreen5.java | 126 +- .../superjumper/HighscoresScreen.java | 24 +- .../superjumper/MainMenuScreen.java | 22 +- .../superjumper/OverlapTester.java | 36 +- .../badlogicgames/superjumper/Platform.java | 95 +- .../com/badlogicgames/superjumper/Screen.java | 25 +- .../badlogicgames/superjumper/Settings.java | 96 +- .../com/badlogicgames/superjumper/Spring.java | 14 +- .../badlogicgames/superjumper/Squirrel.java | 53 +- .../superjumper/SuperJumper.java | 28 +- .../superjumper/SuperJumperDesktop.java | 3 +- .../com/badlogicgames/superjumper/World.java | 414 ++- .../superjumper/WorldRenderer.java | 14 +- .../bouncy/BouncyAndroid.java | 4 +- .../bouncy/BaseFieldDelegate.java | 33 +- .../com/dozingcatsoftware/bouncy/Bouncy.java | 27 +- .../com/dozingcatsoftware/bouncy/Field.java | 103 +- .../dozingcatsoftware/bouncy/FieldLayout.java | 6 +- .../bouncy/GLFieldRenderer.java | 9 +- .../dozingcatsoftware/bouncy/GameMessage.java | 4 +- .../bouncy/IFieldRenderer.java | 6 +- .../bouncy/elements/Box2DFactory.java | 22 +- .../bouncy/elements/BumperElement.java | 18 +- .../elements/DropTargetGroupElement.java | 18 +- .../bouncy/elements/FieldElement.java | 90 +- .../bouncy/elements/FlipperElement.java | 21 +- .../bouncy/elements/RolloverGroupElement.java | 38 +- .../bouncy/elements/SensorElement.java | 22 +- .../bouncy/elements/WallArcElement.java | 12 +- .../bouncy/elements/WallElement.java | 22 +- .../bouncy/elements/WallPathElement.java | 12 +- .../bouncy/fields/Field1Delegate.java | 15 +- .../bouncy/util/JSONArray.java | 1538 ++++----- .../bouncy/util/JSONException.java | 33 +- .../bouncy/util/JSONObject.java | 2811 ++++++++--------- .../bouncy/util/JSONString.java | 23 +- .../bouncy/util/JSONStringer.java | 110 +- .../bouncy/util/JSONTokener.java | 791 +++-- .../bouncy/util/JSONUtils.java | 26 +- .../bouncy/util/JSONWriter.java | 508 ++- .../android/VeryAngryRobotsActivity.java | 23 +- .../badlydrawngames/general/CameraHelper.java | 62 +- .../badlydrawngames/general/Colliders.java | 101 +- .../general/CollisionGeometry.java | 28 +- .../com/badlydrawngames/general/Config.java | 38 +- .../badlydrawngames/general/GameScreen.java | 18 +- .../src/com/badlydrawngames/general/Grid.java | 35 +- .../badlydrawngames/general/MathUtils.java | 20 +- .../com/badlydrawngames/general/Particle.java | 26 +- .../general/ParticleManager.java | 16 +- .../com/badlydrawngames/general/Pools.java | 35 +- .../badlydrawngames/general/Rectangles.java | 18 +- .../badlydrawngames/general/ScoreString.java | 41 +- .../badlydrawngames/general/SimpleButton.java | 76 +- .../veryangryrobots/AchievementsListener.java | 2 +- .../veryangryrobots/AchievementsNotifier.java | 10 +- .../veryangryrobots/Assets.java | 115 +- .../veryangryrobots/DesktopStarter.java | 4 +- .../veryangryrobots/DifficultyManager.java | 11 +- .../veryangryrobots/Flyup.java | 11 +- .../veryangryrobots/FlyupManager.java | 13 +- .../veryangryrobots/IShowScores.java | 3 +- .../veryangryrobots/ISubmitScores.java | 3 +- .../veryangryrobots/MainMenuScreen.java | 61 +- .../veryangryrobots/MazeGenerator.java | 103 +- .../veryangryrobots/ParticleAdapter.java | 40 +- .../veryangryrobots/RoomBuilder.java | 80 +- .../ScoreBasedDifficultyManager.java | 64 +- .../veryangryrobots/ScoreListener.java | 5 +- .../veryangryrobots/ScoreNotifier.java | 14 +- .../veryangryrobots/ScoresScreen.java | 43 +- .../veryangryrobots/ScoringEventListener.java | 2 +- .../veryangryrobots/ScoringEventNotifier.java | 13 +- .../veryangryrobots/SoundManager.java | 54 +- .../veryangryrobots/StatusManager.java | 143 +- .../veryangryrobots/StatusView.java | 50 +- .../veryangryrobots/VeryAngryRobotsGame.java | 30 +- .../veryangryrobots/World.java | 303 +- .../veryangryrobots/WorldListener.java | 32 +- .../veryangryrobots/WorldNotifier.java | 34 +- .../veryangryrobots/WorldPresenter.java | 84 +- .../veryangryrobots/WorldView.java | 187 +- .../veryangryrobots/mobiles/BaseShot.java | 12 +- .../veryangryrobots/mobiles/Captain.java | 36 +- .../veryangryrobots/mobiles/GameObject.java | 122 +- .../veryangryrobots/mobiles/Player.java | 21 +- .../veryangryrobots/mobiles/PlayerShot.java | 7 +- .../veryangryrobots/mobiles/Robot.java | 101 +- .../veryangryrobots/mobiles/RobotShot.java | 16 +- eclipse-formatter.xml | 24 +- .../badlogic/gdx/beans/AppletInitializer.java | 4 +- .../gdx/beans/ArrayPersistenceDelegate.java | 187 +- .../beans/AwtChoicePersistenceDelegate.java | 32 +- .../beans/AwtColorPersistenceDelegate.java | 17 +- .../AwtComponentPersistenceDelegate.java | 36 +- .../AwtContainerPersistenceDelegate.java | 34 +- .../beans/AwtCursorPersistenceDelegate.java | 15 +- .../AwtDimensionPersistenceDelegate.java | 15 +- .../gdx/beans/AwtFontPersistenceDelegate.java | 17 +- ...tFontTextAttributePersistenceDelegate.java | 6 +- .../beans/AwtInsetsPersistenceDelegate.java | 17 +- .../gdx/beans/AwtListPersistenceDelegate.java | 37 +- .../beans/AwtMenuBarPersistenceDelegate.java | 38 +- .../gdx/beans/AwtMenuPersistenceDelegate.java | 38 +- .../AwtMenuShortcutPersistenceDelegate.java | 19 +- .../beans/AwtPointPersistenceDelegate.java | 15 +- .../AwtRectanglePersistenceDelegate.java | 36 +- .../AwtScrollPanePersistenceDelegate.java | 17 +- .../AwtSystemColorPersistenceDelegate.java | 6 +- .../badlogic/gdx/beans/BeanDescriptor.java | 134 +- .../src/com/badlogic/gdx/beans/BeanInfo.java | 24 +- .../src/com/badlogic/gdx/beans/Beans.java | 749 ++--- .../gdx/beans/ClassPersistenceDelegate.java | 134 +- .../beans/CustomizedObjectInputStream.java | 97 +- .../com/badlogic/gdx/beans/Customizer.java | 8 +- .../gdx/beans/DefaultPersistenceDelegate.java | 475 ++- .../com/badlogic/gdx/beans/DesignMode.java | 6 +- .../src/com/badlogic/gdx/beans/Encoder.java | 704 ++--- .../com/badlogic/gdx/beans/EventHandler.java | 630 ++-- .../gdx/beans/EventSetDescriptor.java | 768 +++-- .../badlogic/gdx/beans/ExceptionListener.java | 2 +- .../com/badlogic/gdx/beans/Expression.java | 86 +- .../badlogic/gdx/beans/FeatureDescriptor.java | 400 ++- .../gdx/beans/FieldPersistenceDelegate.java | 58 +- .../gdx/beans/IndexedPropertyChangeEvent.java | 66 +- .../gdx/beans/IndexedPropertyDescriptor.java | 657 ++-- .../gdx/beans/IntrospectionException.java | 8 +- .../com/badlogic/gdx/beans/Introspector.java | 552 ++-- .../badlogic/gdx/beans/MethodDescriptor.java | 139 +- .../gdx/beans/MethodPersistenceDelegate.java | 58 +- .../gdx/beans/NullPersistenceDelegate.java | 36 +- .../gdx/beans/ParameterDescriptor.java | 8 +- .../gdx/beans/PersistenceDelegate.java | 165 +- .../PrimitiveWrapperPersistenceDelegate.java | 78 +- .../gdx/beans/PropertyChangeEvent.java | 53 +- .../gdx/beans/PropertyChangeListener.java | 4 +- .../beans/PropertyChangeListenerProxy.java | 31 +- .../gdx/beans/PropertyChangeSupport.java | 468 ++- .../gdx/beans/PropertyDescriptor.java | 479 ++- .../badlogic/gdx/beans/PropertyEditor.java | 26 +- .../gdx/beans/PropertyEditorManager.java | 187 +- .../gdx/beans/PropertyEditorSupport.java | 203 +- .../gdx/beans/PropertyVetoException.java | 52 +- .../gdx/beans/ProxyPersistenceDelegate.java | 50 +- .../badlogic/gdx/beans/SimpleBeanInfo.java | 85 +- .../badlogic/gdx/beans/StandardBeanInfo.java | 2767 ++++++++-------- .../src/com/badlogic/gdx/beans/Statement.java | 1090 +++---- .../beans/StaticFieldPersistenceDelegate.java | 20 +- .../gdx/beans/StringPersistenceDelegate.java | 45 +- ...wingAbstractButtonPersistenceDelegate.java | 107 +- .../beans/SwingBoxPersistenceDelegate.java | 39 +- ...faultComboBoxModelPersistenceDelegate.java | 36 +- .../beans/SwingJFramePersistenceDelegate.java | 104 +- .../SwingJTabbedPanePersistenceDelegate.java | 97 +- ...wingToolTipManagerPersistenceDelegate.java | 9 +- .../UtilCollectionPersistenceDelegate.java | 92 +- .../beans/UtilDatePersistenceDelegate.java | 15 +- .../beans/UtilListPersistenceDelegate.java | 101 +- .../gdx/beans/UtilMapPersistenceDelegate.java | 32 +- .../gdx/beans/VetoableChangeListener.java | 6 +- .../beans/VetoableChangeListenerProxy.java | 33 +- .../gdx/beans/VetoableChangeSupport.java | 420 ++- .../com/badlogic/gdx/beans/Visibility.java | 8 +- .../com/badlogic/gdx/beans/XMLDecoder.java | 1214 ++++--- .../com/badlogic/gdx/beans/XMLEncoder.java | 1747 +++++----- .../gdx/beans/beancontext/BeanContext.java | 32 +- .../beans/beancontext/BeanContextChild.java | 17 +- .../BeanContextChildComponentProxy.java | 2 +- .../beancontext/BeanContextChildSupport.java | 310 +- .../BeanContextContainerProxy.java | 2 +- .../beans/beancontext/BeanContextEvent.java | 42 +- .../BeanContextMembershipEvent.java | 62 +- .../BeanContextMembershipListener.java | 6 +- .../beans/beancontext/BeanContextProxy.java | 4 +- .../BeanContextServiceAvailableEvent.java | 39 +- .../BeanContextServiceProvider.java | 9 +- .../BeanContextServiceProviderBeanInfo.java | 2 +- .../BeanContextServiceRevokedEvent.java | 52 +- .../BeanContextServiceRevokedListener.java | 4 +- .../beancontext/BeanContextServices.java | 37 +- .../BeanContextServicesListener.java | 8 +- .../BeanContextServicesSupport.java | 1849 +++++------ .../beans/beancontext/BeanContextSupport.java | 2406 +++++++------- .../org/apache/harmony/beans/Argument.java | 80 +- .../org/apache/harmony/beans/BeansUtils.java | 189 +- .../src/org/apache/harmony/beans/Command.java | 1630 +++++----- .../src/org/apache/harmony/beans/Handler.java | 224 +- .../harmony/beans/internal/nls/Messages.java | 280 +- .../com/badlogic/gdx/remote/GdxRemote.java | 19 +- .../com/badlogic/gdx/remote/UxAndroid.java | 62 +- .../g3d/tests/ModelViewerActivity.java | 31 +- .../graphics/g3d/AnimatedModelInstance.java | 9 +- .../gdx/graphics/g3d/ModelLoaderHints.java | 14 +- .../gdx/graphics/g3d/ModelRenderer.java | 12 +- .../gdx/graphics/g3d/StillModelInstance.java | 9 +- .../com/badlogic/gdx/graphics/g3d/Test.java | 28 +- .../g3d/loaders/KeyframedModelLoader.java | 10 +- .../gdx/graphics/g3d/loaders/ModelLoader.java | 15 +- .../g3d/loaders/ModelLoaderRegistry.java | 415 +-- .../g3d/loaders/SkeletonModelLoader.java | 10 +- .../g3d/loaders/StillModelLoader.java | 12 +- .../g3d/loaders/collada/ColladaLoader.java | 61 +- .../graphics/g3d/loaders/collada/Faces.java | 218 +- .../g3d/loaders/collada/Geometry.java | 44 +- .../graphics/g3d/loaders/collada/Source.java | 25 +- .../g3d/loaders/g3d/G3dConstants.java | 8 +- .../graphics/g3d/loaders/g3d/G3dLoader.java | 167 +- .../graphics/g3d/loaders/g3d/G3dtLoader.java | 282 +- .../g3d/loaders/g3d/chunks/ChunkReader.java | 333 +- .../g3d/loaders/g3d/chunks/ChunkWriter.java | 161 +- .../g3d/chunks/CountingDataInputStream.java | 54 +- .../g3d/loaders/g3d/chunks/G3dExporter.java | 105 +- .../graphics/g3d/loaders/md2/MD2Frame.java | 1 + .../graphics/g3d/loaders/md2/MD2Header.java | 1 + .../graphics/g3d/loaders/md2/MD2Loader.java | 48 +- .../graphics/g3d/loaders/md2/MD2Triangle.java | 4 +- .../g3d/loaders/ogre/OgreXmlLoader.java | 373 ++- .../g3d/loaders/ogre/mesh/Animation.java | 123 +- .../g3d/loaders/ogre/mesh/Animations.java | 62 +- .../g3d/loaders/ogre/mesh/Binormal.java | 13 +- .../loaders/ogre/mesh/Boneassignments.java | 62 +- .../g3d/loaders/ogre/mesh/ColourDiffuse.java | 45 +- .../g3d/loaders/ogre/mesh/ColourSpecular.java | 45 +- .../g3d/loaders/ogre/mesh/Extremes.java | 62 +- .../graphics/g3d/loaders/ogre/mesh/Face.java | 13 +- .../graphics/g3d/loaders/ogre/mesh/Faces.java | 66 +- .../g3d/loaders/ogre/mesh/Geometry.java | 66 +- .../g3d/loaders/ogre/mesh/Keyframe.java | 158 +- .../g3d/loaders/ogre/mesh/Keyframes.java | 60 +- .../g3d/loaders/ogre/mesh/Levelofdetail.java | 201 +- .../g3d/loaders/ogre/mesh/Lodfacelist.java | 140 +- .../g3d/loaders/ogre/mesh/Lodgenerated.java | 123 +- .../g3d/loaders/ogre/mesh/Lodmanual.java | 89 +- .../graphics/g3d/loaders/ogre/mesh/Mesh.java | 376 +-- .../g3d/loaders/ogre/mesh/Normal.java | 13 +- .../g3d/loaders/ogre/mesh/ObjectFactory.java | 539 ++-- .../graphics/g3d/loaders/ogre/mesh/Pose.java | 196 +- .../g3d/loaders/ogre/mesh/Poseoffset.java | 333 +- .../g3d/loaders/ogre/mesh/Poseref.java | 97 +- .../graphics/g3d/loaders/ogre/mesh/Poses.java | 62 +- .../g3d/loaders/ogre/mesh/Position.java | 13 +- .../g3d/loaders/ogre/mesh/Sharedgeometry.java | 100 +- .../g3d/loaders/ogre/mesh/Skeletonlink.java | 45 +- .../g3d/loaders/ogre/mesh/Submesh.java | 274 +- .../loaders/ogre/mesh/SubmeshExtremes.java | 100 +- .../g3d/loaders/ogre/mesh/Submeshes.java | 62 +- .../g3d/loaders/ogre/mesh/Submeshname.java | 89 +- .../g3d/loaders/ogre/mesh/Submeshnames.java | 62 +- .../g3d/loaders/ogre/mesh/Tangent.java | 17 +- .../g3d/loaders/ogre/mesh/Texcoord.java | 17 +- .../g3d/loaders/ogre/mesh/Texture.java | 89 +- .../g3d/loaders/ogre/mesh/Textures.java | 62 +- .../graphics/g3d/loaders/ogre/mesh/Track.java | 171 +- .../g3d/loaders/ogre/mesh/Tracks.java | 62 +- .../g3d/loaders/ogre/mesh/Vertex.java | 312 +- .../ogre/mesh/Vertexboneassignment.java | 13 +- .../g3d/loaders/ogre/mesh/Vertexbuffer.java | 471 ++- .../g3d/loaders/ogre/skeleton/Animation.java | 55 +- .../loaders/ogre/skeleton/Animationlink.java | 97 +- .../loaders/ogre/skeleton/Animationlinks.java | 62 +- .../g3d/loaders/ogre/skeleton/Animations.java | 62 +- .../g3d/loaders/ogre/skeleton/Axis.java | 13 +- .../g3d/loaders/ogre/skeleton/Bone.java | 29 +- .../loaders/ogre/skeleton/Bonehierarchy.java | 60 +- .../g3d/loaders/ogre/skeleton/Boneparent.java | 89 +- .../g3d/loaders/ogre/skeleton/Bones.java | 62 +- .../g3d/loaders/ogre/skeleton/Keyframe.java | 17 +- .../g3d/loaders/ogre/skeleton/Keyframes.java | 62 +- .../loaders/ogre/skeleton/ObjectFactory.java | 279 +- .../g3d/loaders/ogre/skeleton/Position.java | 13 +- .../g3d/loaders/ogre/skeleton/Rotate.java | 13 +- .../g3d/loaders/ogre/skeleton/Rotation.java | 13 +- .../g3d/loaders/ogre/skeleton/Scale.java | 17 +- .../g3d/loaders/ogre/skeleton/Skeleton.java | 156 +- .../g3d/loaders/ogre/skeleton/Track.java | 91 +- .../g3d/loaders/ogre/skeleton/Tracks.java | 62 +- .../g3d/loaders/ogre/skeleton/Translate.java | 13 +- .../g3d/loaders/wavefront/ObjLoader.java | 107 +- .../g3d/materials/ColorAttribute.java | 18 +- .../gdx/graphics/g3d/materials/Material.java | 35 +- .../g3d/materials/MaterialAttribute.java | 15 +- .../g3d/materials/TextureAttribute.java | 23 +- .../gdx/graphics/g3d/model/AnimatedModel.java | 9 +- .../gdx/graphics/g3d/model/Animation.java | 7 +- .../gdx/graphics/g3d/model/Model.java | 27 +- .../gdx/graphics/g3d/model/SubMesh.java | 5 +- .../graphics/g3d/model/keyframe/Keyframe.java | 9 +- .../model/keyframe/KeyframedAnimation.java | 7 +- .../g3d/model/keyframe/KeyframedModel.java | 151 +- .../g3d/model/keyframe/KeyframedSubMesh.java | 15 +- .../graphics/g3d/model/skeleton/Skeleton.java | 95 +- .../g3d/model/skeleton/SkeletonAnimation.java | 7 +- .../g3d/model/skeleton/SkeletonJoint.java | 13 +- .../g3d/model/skeleton/SkeletonKeyframe.java | 14 +- .../g3d/model/skeleton/SkeletonModel.java | 147 +- .../g3d/model/skeleton/SkeletonSubMesh.java | 10 +- .../graphics/g3d/model/still/StillModel.java | 41 +- .../g3d/model/still/StillSubMesh.java | 8 +- .../gdx/graphics/g3d/test/ChunkTest.java | 71 +- .../g3d/test/KeyframedModelViewer.java | 138 +- .../gdx/graphics/g3d/test/QbobViewer.java | 123 +- .../g3d/test/SkeletonModelViewer.java | 126 +- .../graphics/g3d/test/StillModelViewer.java | 170 +- .../gdx/graphics/g3d/test/Viewer.java | 113 +- .../graphics/g3d/test/WolfensteinTest.java | 72 +- .../test/utils/PerspectiveCamController.java | 21 +- .../gdx/tiledmappacker/TileSetLayout.java | 13 +- .../gdx/tiledmappacker/TiledMapPacker.java | 48 +- .../badlogic/gdx/twl/ButtonTestAndroid.java | 9 +- .../com/badlogic/gdx/twl/NodeTestAndroid.java | 7 +- .../badlogic/gdx/twl/TextAreaTestAndroid.java | 9 +- .../com/badlogic/gdx/twl/TwlTestActivity.java | 47 +- .../badlogic/gdx/twl/tests/ButtonTest.java | 25 +- .../gdx/twl/tests/ButtonTestDesktop.java | 1 + .../badlogic/gdx/twl/tests/TextAreaTest.java | 19 +- .../gdx/twl/tests/TextAreaTestDesktop.java | 1 + .../gdx/twl/tests/nodes/Connection.java | 74 +- .../badlogic/gdx/twl/tests/nodes/Node.java | 99 +- .../gdx/twl/tests/nodes/NodeArea.java | 312 +- .../gdx/twl/tests/nodes/NodeTest.java | 79 +- .../gdx/twl/tests/nodes/NodeTestDesktop.java | 7 +- .../com/badlogic/gdx/twl/tests/nodes/Pad.java | 224 +- .../src/com/badlogic/gdx/twl/Layout.java | 45 +- .../gdx-twl/src/com/badlogic/gdx/twl/TWL.java | 39 +- .../gdx/twl/renderer/GdxCacheContext.java | 5 +- .../badlogic/gdx/twl/renderer/GdxFont.java | 23 +- .../badlogic/gdx/twl/renderer/GdxImage.java | 6 +- .../gdx/twl/renderer/GdxRenderer.java | 73 +- .../badlogic/gdx/twl/renderer/GdxTexture.java | 38 +- gdx/src/com/badlogic/gdx/Application.java | 119 +- .../com/badlogic/gdx/ApplicationListener.java | 38 +- gdx/src/com/badlogic/gdx/Audio.java | 32 +- gdx/src/com/badlogic/gdx/Files.java | 69 +- gdx/src/com/badlogic/gdx/Game.java | 32 +- gdx/src/com/badlogic/gdx/Gdx.java | 12 +- gdx/src/com/badlogic/gdx/Graphics.java | 352 +-- gdx/src/com/badlogic/gdx/Input.java | 363 +-- gdx/src/com/badlogic/gdx/InputAdapter.java | 14 +- .../com/badlogic/gdx/InputMultiplexer.java | 13 +- gdx/src/com/badlogic/gdx/InputProcessor.java | 56 +- gdx/src/com/badlogic/gdx/Preferences.java | 84 +- gdx/src/com/badlogic/gdx/Screen.java | 37 +- gdx/src/com/badlogic/gdx/Version.java | 9 +- .../badlogic/gdx/assets/AssetDescriptor.java | 18 +- .../gdx/assets/AssetErrorListener.java | 3 +- .../gdx/assets/AssetLoaderParameters.java | 1 + .../badlogic/gdx/assets/AssetLoadingTask.java | 77 +- .../com/badlogic/gdx/assets/AssetManager.java | 304 +- .../gdx/assets/ReferenceCountedAsset.java | 6 +- .../gdx/assets/loaders/AssetLoader.java | 13 +- .../loaders/AsynchronousAssetLoader.java | 10 +- .../gdx/assets/loaders/BitmapFontLoader.java | 10 +- .../assets/loaders/BitmapFontParameter.java | 1 + .../assets/loaders/FileHandleResolver.java | 3 +- .../gdx/assets/loaders/MusicLoader.java | 1 + .../gdx/assets/loaders/MusicParameter.java | 1 + .../gdx/assets/loaders/PixmapLoader.java | 5 +- .../gdx/assets/loaders/PixmapParameter.java | 1 + .../gdx/assets/loaders/SoundLoader.java | 1 + .../gdx/assets/loaders/SoundParameter.java | 1 + .../loaders/SynchronousAssetLoader.java | 5 +- .../assets/loaders/TextureAtlasLoader.java | 22 +- .../assets/loaders/TextureAtlasParameter.java | 3 +- .../gdx/assets/loaders/TextureLoader.java | 25 +- .../gdx/assets/loaders/TextureParameter.java | 5 +- .../resolvers/ExternalFileHandleResolver.java | 1 + .../resolvers/InternalFileHandleResolver.java | 1 + .../com/badlogic/gdx/audio/AudioDevice.java | 36 +- .../com/badlogic/gdx/audio/AudioRecorder.java | 18 +- gdx/src/com/badlogic/gdx/audio/Music.java | 52 +- gdx/src/com/badlogic/gdx/audio/Sound.java | 26 +- .../gdx/audio/analysis/AudioTools.java | 50 +- .../com/badlogic/gdx/audio/analysis/DFT.java | 21 +- .../com/badlogic/gdx/audio/analysis/FFT.java | 29 +- .../gdx/audio/analysis/FourierTransform.java | 162 +- .../badlogic/gdx/audio/analysis/KissFFT.java | 106 +- .../gdx/audio/analysis/NativeFFT.java | 8 +- .../gdx/audio/analysis/ThresholdFunction.java | 20 +- .../com/badlogic/gdx/audio/io/Decoder.java | 36 +- .../badlogic/gdx/audio/io/Mpg123Decoder.java | 47 +- .../badlogic/gdx/audio/io/VorbisDecoder.java | 56 +- .../com/badlogic/gdx/files/FileHandle.java | 126 +- .../badlogic/gdx/files/FileHandleStream.java | 7 +- gdx/src/com/badlogic/gdx/graphics/Camera.java | 224 +- gdx/src/com/badlogic/gdx/graphics/Color.java | 126 +- .../com/badlogic/gdx/graphics/FPSLogger.java | 26 +- gdx/src/com/badlogic/gdx/graphics/GL10.java | 8 +- gdx/src/com/badlogic/gdx/graphics/GL11.java | 8 +- gdx/src/com/badlogic/gdx/graphics/GL20.java | 12 +- .../com/badlogic/gdx/graphics/GLCommon.java | 8 +- gdx/src/com/badlogic/gdx/graphics/GLU.java | 21 +- gdx/src/com/badlogic/gdx/graphics/Mesh.java | 365 +-- .../gdx/graphics/OrthographicCamera.java | 19 +- .../gdx/graphics/PerspectiveCamera.java | 31 +- gdx/src/com/badlogic/gdx/graphics/Pixmap.java | 341 +- .../com/badlogic/gdx/graphics/Texture.java | 303 +- .../badlogic/gdx/graphics/TextureData.java | 45 +- .../badlogic/gdx/graphics/TextureDict.java | 96 +- .../com/badlogic/gdx/graphics/TextureRef.java | 76 +- .../gdx/graphics/VertexAttribute.java | 14 +- .../gdx/graphics/VertexAttributes.java | 35 +- .../badlogic/gdx/graphics/g2d/Animation.java | 77 +- .../badlogic/gdx/graphics/g2d/BitmapFont.java | 234 +- .../gdx/graphics/g2d/BitmapFontCache.java | 122 +- .../gdx/graphics/g2d/EmptyNinePatch.java | 4 +- .../gdx/graphics/g2d/Gdx2DPixmap.java | 207 +- .../badlogic/gdx/graphics/g2d/NinePatch.java | 107 +- .../gdx/graphics/g2d/ParticleEffect.java | 12 +- .../gdx/graphics/g2d/ParticleEmitter.java | 12 +- .../com/badlogic/gdx/graphics/g2d/Sprite.java | 152 +- .../gdx/graphics/g2d/SpriteBatch.java | 223 +- .../gdx/graphics/g2d/SpriteCache.java | 211 +- .../gdx/graphics/g2d/TextureAtlas.java | 203 +- .../gdx/graphics/g2d/TextureRegion.java | 121 +- .../graphics/g2d/tiled/SimpleTileAtlas.java | 91 +- .../gdx/graphics/g2d/tiled/TileAtlas.java | 193 +- .../graphics/g2d/tiled/TileMapRenderer.java | 305 +- .../gdx/graphics/g2d/tiled/TileSet.java | 16 +- .../gdx/graphics/g2d/tiled/TiledLayer.java | 23 +- .../gdx/graphics/g2d/tiled/TiledLoader.java | 31 +- .../gdx/graphics/g2d/tiled/TiledMap.java | 22 +- .../gdx/graphics/g2d/tiled/TiledObject.java | 7 +- .../graphics/g2d/tiled/TiledObjectGroup.java | 7 +- .../badlogic/gdx/graphics/g3d/Animation.java | 12 +- .../badlogic/gdx/graphics/g3d/Animator.java | 137 +- .../badlogic/gdx/graphics/g3d/Material.java | 91 +- .../g3d/decals/CameraGroupStrategy.java | 94 +- .../gdx/graphics/g3d/decals/Decal.java | 535 ++-- .../gdx/graphics/g3d/decals/DecalBatch.java | 175 +- .../graphics/g3d/decals/DecalMaterial.java | 37 +- .../g3d/decals/DefaultGroupStrategy.java | 60 +- .../gdx/graphics/g3d/decals/GroupPlug.java | 13 +- .../graphics/g3d/decals/GroupStrategy.java | 85 +- .../g3d/decals/PluggableGroupStrategy.java | 28 +- .../g3d/decals/SimpleOrthoGroupStrategy.java | 60 +- .../gdx/graphics/g3d/keyframed/Keyframe.java | 10 +- .../g3d/keyframed/KeyframeAnimation.java | 26 +- .../g3d/keyframed/KeyframeAnimator.java | 185 +- .../g3d/keyframed/KeyframedModel.java | 328 +- .../graphics/g3d/loaders/ModelLoaderOld.java | 14 +- .../g3d/loaders/md5/MD5Animation.java | 36 +- .../g3d/loaders/md5/MD5AnimationInfo.java | 1 + .../graphics/g3d/loaders/md5/MD5Animator.java | 44 +- .../gdx/graphics/g3d/loaders/md5/MD5Jni.java | 1 + .../graphics/g3d/loaders/md5/MD5Joints.java | 23 +- .../graphics/g3d/loaders/md5/MD5Loader.java | 232 +- .../gdx/graphics/g3d/loaders/md5/MD5Mesh.java | 433 +-- .../graphics/g3d/loaders/md5/MD5Model.java | 30 +- .../g3d/loaders/md5/MD5Quaternion.java | 21 +- .../graphics/g3d/loaders/md5/MD5Renderer.java | 128 +- .../graphics/g3d/loaders/obj/ObjLoader.java | 42 +- .../badlogic/gdx/graphics/glutils/ETC1.java | 225 +- .../gdx/graphics/glutils/ETC1TextureData.java | 23 +- .../gdx/graphics/glutils/FileTextureData.java | 23 +- .../gdx/graphics/glutils/FrameBuffer.java | 76 +- .../glutils/ImmediateModeRenderer10.java | 60 +- .../glutils/ImmediateModeRenderer20.java | 179 +- .../graphics/glutils/IndexBufferObject.java | 56 +- .../glutils/IndexBufferObjectSubData.java | 56 +- .../gdx/graphics/glutils/IndexData.java | 44 +- .../gdx/graphics/glutils/MipMapGenerator.java | 85 +- .../graphics/glutils/PixmapTextureData.java | 13 +- .../gdx/graphics/glutils/ShaderProgram.java | 365 +-- .../gdx/graphics/glutils/VertexArray.java | 80 +- .../graphics/glutils/VertexBufferObject.java | 106 +- .../glutils/VertexBufferObjectSubData.java | 89 +- .../gdx/graphics/glutils/VertexData.java | 44 +- .../com/badlogic/gdx/input/RemoteInput.java | 258 +- .../com/badlogic/gdx/input/RemoteSender.java | 130 +- .../badlogic/gdx/math/CatmullRomSpline.java | 58 +- gdx/src/com/badlogic/gdx/math/Circle.java | 34 +- .../gdx/math/EarClippingTriangulator.java | 197 +- gdx/src/com/badlogic/gdx/math/Frustum.java | 167 +- .../com/badlogic/gdx/math/Intersector.java | 196 +- gdx/src/com/badlogic/gdx/math/MathUtils.java | 48 +- gdx/src/com/badlogic/gdx/math/Matrix3.java | 111 +- gdx/src/com/badlogic/gdx/math/Matrix4.java | 402 +-- gdx/src/com/badlogic/gdx/math/Plane.java | 85 +- gdx/src/com/badlogic/gdx/math/Polygon.java | 97 +- gdx/src/com/badlogic/gdx/math/Quaternion.java | 449 ++- gdx/src/com/badlogic/gdx/math/Rectangle.java | 102 +- gdx/src/com/badlogic/gdx/math/Vector2.java | 207 +- gdx/src/com/badlogic/gdx/math/Vector3.java | 246 +- .../com/badlogic/gdx/math/WindowedMean.java | 46 +- .../gdx/math/collision/BoundingBox.java | 122 +- .../com/badlogic/gdx/math/collision/Ray.java | 54 +- .../badlogic/gdx/math/collision/Segment.java | 22 +- .../badlogic/gdx/math/collision/Sphere.java | 26 +- .../com/badlogic/gdx/physics/box2d/Body.java | 316 +- .../badlogic/gdx/physics/box2d/BodyDef.java | 44 +- .../gdx/physics/box2d/Box2DDebugRenderer.java | 5 +- .../gdx/physics/box2d/CircleShape.java | 23 +- .../badlogic/gdx/physics/box2d/Contact.java | 30 +- .../gdx/physics/box2d/ContactFilter.java | 8 +- .../gdx/physics/box2d/ContactImpulse.java | 27 +- .../gdx/physics/box2d/ContactListener.java | 45 +- .../physics/box2d/DestructionListener.java | 1 + .../badlogic/gdx/physics/box2d/Filter.java | 22 +- .../badlogic/gdx/physics/box2d/Fixture.java | 95 +- .../gdx/physics/box2d/FixtureDef.java | 16 +- .../com/badlogic/gdx/physics/box2d/Joint.java | 39 +- .../badlogic/gdx/physics/box2d/JointDef.java | 1 + .../badlogic/gdx/physics/box2d/JointEdge.java | 7 +- .../badlogic/gdx/physics/box2d/Manifold.java | 79 +- .../badlogic/gdx/physics/box2d/MassData.java | 8 +- .../gdx/physics/box2d/PolygonShape.java | 44 +- .../gdx/physics/box2d/QueryCallback.java | 11 +- .../gdx/physics/box2d/RayCastCallback.java | 31 +- .../com/badlogic/gdx/physics/box2d/Shape.java | 33 +- .../badlogic/gdx/physics/box2d/Transform.java | 36 +- .../com/badlogic/gdx/physics/box2d/World.java | 211 +- .../gdx/physics/box2d/WorldManifold.java | 19 +- .../physics/box2d/joints/DistanceJoint.java | 31 +- .../box2d/joints/DistanceJointDef.java | 31 +- .../physics/box2d/joints/FrictionJoint.java | 21 +- .../box2d/joints/FrictionJointDef.java | 25 +- .../gdx/physics/box2d/joints/GearJoint.java | 15 +- .../physics/box2d/joints/GearJointDef.java | 21 +- .../gdx/physics/box2d/joints/LineJoint.java | 63 +- .../physics/box2d/joints/LineJointDef.java | 47 +- .../gdx/physics/box2d/joints/MouseJoint.java | 39 +- .../physics/box2d/joints/MouseJointDef.java | 23 +- .../physics/box2d/joints/PrismaticJoint.java | 59 +- .../box2d/joints/PrismaticJointDef.java | 51 +- .../gdx/physics/box2d/joints/PulleyJoint.java | 27 +- .../physics/box2d/joints/PulleyJointDef.java | 47 +- .../physics/box2d/joints/RevoluteJoint.java | 61 +- .../box2d/joints/RevoluteJointDef.java | 47 +- .../gdx/physics/box2d/joints/WeldJoint.java | 7 +- .../physics/box2d/joints/WeldJointDef.java | 1 + .../badlogic/gdx/scenes/scene2d/Action.java | 65 +- .../badlogic/gdx/scenes/scene2d/Actor.java | 69 +- .../gdx/scenes/scene2d/AnimationAction.java | 24 +- .../gdx/scenes/scene2d/CompositeAction.java | 13 +- .../badlogic/gdx/scenes/scene2d/Group.java | 279 +- .../gdx/scenes/scene2d/Interpolator.java | 25 +- .../badlogic/gdx/scenes/scene2d/Layout.java | 3 +- .../gdx/scenes/scene2d/OnActionCompleted.java | 24 +- .../badlogic/gdx/scenes/scene2d/Stage.java | 255 +- .../gdx/scenes/scene2d/TemporalAction.java | 13 +- .../scene2d/actions/ActionResetingPool.java | 10 +- .../gdx/scenes/scene2d/actions/Delay.java | 31 +- .../gdx/scenes/scene2d/actions/FadeIn.java | 19 +- .../gdx/scenes/scene2d/actions/FadeOut.java | 19 +- .../gdx/scenes/scene2d/actions/FadeTo.java | 19 +- .../gdx/scenes/scene2d/actions/Forever.java | 22 +- .../gdx/scenes/scene2d/actions/MoveBy.java | 19 +- .../gdx/scenes/scene2d/actions/MoveTo.java | 19 +- .../gdx/scenes/scene2d/actions/Parallel.java | 34 +- .../gdx/scenes/scene2d/actions/Remove.java | 31 +- .../gdx/scenes/scene2d/actions/Repeat.java | 25 +- .../gdx/scenes/scene2d/actions/RotateBy.java | 19 +- .../gdx/scenes/scene2d/actions/RotateTo.java | 19 +- .../gdx/scenes/scene2d/actions/ScaleTo.java | 19 +- .../gdx/scenes/scene2d/actions/Sequence.java | 51 +- .../gdx/scenes/scene2d/actors/BoundGroup.java | 8 +- .../gdx/scenes/scene2d/actors/Button.java | 39 +- .../gdx/scenes/scene2d/actors/FastImage.java | 49 +- .../gdx/scenes/scene2d/actors/Image.java | 13 +- .../gdx/scenes/scene2d/actors/Label.java | 16 +- .../scenes/scene2d/actors/LinearGroup.java | 1 + .../AccelerateDecelerateInterpolator.java | 28 +- .../interpolators/AccelerateInterpolator.java | 28 +- .../interpolators/AnticipateInterpolator.java | 28 +- .../interpolators/DecelerateInterpolator.java | 28 +- .../interpolators/LinearInterpolator.java | 25 +- .../interpolators/OvershootInterpolator.java | 32 +- .../gdx/scenes/scene2d/ui/Button.java | 165 +- .../gdx/scenes/scene2d/ui/CheckBox.java | 171 +- .../gdx/scenes/scene2d/ui/ComboBox.java | 275 +- .../scenes/scene2d/ui/FlickScrollPane.java | 258 +- .../gdx/scenes/scene2d/ui/ImageButton.java | 191 +- .../scenes/scene2d/ui/ImageToggleButton.java | 203 +- .../badlogic/gdx/scenes/scene2d/ui/Label.java | 84 +- .../badlogic/gdx/scenes/scene2d/ui/List.java | 176 +- .../badlogic/gdx/scenes/scene2d/ui/Pane.java | 95 +- .../gdx/scenes/scene2d/ui/ScrollPane.java | 310 +- .../badlogic/gdx/scenes/scene2d/ui/Skin.java | 1181 +++---- .../gdx/scenes/scene2d/ui/Slider.java | 188 +- .../gdx/scenes/scene2d/ui/SplitPane.java | 304 +- .../gdx/scenes/scene2d/ui/TextField.java | 288 +- .../gdx/scenes/scene2d/ui/ToggleButton.java | 164 +- .../gdx/scenes/scene2d/ui/Widget.java | 81 +- .../gdx/scenes/scene2d/ui/Window.java | 201 +- .../scenes/scene2d/ui/tablelayout/Cell.java | 2 +- .../scenes/scene2d/ui/tablelayout/Table.java | 1 - .../scene2d/ui/tablelayout/Toolkit.java | 2 +- .../scene2d/ui/utils/AndroidClipboard.java | 9 +- .../scenes/scene2d/ui/utils/Clipboard.java | 35 +- .../scene2d/ui/utils/DesktopClipboard.java | 18 +- .../scenes/scene2d/ui/utils/ScissorStack.java | 116 +- gdx/src/com/badlogic/gdx/utils/Array.java | 82 +- .../com/badlogic/gdx/utils/AtomicQueue.java | 6 +- .../com/badlogic/gdx/utils/Base64Coder.java | 224 +- .../com/badlogic/gdx/utils/BufferUtils.java | 277 +- .../badlogic/gdx/utils/ComparableTimSort.java | 166 +- .../com/badlogic/gdx/utils/Disposable.java | 14 +- .../com/badlogic/gdx/utils/FloatArray.java | 51 +- .../badlogic/gdx/utils/GdxNativesLoader.java | 15 +- .../gdx/utils/GdxRuntimeException.java | 8 +- .../com/badlogic/gdx/utils/IdentityMap.java | 72 +- gdx/src/com/badlogic/gdx/utils/IntArray.java | 51 +- gdx/src/com/badlogic/gdx/utils/IntMap.java | 73 +- .../gdx/utils/LittleEndianInputStream.java | 178 +- gdx/src/com/badlogic/gdx/utils/Logger.java | 26 +- gdx/src/com/badlogic/gdx/utils/LongArray.java | 51 +- gdx/src/com/badlogic/gdx/utils/LongMap.java | 72 +- .../com/badlogic/gdx/utils/NumberUtils.java | 19 +- gdx/src/com/badlogic/gdx/utils/ObjectMap.java | 72 +- .../badlogic/gdx/utils/PauseableThread.java | 30 +- gdx/src/com/badlogic/gdx/utils/Pool.java | 45 +- .../badlogic/gdx/utils/PooledLinkedList.java | 72 +- .../com/badlogic/gdx/utils/ScreenUtils.java | 104 +- gdx/src/com/badlogic/gdx/utils/Sort.java | 10 +- .../com/badlogic/gdx/utils/SortedIntList.java | 131 +- gdx/src/com/badlogic/gdx/utils/TimSort.java | 155 +- gdx/src/com/badlogic/gdx/utils/XmlWriter.java | 4 +- .../gdx/tests/android/AndroidTestStarter.java | 10 +- .../gdx/tests/android/GdxTestActivity.java | 1 + .../gdx/tests/android/MatrixTest.java | 34 +- .../gdx/tests/android/MicroBenchmarks.java | 7 +- .../gdx/tests/android/WindowedTest.java | 28 +- .../gdx/tests/angle/AngleDebugStarter.java | 1 + .../gdx/tests/angle/AngleTestStarter.java | 7 +- .../gdx/tests/jogl/JoglDebugStarter.java | 7 +- .../gdx/tests/jogl/JoglTestStarter.java | 4 +- .../gdx/tests/lwjgl/LocalLwjglTest.java | 97 +- .../gdx/tests/lwjgl/LwjglAppletTest.java | 1 + .../gdx/tests/lwjgl/LwjglDebugStarter.java | 18 +- .../gdx/tests/lwjgl/LwjglTestStarter.java | 4 +- .../badlogic/gdx/tests/AccelerometerTest.java | 23 +- .../gdx/tests/ActionSequenceTest.java | 27 +- .../com/badlogic/gdx/tests/ActionTest.java | 147 +- .../src/com/badlogic/gdx/tests/AlphaTest.java | 13 +- .../com/badlogic/gdx/tests/AnimationTest.java | 54 +- .../badlogic/gdx/tests/AssetManagerTest.java | 42 +- .../badlogic/gdx/tests/AtlasIssueTest.java | 7 +- .../badlogic/gdx/tests/AudioDeviceTest.java | 13 +- .../badlogic/gdx/tests/AudioRecorderTest.java | 19 +- .../gdx/tests/BitmapFontAlignmentTest.java | 13 +- .../gdx/tests/BitmapFontFlipTest.java | 14 +- .../badlogic/gdx/tests/BitmapFontTest.java | 6 +- .../src/com/badlogic/gdx/tests/BobTest.java | 9 +- .../gdx/tests/Box2DInitialOverlapTest.java | 28 +- .../src/com/badlogic/gdx/tests/Box2DTest.java | 124 +- .../gdx/tests/Box2DTestCollection.java | 34 +- .../badlogic/gdx/tests/BufferUtilsTest.java | 319 +- .../com/badlogic/gdx/tests/CompassTest.java | 35 +- .../badlogic/gdx/tests/ComplexActionTest.java | 35 +- .../src/com/badlogic/gdx/tests/CullTest.java | 47 +- .../src/com/badlogic/gdx/tests/DecalTest.java | 51 +- .../com/badlogic/gdx/tests/DeltaTimeTest.java | 18 +- .../src/com/badlogic/gdx/tests/ETC1Test.java | 37 +- .../badlogic/gdx/tests/EdgeDetectionTest.java | 62 +- .../src/com/badlogic/gdx/tests/ExitTest.java | 23 +- .../src/com/badlogic/gdx/tests/FFTTest.java | 1 + .../src/com/badlogic/gdx/tests/FilesTest.java | 9 +- .../com/badlogic/gdx/tests/FillrateTest.java | 36 +- .../gdx/tests/FilterPerformanceTest.java | 38 +- .../gdx/tests/FlickScrollPaneTest.java | 1 - .../src/com/badlogic/gdx/tests/FloatTest.java | 20 +- .../badlogic/gdx/tests/FrameBufferTest.java | 12 +- .../gdx/tests/FramebufferToTextureTest.java | 47 +- .../com/badlogic/gdx/tests/FrustumTest.java | 93 +- .../badlogic/gdx/tests/FullscreenTest.java | 48 +- .../src/com/badlogic/gdx/tests/Gdx2DTest.java | 138 +- .../com/badlogic/gdx/tests/GroupFadeTest.java | 24 +- .../tests/ImmediateModeRendererAlphaTest.java | 125 +- .../gdx/tests/ImmediateModeRendererTest.java | 16 +- .../gdx/tests/IndexBufferObjectClassTest.java | 19 +- .../tests/IndexBufferObjectShaderTest.java | 82 +- .../src/com/badlogic/gdx/tests/InputTest.java | 85 +- .../gdx/tests/IntegerBitmapFontTest.java | 24 +- .../gdx/tests/InverseKinematicsTest.java | 103 +- .../com/badlogic/gdx/tests/IsoCamTest.java | 74 +- .../badlogic/gdx/tests/IsometricTileTest.java | 14 +- .../badlogic/gdx/tests/KinematicBodyTest.java | 4 +- .../com/badlogic/gdx/tests/LifeCycleTest.java | 34 +- .../badlogic/gdx/tests/LineDrawingTest.java | 40 +- .../src/com/badlogic/gdx/tests/MD5Test.java | 43 +- .../com/badlogic/gdx/tests/ManagedTest.java | 14 +- .../badlogic/gdx/tests/ManualBindTest.java | 10 +- .../com/badlogic/gdx/tests/MatrixJNITest.java | 89 +- .../gdx/tests/MeshMultitextureTest.java | 38 +- .../badlogic/gdx/tests/MeshShaderTest.java | 75 +- .../src/com/badlogic/gdx/tests/MeshTest.java | 12 +- .../com/badlogic/gdx/tests/MipMapTest.java | 80 +- .../com/badlogic/gdx/tests/Mpg123Test.java | 7 +- .../gdx/tests/MultiTouchActorTest.java | 82 +- .../badlogic/gdx/tests/MultitouchTest.java | 46 +- .../src/com/badlogic/gdx/tests/MusicTest.java | 56 +- .../badlogic/gdx/tests/MyFirstTriangle.java | 25 +- .../src/com/badlogic/gdx/tests/ObjTest.java | 39 +- .../src/com/badlogic/gdx/tests/OldUITest.java | 50 +- .../gdx/tests/OnscreenKeyboardTest.java | 52 +- .../gdx/tests/OrthoCamBorderTest.java | 6 +- .../com/badlogic/gdx/tests/ParallaxTest.java | 76 +- .../gdx/tests/ParticleEmitterTest.java | 12 +- .../com/badlogic/gdx/tests/PickingTest.java | 60 +- .../badlogic/gdx/tests/PixelsPerInchTest.java | 10 +- .../gdx/tests/PixmapBlendingTest.java | 11 +- .../com/badlogic/gdx/tests/PixmapTest.java | 76 +- .../src/com/badlogic/gdx/tests/Pong.java | 37 +- .../badlogic/gdx/tests/PreferencesTest.java | 20 +- .../com/badlogic/gdx/tests/ProjectTest.java | 52 +- .../gdx/tests/ProjectiveTextureTest.java | 112 +- .../com/badlogic/gdx/tests/RemoteTest.java | 80 +- .../com/badlogic/gdx/tests/RotationTest.java | 18 +- .../badlogic/gdx/tests/ScreenCaptureTest.java | 113 +- .../gdx/tests/ShaderMultitextureTest.java | 48 +- .../badlogic/gdx/tests/ShadowMappingTest.java | 182 +- .../gdx/tests/SimpleAnimationTest.java | 138 +- .../badlogic/gdx/tests/SimpleDecalTest.java | 46 +- .../gdx/tests/SimpleStageCullingTest.java | 104 +- .../com/badlogic/gdx/tests/SimpleTest.java | 43 +- .../src/com/badlogic/gdx/tests/SoundTest.java | 34 +- .../com/badlogic/gdx/tests/SplineTest.java | 84 +- .../gdx/tests/SpriteBatchRotationTest.java | 13 +- .../gdx/tests/SpriteBatchShaderTest.java | 25 +- .../badlogic/gdx/tests/SpriteBatchTest.java | 44 +- .../gdx/tests/SpriteCacheOffsetTest.java | 10 +- .../badlogic/gdx/tests/SpriteCacheTest.java | 38 +- .../gdx/tests/SpritePerformanceTest.java | 5 +- .../gdx/tests/SpritePerformanteTest2.java | 51 +- .../gdx/tests/StagePerformanceTest.java | 71 +- .../src/com/badlogic/gdx/tests/StageTest.java | 51 +- .../com/badlogic/gdx/tests/TerrainTest.java | 14 +- .../gdx/tests/TextInputDialogTest.java | 26 +- .../badlogic/gdx/tests/TextureAtlasTest.java | 3 +- .../badlogic/gdx/tests/TextureDataTest.java | 8 +- .../gdx/tests/TextureDownloadTest.java | 35 +- .../badlogic/gdx/tests/TextureFormatTest.java | 22 +- .../gdx/tests/TexturePackerAtlasTest.java | 1 + .../badlogic/gdx/tests/TextureRenderTest.java | 12 +- .../src/com/badlogic/gdx/tests/TileTest.java | 12 +- .../com/badlogic/gdx/tests/TiledMapTest.java | 38 +- .../gdx/tests/TransformationTest.java | 74 +- .../src/com/badlogic/gdx/tests/UITest.java | 90 +- .../src/com/badlogic/gdx/tests/VBOVATest.java | 15 +- .../gdx/tests/VertexArrayClassTest.java | 16 +- .../badlogic/gdx/tests/VertexArrayTest.java | 10 +- .../tests/VertexBufferObjectClassTest.java | 19 +- .../tests/VertexBufferObjectShaderTest.java | 73 +- .../gdx/tests/VertexBufferObjectTest.java | 10 +- .../com/badlogic/gdx/tests/VibratorTest.java | 19 +- .../com/badlogic/gdx/tests/VorbisTest.java | 7 +- .../com/badlogic/gdx/tests/WaterRipples.java | 34 +- .../badlogic/gdx/tests/box2d/ApplyForce.java | 5 +- .../badlogic/gdx/tests/box2d/BodyTypes.java | 13 +- .../badlogic/gdx/tests/box2d/Box2DTest.java | 77 +- .../com/badlogic/gdx/tests/box2d/Bridge.java | 3 +- .../badlogic/gdx/tests/box2d/Cantilever.java | 3 +- .../com/badlogic/gdx/tests/box2d/Chain.java | 3 +- .../gdx/tests/box2d/CharacterCollision.java | 3 +- .../gdx/tests/box2d/CollisionFiltering.java | 3 +- .../gdx/tests/box2d/ContinuousTest.java | 3 +- .../gdx/tests/box2d/DebugRendererTest.java | 3 +- .../gdx/tests/box2d/OneSidedPlatform.java | 6 +- .../badlogic/gdx/tests/box2d/Prismatic.java | 11 +- .../com/badlogic/gdx/tests/box2d/Pyramid.java | 3 +- .../badlogic/gdx/tests/box2d/SimpleTest.java | 3 +- .../badlogic/gdx/tests/box2d/SphereStack.java | 3 +- .../gdx/tests/box2d/VaryingRestitution.java | 3 +- .../gdx/tests/box2d/VerticalStack.java | 10 +- .../gdx/tests/gles2/HelloTriangle.java | 37 +- .../badlogic/gdx/tests/gles2/MipMap2D.java | 109 +- .../com/badlogic/gdx/tests/gles2/Shapes.java | 158 +- .../gdx/tests/gles2/SimpleVertexShader.java | 39 +- .../com/badlogic/gdx/tests/utils/GdxTest.java | 29 +- .../badlogic/gdx/tests/utils/GdxTests.java | 138 +- .../gdx/tests/utils/OrthoCamController.java | 22 +- .../tests/utils/PerspectiveCamController.java | 75 +- 1005 files changed, 48756 insertions(+), 57890 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 0c130c66b1a..447a9b3754b 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.util.ArrayList; @@ -47,303 +48,291 @@ import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.utils.GdxNativesLoader; -/** - * An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class. In +/** An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class. In * the {@link Activity#onCreate(Bundle)} method call the {@link #initialize(ApplicationListener, boolean)} method specifying the * configuration for the GLSurfaceView. - * - * @author mzechner - */ + * + * @author mzechner */ public class AndroidApplication extends Activity implements Application { - static { - GdxNativesLoader.load(); - } - - protected AndroidGraphics graphics; - protected AndroidInput input; - protected AndroidAudio audio; - protected AndroidFiles files; - protected ApplicationListener listener; - protected Handler handler; - protected boolean firstResume = true; - protected final List runnables = new ArrayList(); - protected WakeLock wakeLock = null; - protected int logLevel = LOG_INFO; - - /** - * This method has to be called in the {@link Activity#onCreate(Bundle)} 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 Graphics#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 Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}. - * - * @param listener the {@link ApplicationListener} implementing the program logic - * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. - */ - public void initialize(ApplicationListener listener, boolean useGL2IfAvailable) { - AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); - config.useGL20 = useGL2IfAvailable; - initialize(listener, config); - } - - - /** - * This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get - * input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0 - * context which can then be used via {@link Graphics#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 Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields - * in the {@link AndroidApplicationConfiguration} instance. - * - * @param listener the {@link ApplicationListener} implementing the program logic - * @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer, etc.). - */ - public void initialize(ApplicationListener listener, AndroidApplicationConfiguration config) { - graphics = new AndroidGraphics(this, config, config.resolutionStrategy==null?new FillResolutionStrategy():config.resolutionStrategy); - input = new AndroidInput(this, graphics.view, config); - audio = new AndroidAudio(this); - files = new AndroidFiles(this.getAssets()); - this.listener = listener; - this.handler = new Handler(); - - Gdx.app = this; - Gdx.input = this.getInput(); - Gdx.audio = this.getAudio(); - Gdx.files = this.getFiles(); - Gdx.graphics = this.getGraphics(); - - try { - requestWindowFeature(Window.FEATURE_NO_TITLE); - } catch(Exception ex) { - log("AndroidApplication", "Content already displayed, cannot request FEATURE_NO_TITLE", ex); - } - getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); - getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); - setContentView(graphics.getView(), createLayoutParams()); - createWakeLock(config); - } - - protected FrameLayout.LayoutParams createLayoutParams() { - FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.FILL_PARENT); - layoutParams.gravity = Gravity.CENTER; - return layoutParams; - } - - protected void createWakeLock(AndroidApplicationConfiguration config) { - if(config.useWakelock) { - PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE); - wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "libgdx wakelock"); - } - } - - /** - * This method has to be called in the {@link Activity#onCreate(Bundle)} 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 Graphics#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 Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}. - *

- * Note: you have to add the returned view to your layout! - * - * @param listener the {@link ApplicationListener} implementing the program logic - * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. - * @return the GLSurfaceView of the application - */ - public View initializeForView(ApplicationListener listener, boolean useGL2IfAvailable) { - AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); - config.useGL20 = useGL2IfAvailable; - return initializeForView(listener, config); - } - - /** - * This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get - * input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0 - * context which can then be used via {@link Graphics#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 Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields - * in the {@link AndroidApplicationConfiguration} instance. - *

- * Note: you have to add the returned view to your layout! - * - * @param listener the {@link ApplicationListener} implementing the program logic - * @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer, etc.). - * @return the GLSurfaceView of the application - */ - public View initializeForView(ApplicationListener listener, AndroidApplicationConfiguration config) { - graphics = new AndroidGraphics(this, config, config.resolutionStrategy==null?new FillResolutionStrategy():config.resolutionStrategy); - input = new AndroidInput(this, graphics.view, config); - audio = new AndroidAudio(this); - files = new AndroidFiles(this.getAssets()); - this.listener = listener; - this.handler = new Handler(); - - Gdx.app = this; - Gdx.input = this.getInput(); - Gdx.audio = this.getAudio(); - Gdx.files = this.getFiles(); - Gdx.graphics = this.getGraphics(); - - createWakeLock(config); - return graphics.getView(); - } - - @Override - protected void onPause() { - if(wakeLock != null) wakeLock.release(); - graphics.pause(); - - input.unregisterSensorListeners(); - // erase pointer ids. this sucks donkeyballs... - int[] realId = input.realId; - for(int i = 0; i < realId.length; i++) realId[i] = -1; - - if (isFinishing()) { - graphics.clearManagedCaches(); - graphics.destroy(); - } - - 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(); - } - - super.onPause(); - } - - @Override - protected void onResume() { - if(wakeLock != null) wakeLock.acquire(); - Gdx.app = this; - Gdx.input = this.getInput(); - Gdx.audio = this.getAudio(); - Gdx.files = this.getFiles(); - Gdx.graphics = this.getGraphics(); - - ((AndroidInput)getInput()).registerSensorListeners(); - if (audio != null) audio.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 (!firstResume) - graphics.resume(); - else - firstResume = false; - super.onResume(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - } - - /** - * {@inheritDoc} - */ - @Override - public Audio getAudio() { - return audio; - } - - /** - * {@inheritDoc} - */ - @Override - public Files getFiles() { - return files; - } - - /** - * {@inheritDoc} - */ - @Override - public Graphics getGraphics() { - return graphics; - } - - /** - * {@inheritDoc} - */ - @Override - public Input getInput() { - return input; - } - - /** - * {@inheritDoc} - */ - @Override - public ApplicationType getType() { - return ApplicationType.Android; - } - - /** - * {@inheritDoc} - */ - @Override - public int getVersion() { - return Integer.parseInt(android.os.Build.VERSION.SDK); - } - - @Override - public long getJavaHeap() { - return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); - } - - @Override - public long getNativeHeap() { - return Debug.getNativeHeapAllocatedSize(); - } - - @Override public Preferences getPreferences (String name) { + static { + GdxNativesLoader.load(); + } + + protected AndroidGraphics graphics; + protected AndroidInput input; + protected AndroidAudio audio; + protected AndroidFiles files; + protected ApplicationListener listener; + protected Handler handler; + protected boolean firstResume = true; + protected final List runnables = new ArrayList(); + protected WakeLock wakeLock = null; + protected int logLevel = LOG_INFO; + + /** This method has to be called in the {@link Activity#onCreate(Bundle)} 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 Graphics#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 Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}. + * + * @param listener the {@link ApplicationListener} implementing the program logic + * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. */ + public void initialize (ApplicationListener listener, boolean useGL2IfAvailable) { + AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); + config.useGL20 = useGL2IfAvailable; + initialize(listener, config); + } + + /** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get + * input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0 + * context which can then be used via {@link Graphics#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 Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields in + * the {@link AndroidApplicationConfiguration} instance. + * + * @param listener the {@link ApplicationListener} implementing the program logic + * @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer, + * etc.). */ + public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) { + graphics = new AndroidGraphics(this, config, config.resolutionStrategy == null ? new FillResolutionStrategy() + : config.resolutionStrategy); + input = new AndroidInput(this, graphics.view, config); + audio = new AndroidAudio(this); + files = new AndroidFiles(this.getAssets()); + this.listener = listener; + this.handler = new Handler(); + + Gdx.app = this; + Gdx.input = this.getInput(); + Gdx.audio = this.getAudio(); + Gdx.files = this.getFiles(); + Gdx.graphics = this.getGraphics(); + + try { + requestWindowFeature(Window.FEATURE_NO_TITLE); + } catch (Exception ex) { + log("AndroidApplication", "Content already displayed, cannot request FEATURE_NO_TITLE", ex); + } + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); + setContentView(graphics.getView(), createLayoutParams()); + createWakeLock(config); + } + + protected FrameLayout.LayoutParams createLayoutParams () { + FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, + android.view.ViewGroup.LayoutParams.FILL_PARENT); + layoutParams.gravity = Gravity.CENTER; + return layoutParams; + } + + protected void createWakeLock (AndroidApplicationConfiguration config) { + if (config.useWakelock) { + PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE); + wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "libgdx wakelock"); + } + } + + /** This method has to be called in the {@link Activity#onCreate(Bundle)} 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 Graphics#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 Graphics#isGL20Available()} method. Uses a default {@link AndroidApplicationConfiguration}. + *

+ * Note: you have to add the returned view to your layout! + * + * @param listener the {@link ApplicationListener} implementing the program logic + * @param useGL2IfAvailable whether to use OpenGL ES 2.0 if its available. + * @return the GLSurfaceView of the application */ + public View initializeForView (ApplicationListener listener, boolean useGL2IfAvailable) { + AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); + config.useGL20 = useGL2IfAvailable; + return initializeForView(listener, config); + } + + /** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get + * input, render via OpenGL and so on. If config.useGL20 is set the AndroidApplication will try to create an OpenGL ES 2.0 + * context which can then be used via {@link Graphics#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 Graphics#isGL20Available()} method. You can configure other aspects of the application with the rest of the fields in + * the {@link AndroidApplicationConfiguration} instance. + *

+ * Note: you have to add the returned view to your layout! + * + * @param listener the {@link ApplicationListener} implementing the program logic + * @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer, + * etc.). + * @return the GLSurfaceView of the application */ + public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) { + graphics = new AndroidGraphics(this, config, config.resolutionStrategy == null ? new FillResolutionStrategy() + : config.resolutionStrategy); + input = new AndroidInput(this, graphics.view, config); + audio = new AndroidAudio(this); + files = new AndroidFiles(this.getAssets()); + this.listener = listener; + this.handler = new Handler(); + + Gdx.app = this; + Gdx.input = this.getInput(); + Gdx.audio = this.getAudio(); + Gdx.files = this.getFiles(); + Gdx.graphics = this.getGraphics(); + + createWakeLock(config); + return graphics.getView(); + } + + @Override + protected void onPause () { + if (wakeLock != null) wakeLock.release(); + graphics.pause(); + + input.unregisterSensorListeners(); + // erase pointer ids. this sucks donkeyballs... + int[] realId = input.realId; + for (int i = 0; i < realId.length; i++) + realId[i] = -1; + + if (isFinishing()) { + graphics.clearManagedCaches(); + graphics.destroy(); + } + + 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(); + } + + super.onPause(); + } + + @Override + protected void onResume () { + if (wakeLock != null) wakeLock.acquire(); + Gdx.app = this; + Gdx.input = this.getInput(); + Gdx.audio = this.getAudio(); + Gdx.files = this.getFiles(); + Gdx.graphics = this.getGraphics(); + + ((AndroidInput)getInput()).registerSensorListeners(); + if (audio != null) audio.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 (!firstResume) + graphics.resume(); + else + firstResume = false; + super.onResume(); + } + + @Override + protected void onDestroy () { + super.onDestroy(); + } + + /** {@inheritDoc} */ + @Override + public Audio getAudio () { + return audio; + } + + /** {@inheritDoc} */ + @Override + public Files getFiles () { + return files; + } + + /** {@inheritDoc} */ + @Override + public Graphics getGraphics () { + return graphics; + } + + /** {@inheritDoc} */ + @Override + public Input getInput () { + return input; + } + + /** {@inheritDoc} */ + @Override + public ApplicationType getType () { + return ApplicationType.Android; + } + + /** {@inheritDoc} */ + @Override + public int getVersion () { + return Integer.parseInt(android.os.Build.VERSION.SDK); + } + + @Override + public long getJavaHeap () { + return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); + } + + @Override + public long getNativeHeap () { + return Debug.getNativeHeapAllocatedSize(); + } + + @Override + public Preferences getPreferences (String name) { return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE)); } - @Override public void postRunnable (Runnable runnable) { - synchronized(runnables) { + @Override + public void postRunnable (Runnable runnable) { + synchronized (runnables) { runnables.add(runnable); } } - - @Override public void onConfigurationChanged(Configuration config) { + + @Override + public void onConfigurationChanged (Configuration config) { super.onConfigurationChanged(config); boolean keyboardAvailable = false; - if(config.keyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true; + if (config.keyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true; input.keyboardAvailable = keyboardAvailable; } - @Override public void exit () { + @Override + public void exit () { handler.post(new Runnable() { - @Override public void run () { - AndroidApplication.this.finish(); - } + @Override + public void run () { + AndroidApplication.this.finish(); + } }); } - - @Override - public void log(String tag, String message) { - if(logLevel >= LOG_INFO) Log.i(tag, message); - } - - @Override public void log (String tag, String message, Exception exception) { - if(logLevel >= LOG_INFO) Log.i(tag, message, exception); - } - - @Override public void error (String tag, String message) { - if(logLevel >= LOG_ERROR) Log.e(tag, message); + + @Override + public void log (String tag, String message) { + if (logLevel >= LOG_INFO) Log.i(tag, message); } + @Override + public void log (String tag, String message, Exception exception) { + if (logLevel >= LOG_INFO) Log.i(tag, message, exception); + } - @Override public void error (String tag, String message, Exception exception) { - if(logLevel >= LOG_ERROR) Log.e(tag, message, exception); + @Override + public void error (String tag, String message) { + if (logLevel >= LOG_ERROR) Log.e(tag, message); } + @Override + public void error (String tag, String message, Exception exception) { + if (logLevel >= LOG_ERROR) Log.e(tag, message, exception); + } - @Override public void setLogLevel (int logLevel) { + @Override + public void setLogLevel (int logLevel) { this.logLevel = logLevel; } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplicationConfiguration.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplicationConfiguration.java index a7670c5d2b1..6dbe477ac23 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplicationConfiguration.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplicationConfiguration.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.android; import android.os.PowerManager.WakeLock; @@ -5,40 +6,36 @@ import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy; import com.badlogic.gdx.backends.android.surfaceview.ResolutionStrategy; -/** - * Class defining the configuration of an {@link AndroidApplication}. Allows you - * to disable the use of the accelerometer to save battery among other things. - * @author mzechner - * - */ +/** Class defining the configuration of an {@link AndroidApplication}. Allows you to disable the use of the accelerometer to save + * battery among other things. + * @author mzechner */ public class AndroidApplicationConfiguration { /** whether to use OpenGL ES 2.0 or not. default: false **/ public boolean useGL20 = false; - + /** number of bits per color channel **/ public int r = 5, g = 6, b = 5, a = 0; - + /** number of bits for depth and stencil buffer **/ - public int depth = 16, stencil = 0; - + public int depth = 16, stencil = 0; + /** number of samples for CSAA/MSAA, 2 is a good value **/ public int numSamples = 0; - + /** whether to use the accelerometer. default: true **/ public boolean useAccelerometer = true; - + /** whether to use the compass. default: true **/ - public boolean useCompass = true; - - /** the time in milliseconds to sleep after each event in the touch handler, set this - * to 16ms to get rid of touch flooding on pre Android 2.0 devices. default: 0 **/ + public boolean useCompass = true; + + /** the time in milliseconds to sleep after each event in the touch handler, set this to 16ms to get rid of touch flooding on + * pre Android 2.0 devices. default: 0 **/ public int touchSleepTime = 0; - - /** whether to use a {@link WakeLock} or not. In case this is true you have to - * add the permission "android.permission.WAKE_LOCK" to your manifest file. default: false - */ + + /** whether to use a {@link WakeLock} or not. In case this is true you have to add the permission "android.permission.WAKE_LOCK" + * to your manifest file. default: false */ public boolean useWakelock = false; - + /** the {@link ResolutionStrategy}. default: {@link FillResolutionStrategy} **/ public ResolutionStrategy resolutionStrategy = new FillResolutionStrategy(); } 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 2d81bf7432a..4a1a9fcb2ab 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.io.IOException; @@ -35,12 +36,9 @@ import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * An implementation of the {@link Audio} interface for Android. - * - * @author mzechner +/** An implementation of the {@link Audio} interface for Android. * - */ + * @author mzechner */ public final class AndroidAudio implements Audio { private SoundPool soundPool; private final AudioManager manager; @@ -54,7 +52,7 @@ public AndroidAudio (Activity context) { } protected void pause () { - synchronized(musics) { + synchronized (musics) { wasPlaying.clear(); for (AndroidMusic music : musics) { if (music.isPlaying()) { @@ -67,24 +65,22 @@ protected void pause () { } protected void resume () { - synchronized(musics) { + synchronized (musics) { for (int i = 0; i < musics.size(); i++) { if (wasPlaying.get(i)) musics.get(i).play(); } } } - /** - * {@inheritDoc} - */ - @Override public AudioDevice newAudioDevice (int samplingRate, boolean isMono) { + /** {@inheritDoc} */ + @Override + public AudioDevice newAudioDevice (int samplingRate, boolean isMono) { return new AndroidAudioDevice(samplingRate, isMono); } - /** - * {@inheritDoc} - */ - @Override public Music newMusic (FileHandle file) { + /** {@inheritDoc} */ + @Override + public Music newMusic (FileHandle file) { AndroidFileHandle aHandle = (AndroidFileHandle)file; MediaPlayer mediaPlayer = new MediaPlayer(); @@ -96,7 +92,7 @@ protected void resume () { descriptor.close(); mediaPlayer.prepare(); AndroidMusic music = new AndroidMusic(this, mediaPlayer); - synchronized(musics) { + synchronized (musics) { musics.add(music); } return music; @@ -109,7 +105,7 @@ protected void resume () { mediaPlayer.setDataSource(aHandle.path()); mediaPlayer.prepare(); AndroidMusic music = new AndroidMusic(this, mediaPlayer); - synchronized(musics) { + synchronized (musics) { musics.add(music); } return music; @@ -120,10 +116,9 @@ protected void resume () { } - /** - * {@inheritDoc} - */ - @Override public Sound newSound (FileHandle file) { + /** {@inheritDoc} */ + @Override + public Sound newSound (FileHandle file) { AndroidFileHandle aHandle = (AndroidFileHandle)file; if (aHandle.type() == FileType.Internal) { try { @@ -144,23 +139,20 @@ protected void resume () { } } - /** - * {@inheritDoc} - */ - @Override public AudioRecorder newAudioRecoder (int samplingRate, boolean isMono) { + /** {@inheritDoc} */ + @Override + public AudioRecorder newAudioRecoder (int samplingRate, boolean isMono) { return new AndroidAudioRecorder(samplingRate, isMono); } - /** - * Kills the soundpool and all other resources - */ + /** Kills the soundpool and all other resources */ public void dispose () { - synchronized(musics) { + synchronized (musics) { // gah i hate myself.... music.dispose() removes the music from the list... ArrayList musicsCopy = new ArrayList(musics); for (AndroidMusic music : musicsCopy) { music.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 0c0483f3b9b..aec6ea0a765 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.media.AudioFormat; @@ -21,12 +22,9 @@ 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 - * - */ + * @author mzechner */ class AndroidAudioDevice implements AudioDevice { /** the audio track **/ private final AudioTrack track; @@ -36,7 +34,7 @@ class AndroidAudioDevice implements AudioDevice { /** whether this device is in mono or stereo mode **/ private final boolean isMono; - + /** the latency in samples **/ private final int latency; @@ -47,25 +45,29 @@ class AndroidAudioDevice implements AudioDevice { track = new AudioTrack(AudioManager.STREAM_MUSIC, samplingRate, isMono ? AudioFormat.CHANNEL_CONFIGURATION_MONO : AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, minSize, AudioTrack.MODE_STREAM); track.play(); - latency = minSize / (isMono?1:2); + latency = minSize / (isMono ? 1 : 2); } - @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) { + @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) { + @Override + public void writeSamples (float[] samples, int offset, int numSamples) { if (buffer.length < samples.length) buffer = new short[samples.length]; int bound = offset + numSamples; @@ -82,7 +84,8 @@ class AndroidAudioDevice implements AudioDevice { writtenSamples += track.write(buffer, writtenSamples, numSamples - writtenSamples); } - @Override public int getLatency () { + @Override + public int getLatency () { return latency; } } 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 2ae89b0d4d9..0d1ab2a7f9d 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.media.AudioFormat; @@ -21,11 +22,8 @@ import com.badlogic.gdx.audio.AudioRecorder; -/** - * {@link AudioRecorder} implementation for the android system based on AudioRecord - * @author badlogicgames@gmail.com - * - */ +/** {@link AudioRecorder} implementation for the android system based on AudioRecord + * @author badlogicgames@gmail.com */ public class AndroidAudioRecorder implements AudioRecorder { /** the audio track we read samples from **/ private AudioRecord recorder; @@ -38,12 +36,14 @@ public AndroidAudioRecorder (int samplingRate, boolean isMono) { 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); 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 62d0421d045..c283ec1e7ea 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 @@ -26,10 +26,8 @@ import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * @author mzechner - * @author Nathan Sweet - */ +/** @author mzechner + * @author Nathan Sweet */ public class AndroidFileHandle extends FileHandle { // The asset manager, or null if this is not an internal file. final AssetManager assets; 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 3d6b686a6ac..ec65cd20bc0 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 @@ -13,6 +13,7 @@ * 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; @@ -21,10 +22,8 @@ import com.badlogic.gdx.Files; import com.badlogic.gdx.files.FileHandle; -/** - * @author mzechner - * @author Nathan Sweet - */ +/** @author mzechner + * @author Nathan Sweet */ public class AndroidFiles implements Files { protected final String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; protected final AssetManager assets; @@ -33,31 +32,38 @@ public AndroidFiles (AssetManager assets) { this.assets = assets; } - @Override public FileHandle getFileHandle (String path, FileType type) { + @Override + public FileHandle getFileHandle (String path, FileType type) { return new AndroidFileHandle(type == FileType.Internal ? assets : null, path, type); } - @Override public FileHandle classpath (String path) { + @Override + public FileHandle classpath (String path) { return new AndroidFileHandle(null, path, FileType.Classpath); } - @Override public FileHandle internal (String path) { + @Override + public FileHandle internal (String path) { return new AndroidFileHandle(assets, path, FileType.Internal); } - @Override public FileHandle external (String path) { + @Override + public FileHandle external (String path) { return new AndroidFileHandle(null, path, FileType.External); } - @Override public FileHandle absolute (String path) { + @Override + public FileHandle absolute (String path) { return new AndroidFileHandle(null, path, FileType.Absolute); } - @Override public String getExternalStoragePath () { + @Override + public String getExternalStoragePath () { return sdcard; } - @Override public boolean isExternalStorageAvailable () { + @Override + public boolean isExternalStorageAvailable () { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } } 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 963d3c0824c..7fbbcf6463c 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 @@ -13,6 +13,7 @@ * 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,11 +22,8 @@ import com.badlogic.gdx.graphics.GL10; -/** - * An implementation of the {@link GL10} interface for Android. - * @author mzechner - * - */ +/** An implementation of the {@link GL10} interface for Android. + * @author mzechner */ class AndroidGL10 implements GL10 { final javax.microedition.khronos.opengles.GL10 gl; @@ -33,361 +31,447 @@ public AndroidGL10 (javax.microedition.khronos.opengles.GL10 gl) { this.gl = gl; } - @Override public final void glActiveTexture (int texture) { + @Override + public final void glActiveTexture (int texture) { gl.glActiveTexture(texture); } - @Override public final void glAlphaFunc (int func, float ref) { + @Override + public final void glAlphaFunc (int func, float ref) { gl.glAlphaFunc(func, ref); } - @Override public final void glBindTexture (int target, int texture) { + @Override + public final void glBindTexture (int target, int texture) { gl.glBindTexture(target, texture); } - @Override public final void glBlendFunc (int sfactor, int dfactor) { + @Override + public final void glBlendFunc (int sfactor, int dfactor) { gl.glBlendFunc(sfactor, dfactor); } - @Override public final void glClear (int mask) { + @Override + public final void glClear (int mask) { gl.glClear(mask); } - @Override public final void glClearColor (float red, float green, float blue, float alpha) { + @Override + public final void glClearColor (float red, float green, float blue, float alpha) { gl.glClearColor(red, green, blue, alpha); } - @Override public final void glClearDepthf (float depth) { + @Override + public final void glClearDepthf (float depth) { gl.glClearDepthf(depth); } - @Override public final void glClearStencil (int 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) { gl.glClientActiveTexture(texture); } - @Override public final void glColor4f (float red, float green, float blue, float alpha) { + @Override + public final void glColor4f (float red, float green, float blue, float alpha) { gl.glColor4f(red, green, blue, alpha); } - @Override public final void glColorMask (boolean red, boolean green, boolean blue, boolean 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) { + @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) { + @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, + @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) { + @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) { + @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) { + @Override + public final void glCullFace (int mode) { gl.glCullFace(mode); } - @Override public final void glDeleteTextures (int n, IntBuffer textures) { + @Override + public final void glDeleteTextures (int n, IntBuffer textures) { gl.glDeleteTextures(n, textures); } - @Override public final void glDepthFunc (int func) { + @Override + public final void glDepthFunc (int func) { gl.glDepthFunc(func); } - @Override public final void glDepthMask (boolean flag) { + @Override + public final void glDepthMask (boolean flag) { gl.glDepthMask(flag); } - @Override public final void glDepthRangef (float zNear, float zFar) { + @Override + public final void glDepthRangef (float zNear, float zFar) { gl.glDepthRangef(zNear, zFar); } - @Override public final void glDisable (int cap) { + @Override + public final void glDisable (int cap) { gl.glDisable(cap); } - @Override public final void glDisableClientState (int array) { + @Override + public final void glDisableClientState (int array) { gl.glDisableClientState(array); } - @Override public final void glDrawArrays (int mode, int first, int 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) { + @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) { + @Override + public final void glEnable (int cap) { gl.glEnable(cap); } - @Override public final void glEnableClientState (int 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) { + @Override + public final void glFogf (int pname, float param) { gl.glFogf(pname, param); } - @Override public final void glFogfv (int pname, FloatBuffer params) { + @Override + public final void glFogfv (int pname, FloatBuffer params) { gl.glFogfv(pname, params); } - @Override public final void glFrontFace (int 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) { + @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 glGenTextures (int n, IntBuffer 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) { + @Override + public final void glGetIntegerv (int pname, IntBuffer params) { gl.glGetIntegerv(pname, params); } - @Override public final String glGetString (int name) { + @Override + public final String glGetString (int name) { return gl.glGetString(name); } - @Override public final void glHint (int target, int mode) { + @Override + public final void glHint (int target, int mode) { gl.glHint(target, mode); } - @Override public final void glLightModelf (int pname, float param) { + @Override + public final void glLightModelf (int pname, float param) { gl.glLightModelf(pname, param); } - @Override public final void glLightModelfv (int pname, FloatBuffer params) { + @Override + public final void glLightModelfv (int pname, FloatBuffer params) { gl.glLightModelfv(pname, params); } - @Override public final void glLightf (int light, int pname, float 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) { + @Override + public final void glLightfv (int light, int pname, FloatBuffer params) { gl.glLightfv(light, pname, params); } - @Override public final void glLineWidth (float width) { + @Override + public final void glLineWidth (float width) { gl.glLineWidth(width); } - @Override public final void glLoadIdentity () { + @Override + public final void glLoadIdentity () { gl.glLoadIdentity(); } - @Override public final void glLoadMatrixf (FloatBuffer m) { + @Override + public final void glLoadMatrixf (FloatBuffer m) { gl.glLoadMatrixf(m); } - @Override public final void glLogicOp (int opcode) { + @Override + public final void glLogicOp (int opcode) { gl.glLogicOp(opcode); } - @Override public final void glMaterialf (int face, int pname, float 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) { + @Override + public final void glMaterialfv (int face, int pname, FloatBuffer params) { gl.glMaterialfv(face, pname, params); } - @Override public final void glMatrixMode (int mode) { + @Override + public final void glMatrixMode (int mode) { gl.glMatrixMode(mode); } - @Override public final void glMultMatrixf (FloatBuffer m) { + @Override + public final void glMultMatrixf (FloatBuffer m) { gl.glMultMatrixf(m); } - @Override public final void glMultiTexCoord4f (int target, float s, float t, float r, float 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 glNormal3f (float nx, float ny, float nz) { + @Override + public final void glNormal3f (float nx, float ny, float nz) { gl.glNormal3f(nx, ny, nz); } - @Override public final void glNormalPointer (int type, int stride, Buffer 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) { + @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 glPixelStorei (int pname, int param) { + @Override + public final void glPixelStorei (int pname, int param) { gl.glPixelStorei(pname, param); } - @Override public final void glPointSize (float size) { + @Override + public final void glPointSize (float size) { gl.glPointSize(size); } - @Override public final void glPolygonOffset (float factor, float units) { + @Override + public final void glPolygonOffset (float factor, float units) { gl.glPolygonOffset(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) { + @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) { + @Override + public final void glRotatef (float angle, float x, float y, float z) { gl.glRotatef(angle, x, y, z); } - @Override public final void glSampleCoverage (float value, boolean invert) { + @Override + public final void glSampleCoverage (float value, boolean invert) { gl.glSampleCoverage(value, invert); } - @Override public final void glScalef (float x, float y, float z) { + @Override + public final void glScalef (float x, float y, float z) { gl.glScalef(x, y, z); } - @Override public final void glScissor (int x, int y, int width, int 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) { + @Override + public final void glStencilFunc (int func, int ref, int mask) { gl.glStencilFunc(func, ref, mask); } - @Override public final void glStencilMask (int mask) { + @Override + public final void glStencilMask (int mask) { gl.glStencilMask(mask); } - @Override public final void glStencilOp (int fail, int zfail, int 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) { + @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) { + @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) { + @Override + public final void glTexEnvfv (int target, int pname, FloatBuffer params) { gl.glTexEnvfv(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) { + @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) { + @Override + public final void glTexParameterf (int target, int pname, float param) { gl.glTexParameterf(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) { + @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) { + @Override + public final void glTranslatef (float x, float y, float z) { gl.glTranslatef(x, y, z); } - @Override public final void glVertexPointer (int size, int type, int stride, Buffer 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) { + @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) { + @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) { + @Override + public final void glFogfv (int pname, float[] params, int offset) { gl.glFogfv(pname, params, offset); } - @Override public final void glGenTextures (int n, int[] textures, int 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) { + @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) { + @Override + public final void glLightModelfv (int pname, float[] params, int offset) { gl.glLightModelfv(pname, params, offset); } - @Override public final void glLightfv (int light, int pname, float[] params, int offset) { + @Override + public final void glLightfv (int light, int pname, float[] params, int offset) { gl.glLightfv(light, pname, params, offset); } - @Override public final void glLoadMatrixf (float[] m, int offset) { + @Override + public final void glLoadMatrixf (float[] m, int offset) { gl.glLoadMatrixf(m, offset); } - @Override public final void glMaterialfv (int face, int pname, float[] params, int offset) { + @Override + public final void glMaterialfv (int face, int pname, float[] params, int offset) { gl.glMaterialfv(face, pname, params, offset); } - @Override public final void glMultMatrixf (float[] m, int offset) { + @Override + public final void glMultMatrixf (float[] m, int offset) { gl.glMultMatrixf(m, offset); } - @Override public final void glTexEnvfv (int target, int pname, float[] params, int offset) { + @Override + public final void glTexEnvfv (int target, int pname, float[] params, int offset) { gl.glTexEnvfv(target, pname, params, offset); } - @Override public void glPolygonMode (int face, int mode) { + @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 d023f99c53f..441ac9baed6 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.nio.Buffer; @@ -23,12 +24,9 @@ import com.badlogic.gdx.graphics.GL11; -/** - * An implementation of the {@link GL11} interface for Android - * - * @author mzechner +/** An implementation of the {@link GL11} interface for Android * - */ + * @author mzechner */ final class AndroidGL11 extends AndroidGL10 implements GL11 { private final javax.microedition.khronos.opengles.GL11 gl; @@ -37,199 +35,248 @@ public AndroidGL11 (GL10 gl) { this.gl = (javax.microedition.khronos.opengles.GL11)gl; } - @Override public void glBindBuffer (int target, int 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) { + @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) { + @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) { + @Override + public void glClipPlanef (int plane, FloatBuffer equation) { gl.glClipPlanef(plane, equation); } - @Override public void glColor4ub (byte red, byte green, byte blue, byte 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) { + @Override + public void glDeleteBuffers (int n, IntBuffer buffers) { gl.glDeleteBuffers(n, buffers); } - @Override public void glGenBuffers (int n, IntBuffer buffers) { + @Override + public void glGenBuffers (int n, IntBuffer buffers) { gl.glGenBuffers(n, buffers); } - @Override public void glGetBooleanv (int pname, IntBuffer params) { + @Override + public void glGetBooleanv (int pname, IntBuffer params) { gl.glGetBooleanv(pname, params); } - @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + @Override + public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { gl.glGetBufferParameteriv(target, pname, params); } - @Override public void glGetClipPlanef (int pname, FloatBuffer eqn) { + @Override + public void glGetClipPlanef (int pname, FloatBuffer eqn) { gl.glGetClipPlanef(pname, eqn); } - @Override public void glGetFloatv (int pname, FloatBuffer params) { + @Override + public void glGetFloatv (int pname, FloatBuffer params) { gl.glGetFloatv(pname, params); } - @Override public void glGetLightfv (int light, int pname, FloatBuffer params) { + @Override + public void glGetLightfv (int light, int pname, FloatBuffer params) { gl.glGetLightfv(light, pname, params); } - @Override public void glGetMaterialfv (int face, int pname, FloatBuffer params) { + @Override + public void glGetMaterialfv (int face, int pname, FloatBuffer params) { gl.glGetMaterialfv(face, pname, params); } - @Override public void glGetPointerv (int pname, Buffer[] params) { + @Override + public void glGetPointerv (int pname, Buffer[] params) { gl.glGetPointerv(pname, params); } - @Override public void glGetTexEnviv (int env, int pname, IntBuffer params) { + @Override + public void glGetTexEnviv (int env, int pname, IntBuffer params) { gl.glGetTexEnviv(env, pname, params); } - @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer 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) { + @Override + public void glGetTexParameteriv (int target, int pname, IntBuffer params) { gl.glGetTexParameteriv(target, pname, params); } - @Override public boolean glIsBuffer (int buffer) { + @Override + public boolean glIsBuffer (int buffer) { return gl.glIsBuffer(buffer); } - @Override public boolean glIsEnabled (int cap) { + @Override + public boolean glIsEnabled (int cap) { return gl.glIsEnabled(cap); } - @Override public boolean glIsTexture (int texture) { + @Override + public boolean glIsTexture (int texture) { return gl.glIsTexture(texture); } - @Override public void glPointParameterf (int pname, float param) { + @Override + public void glPointParameterf (int pname, float param) { gl.glPointParameterf(pname, param); } - @Override public void glPointParameterfv (int pname, FloatBuffer params) { + @Override + public void glPointParameterfv (int pname, FloatBuffer params) { gl.glPointParameterfv(pname, params); } - @Override public void glPointSizePointerOES (int type, int stride, Buffer 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) { + @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) { + @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) { + @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) { + @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) { + @Override + public void glTexParameteriv (int target, int pname, IntBuffer params) { gl.glTexParameteriv(target, pname, params); } - @Override public void glClipPlanef (int plane, float[] equation, int offset) { + @Override + public void glClipPlanef (int plane, float[] equation, int offset) { gl.glClipPlanef(plane, equation, offset); } - @Override public void glDeleteBuffers (int n, int[] buffers, int 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) { + @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) { + @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) { + @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) { + @Override + public void glGetClipPlanef (int pname, float[] eqn, int offset) { gl.glGetClipPlanef(pname, eqn, offset); } - @Override public void glGetFloatv (int pname, float[] params, int 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) { + @Override + public void glGetLightfv (int light, int pname, float[] params, int offset) { gl.glGetLightfv(light, pname, params, offset); } - @Override public void glGetMaterialfv (int face, int pname, float[] params, int offset) { + @Override + public void glGetMaterialfv (int face, int pname, float[] params, int offset) { gl.glGetMaterialfv(face, pname, params, offset); } - @Override public void glGetTexEnviv (int env, int pname, int[] params, int offset) { + @Override + public void glGetTexEnviv (int env, int pname, int[] params, int offset) { gl.glGetTexEnviv(env, pname, params, offset); } - @Override public void glGetTexParameterfv (int target, int pname, float[] params, int 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) { + @Override + public void glGetTexParameteriv (int target, int pname, int[] params, int offset) { gl.glGetTexParameteriv(target, pname, params, offset); } - @Override public void glPointParameterfv (int pname, float[] params, int offset) { + @Override + public void glPointParameterfv (int pname, float[] params, int offset) { gl.glPointParameterfv(pname, params, offset); } - @Override public void glTexEnviv (int target, int pname, int[] params, int 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) { + @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) { + @Override + public void glTexParameteriv (int target, int pname, int[] params, int offset) { gl.glTexParameteriv(target, pname, params, offset); } - @Override public void glColorPointer (int size, int type, int stride, int 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) { + @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) { + @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) { + @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) { + @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 6b6f2b800e6..6c796a68263 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.nio.Buffer; diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGLU.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGLU.java index f2f2eecd072..bea7c5f7b65 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGLU.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidGLU.java @@ -13,35 +13,43 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GLU; -public class AndroidGLU implements GLU { - - @Override public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, - float upX, float upY, float upZ) { +public class AndroidGLU implements GLU { + + @Override + public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, + float upY, float upZ) { android.opengl.GLU.gluLookAt(((AndroidGL10)gl).gl, eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } - @Override public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { + @Override + public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { android.opengl.GLU.gluOrtho2D(((AndroidGL10)gl).gl, left, right, bottom, top); } - @Override public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { + @Override + public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { android.opengl.GLU.gluPerspective(((AndroidGL10)gl).gl, fovy, aspect, zNear, zFar); } - @Override public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] win, int winOffset) { - int result = android.opengl.GLU.gluProject(objX, objY, objZ, model, modelOffset, project, projectOffset, view, viewOffset, win, winOffset); + int result = android.opengl.GLU.gluProject(objX, objY, objZ, model, modelOffset, project, projectOffset, view, viewOffset, + win, winOffset); return result == GL10.GL_TRUE; } - @Override public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] obj, int objOffset) { - int result = android.opengl.GLU.gluUnProject(winX, winY, winZ, model, modelOffset, project, projectOffset, view, viewOffset, obj, objOffset); + int result = android.opengl.GLU.gluUnProject(winX, winY, winZ, model, modelOffset, project, projectOffset, view, + viewOffset, obj, objOffset); return result == GL10.GL_TRUE; } 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 b8b4e58bd72..a33217076da 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 @@ -47,11 +47,9 @@ import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.WindowedMean; -/** - * An implementation of {@link Graphics} for Android. +/** An implementation of {@link Graphics} for Android. * - * @author mzechner - */ + * @author mzechner */ public final class AndroidGraphics implements Graphics, Renderer { final View view; int width; @@ -86,7 +84,8 @@ public final class AndroidGraphics implements Graphics, Renderer { private final AndroidApplicationConfiguration config; private BufferFormat bufferFormat = new BufferFormat(5, 6, 5, 0, 16, 0, 0, false); - public AndroidGraphics (AndroidApplication activity, AndroidApplicationConfiguration config, ResolutionStrategy resolutionStrategy) { + public AndroidGraphics (AndroidApplication activity, AndroidApplicationConfiguration config, + ResolutionStrategy resolutionStrategy) { this.config = config; view = createGLSurfaceView(activity, config.useGL20, resolutionStrategy); view.setFocusable(true); @@ -94,51 +93,58 @@ public AndroidGraphics (AndroidApplication activity, AndroidApplicationConfigura this.app = activity; } - private View createGLSurfaceView(Activity activity, boolean useGL2, ResolutionStrategy resolutionStrategy) { - EGLConfigChooser configChooser = getEglConfigChooser(); - - if (useGL2 && checkGL20()) { - GLSurfaceView20 view = new GLSurfaceView20(activity, resolutionStrategy); - if (configChooser != null) view.setEGLConfigChooser(configChooser); - else view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); - view.setRenderer(this); - return view; - } else { - if (Integer.parseInt(android.os.Build.VERSION.SDK) <= 4) { - GLSurfaceViewCupcake view = new GLSurfaceViewCupcake(activity, resolutionStrategy); - if (configChooser != null) view.setEGLConfigChooser(configChooser); - else view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); - view.setRenderer(this); - return view; - } else { - android.opengl.GLSurfaceView view = new DefaultGLSurfaceView(activity, resolutionStrategy); - if (configChooser != null) view.setEGLConfigChooser(configChooser); - else view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); - view.setRenderer(this); - return view; - } - } - } + private View createGLSurfaceView (Activity activity, boolean useGL2, ResolutionStrategy resolutionStrategy) { + EGLConfigChooser configChooser = getEglConfigChooser(); + + if (useGL2 && checkGL20()) { + GLSurfaceView20 view = new GLSurfaceView20(activity, resolutionStrategy); + if (configChooser != null) + view.setEGLConfigChooser(configChooser); + else + view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); + view.setRenderer(this); + return view; + } else { + if (Integer.parseInt(android.os.Build.VERSION.SDK) <= 4) { + GLSurfaceViewCupcake view = new GLSurfaceViewCupcake(activity, resolutionStrategy); + if (configChooser != null) + view.setEGLConfigChooser(configChooser); + else + view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); + view.setRenderer(this); + return view; + } else { + android.opengl.GLSurfaceView view = new DefaultGLSurfaceView(activity, resolutionStrategy); + if (configChooser != null) + view.setEGLConfigChooser(configChooser); + else + view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil); + view.setRenderer(this); + return view; + } + } + } private EGLConfigChooser getEglConfigChooser () { - return new GdxEglConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil, config.numSamples, config.useGL20); - -// if (!Build.DEVICE.equalsIgnoreCase("GT-I7500")) -// return null; -// else -// return new android.opengl.GLSurfaceView.EGLConfigChooser() { + return new GdxEglConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil, config.numSamples, + config.useGL20); + +// if (!Build.DEVICE.equalsIgnoreCase("GT-I7500")) +// return null; +// else +// return new android.opengl.GLSurfaceView.EGLConfigChooser() { // -// public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) { +// public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) { // -// // Ensure that we get a 16bit depth-buffer. Otherwise, we'll fall -// // back to Pixelflinger on some device (read: Samsung I7500) -// int[] attributes = new int[] {EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE}; -// EGLConfig[] configs = new EGLConfig[1]; -// int[] result = new int[1]; -// egl.eglChooseConfig(display, attributes, configs, 1, result); -// return configs[0]; -// } -// }; +// // Ensure that we get a 16bit depth-buffer. Otherwise, we'll fall +// // back to Pixelflinger on some device (read: Samsung I7500) +// int[] attributes = new int[] {EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE}; +// EGLConfig[] configs = new EGLConfig[1]; +// int[] result = new int[1]; +// egl.eglChooseConfig(display, attributes, configs, 1, result); +// return configs[0]; +// } +// }; } private void updatePpi () { @@ -170,52 +176,45 @@ private boolean checkGL20 () { return num_config[0] > 0; } - /** - * {@inheritDoc} - */ - @Override public GL10 getGL10 () { + /** {@inheritDoc} */ + @Override + public GL10 getGL10 () { return gl10; } - /** - * {@inheritDoc} - */ - @Override public GL11 getGL11 () { + /** {@inheritDoc} */ + @Override + public GL11 getGL11 () { return gl11; } - /** - * {@inheritDoc} - */ - @Override public GL20 getGL20 () { + /** {@inheritDoc} */ + @Override + public GL20 getGL20 () { return gl20; } - /** - * {@inheritDoc} - */ - @Override public int getHeight () { + /** {@inheritDoc} */ + @Override + public int getHeight () { return height; } - /** - * {@inheritDoc} - */ - @Override public int getWidth () { + /** {@inheritDoc} */ + @Override + public int getWidth () { return width; } - /** - * {@inheritDoc} - */ - @Override public boolean isGL11Available () { + /** {@inheritDoc} */ + @Override + public boolean isGL11Available () { return gl11 != null; } - /** - * {@inheritDoc} - */ - @Override public boolean isGL20Available () { + /** {@inheritDoc} */ + @Override + public boolean isGL20Available () { return gl20 != null; } @@ -223,13 +222,11 @@ private static boolean isPowerOfTwo (int value) { return ((value != 0) && (value & (value - 1)) == 0); } - /** - * This instantiates the GL10, GL11 and GL20 instances. Includes the check for certain devices that pretend to support GL11 but + /** 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 - */ + * @param gl */ private void setupGL (javax.microedition.khronos.opengles.GL10 gl) { if (gl10 != null || gl20 != null) return; @@ -266,7 +263,8 @@ private void setupGL (javax.microedition.khronos.opengles.GL10 gl) { Gdx.app.log("AndroidGraphics", "OGL extensions: " + gl.glGetString(GL10.GL_EXTENSIONS)); } - @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; updatePpi(); @@ -281,7 +279,8 @@ private void setupGL (javax.microedition.khronos.opengles.GL10 gl) { app.listener.resize(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); logConfig(config); updatePpi(); @@ -313,9 +312,9 @@ private void logConfig (EGLConfig config) { int b = getAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0); int a = getAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0); int d = getAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0); - int s = getAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); + int s = getAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0); int samples = Math.max(getAttrib(egl, display, config, EGL10.EGL_SAMPLES, 0), - getAttrib(egl, display, config, GdxEglConfigChooser.EGL_COVERAGE_SAMPLES_NV, 0)); + getAttrib(egl, display, config, GdxEglConfigChooser.EGL_COVERAGE_SAMPLES_NV, 0)); boolean coverageSample = getAttrib(egl, display, config, GdxEglConfigChooser.EGL_COVERAGE_SAMPLES_NV, 0) != 0; Gdx.app.log("AndroidGraphics", "framebuffer: (" + r + ", " + g + ", " + b + ", " + a + ")"); @@ -373,7 +372,8 @@ void destroy () { } } - @Override public void onDrawFrame (javax.microedition.khronos.opengles.GL10 gl) { + @Override + public void onDrawFrame (javax.microedition.khronos.opengles.GL10 gl) { long time = System.nanoTime(); deltaTime = (time - lastFrameTime) / 1000000000.0f; lastFrameTime = time; @@ -442,24 +442,21 @@ void destroy () { frames++; } - /** - * {@inheritDoc} - */ - @Override public float getDeltaTime () { + /** {@inheritDoc} */ + @Override + public float getDeltaTime () { return mean.getMean() == 0 ? deltaTime : mean.getMean(); } - /** - * {@inheritDoc} - */ - @Override public GraphicsType getType () { + /** {@inheritDoc} */ + @Override + public GraphicsType getType () { return GraphicsType.AndroidGL; } - /** - * {@inheritDoc} - */ - @Override public int getFramesPerSecond () { + /** {@inheritDoc} */ + @Override + public int getFramesPerSecond () { return fps; } @@ -479,58 +476,69 @@ public View getView () { return view; } - /** - * {@inheritDoc} - */ - @Override public GLCommon getGLCommon () { + /** {@inheritDoc} */ + @Override + public GLCommon getGLCommon () { return gl; } - @Override public float getPpiX () { + @Override + public float getPpiX () { return ppiX; } - @Override public float getPpiY () { + @Override + public float getPpiY () { return ppiY; } - @Override public float getPpcX () { + @Override + public float getPpcX () { return ppcX; } - @Override public float getPpcY () { + @Override + public float getPpcY () { return ppcY; } - - @Override public float getDensity () { + + @Override + public float getDensity () { return density; } - @Override public GLU getGLU () { + @Override + public GLU getGLU () { return glu; } - @Override public boolean supportsDisplayModeChange () { + @Override + public boolean supportsDisplayModeChange () { return false; } - @Override public boolean setDisplayMode (DisplayMode displayMode) { + @Override + public boolean setDisplayMode (DisplayMode displayMode) { return false; } - @Override public DisplayMode[] getDisplayModes () { + @Override + public DisplayMode[] getDisplayModes () { return new DisplayMode[] {getDesktopDisplayMode()}; } - @Override public boolean setDisplayMode (int width, int height, boolean fullscreen) { + @Override + public boolean setDisplayMode (int width, int height, boolean fullscreen) { return false; } - @Override public void setTitle (String title) { + @Override + public void setTitle (String title) { } - @Override public void setIcon (Pixmap pixmap) { + @Override + public void setIcon (Pixmap pixmap) { } @@ -540,21 +548,25 @@ protected AndroidDisplayMode (int width, int height, int refreshRate, int bitsPe } } - @Override public DisplayMode getDesktopDisplayMode () { + @Override + public DisplayMode getDesktopDisplayMode () { DisplayMetrics metrics = new DisplayMetrics(); app.getWindowManager().getDefaultDisplay().getMetrics(metrics); return new AndroidDisplayMode(metrics.widthPixels, metrics.heightPixels, 0, 0); } - @Override public BufferFormat getBufferFormat () { + @Override + public BufferFormat getBufferFormat () { return bufferFormat; } - @Override public void setVSync (boolean vsync) { + @Override + public void setVSync (boolean vsync) { } - @Override public boolean supportsExtension (String extension) { - if(extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); + @Override + public boolean supportsExtension (String extension) { + if (extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); return extensions.contains(extension); } } 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 d4503761e22..3a0b7f670b1 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 @@ -29,13 +29,11 @@ import android.hardware.SensorManager; import android.os.Handler; import android.os.Vibrator; -import android.view.Display; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; -import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; @@ -45,12 +43,9 @@ import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.utils.Pool; -/** - * An implementation of the {@link Input} interface for Android. +/** An implementation of the {@link Input} interface for Android. * - * @author mzechner - * - */ + * @author mzechner */ public final class AndroidInput implements Input, OnKeyListener, OnTouchListener, SensorEventListener { class KeyEvent { static final int KEY_DOWN = 0; @@ -143,30 +138,34 @@ public AndroidInput (AndroidApplication activity, View view, AndroidApplicationC hasMultitouch = touchHandler.supportsMultitouch(app); vibrator = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE); - + int rotation = getRotation(); DisplayMode mode = app.graphics.getDesktopDisplayMode(); - if(((rotation == 0 || rotation == 180) && (mode.width >= mode.height)) || - ((rotation == 90 || rotation == 270) && (mode.width <= mode.height))) { + if (((rotation == 0 || rotation == 180) && (mode.width >= mode.height)) + || ((rotation == 90 || rotation == 270) && (mode.width <= mode.height))) { nativeOrientation = Orientation.Landscape; } else { nativeOrientation = Orientation.Portrait; - } + } } - @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) { + @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); @@ -181,7 +180,8 @@ public void onClick (DialogInterface dialog, int whichButton) { } }); alert.setOnCancelListener(new OnCancelListener() { - @Override public void onCancel (DialogInterface arg0) { + @Override + public void onCancel (DialogInterface arg0) { listener.canceled(); } }); @@ -190,25 +190,29 @@ public void onClick (DialogInterface dialog, int whichButton) { }); } - @Override public int getX () { + @Override + public int getX () { synchronized (this) { return touchX[0]; } } - @Override public int getY () { + @Override + public int getY () { synchronized (this) { return touchY[0]; } } - @Override public int getX (int pointer) { + @Override + public int getX (int pointer) { synchronized (this) { return touchX[pointer]; } } - @Override public int getY (int pointer) { + @Override + public int getY (int pointer) { synchronized (this) { return touchY[pointer]; } @@ -220,7 +224,8 @@ public boolean isTouched (int pointer) { } } - @Override public boolean isKeyPressed (int key) { + @Override + public boolean isKeyPressed (int key) { synchronized (this) { if (key == Input.Keys.ANY_KEY) return keys.size() > 0; @@ -229,7 +234,8 @@ public boolean isTouched (int pointer) { } } - @Override public boolean isTouched () { + @Override + public boolean isTouched () { synchronized (this) { return touched[0]; } @@ -293,9 +299,9 @@ void processEvents () { usedKeyEvents.free(keyEvents.get(i)); } } - - if(touchEvents.size() == 0) { - for(int i = 0; i < deltaX.length; i++) { + + if (touchEvents.size() == 0) { + for (int i = 0; i < deltaX.length; i++) { deltaX[0] = 0; deltaY[0] = 0; } @@ -308,7 +314,8 @@ void processEvents () { boolean requestFocus = true; - @Override public boolean onTouch (View view, MotionEvent event) { + @Override + public boolean onTouch (View view, MotionEvent event) { if (requestFocus) { view.requestFocus(); view.requestFocusFromTouch(); @@ -327,7 +334,8 @@ void processEvents () { return true; } - @Override public boolean onKey (View v, int keyCode, android.view.KeyEvent e) { + @Override + public boolean onKey (View v, int keyCode, android.view.KeyEvent e) { synchronized (this) { char character = (char)e.getUnicodeChar(); // Android doesn't report a unicode char for back space. hrm... @@ -375,13 +383,15 @@ void processEvents () { return false; } - @Override public void onAccuracyChanged (Sensor arg0, int arg1) { + @Override + public void onAccuracyChanged (Sensor arg0, int arg1) { } - @Override public void onSensorChanged (SensorEvent event) { + @Override + public void onSensorChanged (SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { - if(nativeOrientation == Orientation.Portrait) { + if (nativeOrientation == Orientation.Portrait) { System.arraycopy(event.values, 0, accelerometerValues, 0, accelerometerValues.length); } else { accelerometerValues[0] = event.values[1]; @@ -394,7 +404,8 @@ void processEvents () { } } - @Override public void setOnscreenKeyboardVisible (final boolean visible) { + @Override + public void setOnscreenKeyboardVisible (final boolean visible) { handle.post(new Runnable() { public void run () { InputMethodManager manager = (InputMethodManager)app.getSystemService(Context.INPUT_METHOD_SERVICE); @@ -410,31 +421,38 @@ public void run () { }); } - @Override public void setCatchBackKey (boolean catchBack) { + @Override + public void setCatchBackKey (boolean catchBack) { this.catchBack = catchBack; } - - @Override public void setCatchMenuKey (boolean catchMenu) { + + @Override + public void setCatchMenuKey (boolean catchMenu) { this.catchMenu = catchMenu; } - @Override public void vibrate (int milliseconds) { + @Override + public void vibrate (int milliseconds) { vibrator.vibrate(milliseconds); } - @Override public void vibrate (long[] pattern, int repeat) { + @Override + public void vibrate (long[] pattern, int repeat) { vibrator.vibrate(pattern, repeat); } - @Override public void cancelVibrate () { + @Override + public void cancelVibrate () { vibrator.cancel(); } - @Override public boolean justTouched () { + @Override + public boolean justTouched () { return justTouched; } - @Override public boolean isButtonPressed (int button) { + @Override + public boolean isButtonPressed (int button) { if (button == Buttons.LEFT) return isTouched(); else @@ -453,21 +471,24 @@ private void updateOrientation () { } } - @Override public float getAzimuth () { + @Override + public float getAzimuth () { if (!compassAvailable) return 0; updateOrientation(); return azimuth; } - @Override public float getPitch () { + @Override + public float getPitch () { if (!compassAvailable) return 0; updateOrientation(); return pitch; } - @Override public float getRoll () { + @Override + public float getRoll () { if (!compassAvailable) return 0; updateOrientation(); @@ -510,11 +531,13 @@ void unregisterSensorListeners () { Gdx.app.log("AndroidInput", "sensor listener tear down"); } - @Override public InputProcessor getInputProcessor () { + @Override + public InputProcessor getInputProcessor () { return this.processor; } - @Override public boolean isPeripheralAvailable (Peripheral peripheral) { + @Override + public boolean isPeripheralAvailable (Peripheral peripheral) { if (peripheral == Peripheral.Accelerometer) return accelerometerAvailable; if (peripheral == Peripheral.Compass) return compassAvailable; if (peripheral == Peripheral.HardwareKeyboard) return keyboardAvailable; @@ -550,7 +573,8 @@ public int lookUpPointerIndex (int pointerId) { return -1; } - @Override public int getRotation () { + @Override + public int getRotation () { int orientation = app.getWindowManager().getDefaultDisplay().getOrientation(); switch (orientation) { case Surface.ROTATION_0: @@ -566,33 +590,41 @@ public int lookUpPointerIndex (int pointerId) { } } - @Override public Orientation getNativeOrientation () { + @Override + public Orientation getNativeOrientation () { return nativeOrientation; } - @Override public void setCursorCatched (boolean catched) { + @Override + public void setCursorCatched (boolean catched) { } - @Override public boolean isCursorCatched () { + @Override + public boolean isCursorCatched () { return false; } - @Override public int getDeltaX () { + @Override + public int getDeltaX () { return deltaX[0]; } - @Override public int getDeltaX (int pointer) { + @Override + public int getDeltaX (int pointer) { return deltaX[pointer]; } - @Override public int getDeltaY () { + @Override + public int getDeltaY () { return deltaY[0]; } - @Override public int getDeltaY (int pointer) { + @Override + public int getDeltaY (int pointer) { return deltaY[pointer]; } - @Override public void setCursorPosition (int x, int y) { - } + @Override + public void setCursorPosition (int x, int y) { + } } 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 2204c97a11a..c89e9d3f1e1 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import android.view.MotionEvent; @@ -20,27 +21,24 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.android.AndroidInput.TouchEvent; -/** - * Multitouch handler for devices running Android >= 2.0. If device is capable of (fake) multitouch this will report additional +/** Multitouch handler for devices running Android >= 2.0. If device is capable of (fake) multitouch this will report additional * pointers. * - * @author badlogicgames@gmail.com - * - */ + * @author badlogicgames@gmail.com */ 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; int realPointerIndex = 0; -// logAction(action, pointerId); - synchronized(input) { // FUCK +// logAction(action, pointerId); + synchronized (input) { // FUCK switch (action) { - case MotionEvent.ACTION_DOWN: - case MotionEvent.ACTION_POINTER_DOWN: + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_POINTER_DOWN: realPointerIndex = input.getFreePointerIndex(); // get a free pointer index as reported by Input.getX() etc. input.realId[realPointerIndex] = pointerId; x = (int)event.getX(pointerIndex); @@ -52,13 +50,13 @@ public void onTouch (MotionEvent event, AndroidInput input) { input.deltaY[realPointerIndex] = 0; input.touched[realPointerIndex] = true; break; - + case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_OUTSIDE: - case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_CANCEL: realPointerIndex = input.lookUpPointerIndex(pointerId); - if(realPointerIndex == -1) break; + if (realPointerIndex == -1) break; input.realId[realPointerIndex] = -1; x = (int)event.getX(pointerIndex); y = (int)event.getY(pointerIndex); @@ -69,7 +67,7 @@ public void onTouch (MotionEvent event, AndroidInput input) { input.deltaY[realPointerIndex] = 0; input.touched[realPointerIndex] = false; break; - + case MotionEvent.ACTION_MOVE: int pointerCount = event.getPointerCount(); for (int i = 0; i < pointerCount; i++) { @@ -78,7 +76,7 @@ public void onTouch (MotionEvent event, AndroidInput input) { x = (int)event.getX(pointerIndex); y = (int)event.getY(pointerIndex); realPointerIndex = input.lookUpPointerIndex(pointerId); - if(realPointerIndex == -1) continue; + if (realPointerIndex == -1) continue; postTouchEvent(input, TouchEvent.TOUCH_DRAGGED, x, y, realPointerIndex); input.deltaX[realPointerIndex] = x - input.touchX[realPointerIndex]; input.deltaY[realPointerIndex] = y - input.touchY[realPointerIndex]; @@ -90,28 +88,36 @@ public void onTouch (MotionEvent event, AndroidInput input) { } } - private void logAction(int action, int pointer) { + private void logAction (int action, int pointer) { String actionStr = ""; - if(action == MotionEvent.ACTION_DOWN) actionStr = "DOWN"; - else if(action == MotionEvent.ACTION_POINTER_DOWN) actionStr = "POINTER DOWN"; - else if(action == MotionEvent.ACTION_UP) actionStr = "UP"; - else if(action == MotionEvent.ACTION_POINTER_UP) actionStr = "POINTER UP"; - else if(action == MotionEvent.ACTION_OUTSIDE) actionStr = "OUTSIDE"; - else if(action == MotionEvent.ACTION_CANCEL) actionStr = "CANCEL"; - else if(action == MotionEvent.ACTION_MOVE) actionStr = "MOVE"; - else actionStr = "UNKNOWN (" + action + ")"; + if (action == MotionEvent.ACTION_DOWN) + actionStr = "DOWN"; + else if (action == MotionEvent.ACTION_POINTER_DOWN) + actionStr = "POINTER DOWN"; + else if (action == MotionEvent.ACTION_UP) + actionStr = "UP"; + else if (action == MotionEvent.ACTION_POINTER_UP) + actionStr = "POINTER UP"; + else if (action == MotionEvent.ACTION_OUTSIDE) + actionStr = "OUTSIDE"; + else if (action == MotionEvent.ACTION_CANCEL) + actionStr = "CANCEL"; + else if (action == MotionEvent.ACTION_MOVE) + actionStr = "MOVE"; + else + actionStr = "UNKNOWN (" + action + ")"; Gdx.app.log("AndroidMultiTouchHandler", "action " + actionStr + ", Android pointer id: " + pointer); } - + private void postTouchEvent (AndroidInput input, int type, int x, int y, int pointer) { - long timeStamp = System.nanoTime(); + long timeStamp = System.nanoTime(); TouchEvent event = input.usedTouchEvents.obtain(); event.timeStamp = timeStamp; event.pointer = pointer; event.x = x; event.y = y; event.type = type; - input.touchEvents.add(event); + input.touchEvents.add(event); } public boolean supportsMultitouch (AndroidApplication activity) { 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 5ec243b201d..eed7ab082cf 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; import java.io.IOException; @@ -32,34 +33,39 @@ public class AndroidMusic implements Music { this.player = player; } - @Override public void dispose () { - if(player == null) return; + @Override + public void dispose () { + if (player == null) return; try { if (player.isPlaying()) player.stop(); player.release(); - } catch(Throwable t) { + } catch (Throwable t) { Gdx.app.log("AndroidMusic", "error while disposing AndroidMusic instance, non-fatal"); } finally { player = null; - synchronized(audio.musics) { + synchronized (audio.musics) { 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 () { + @Override + public void pause () { if (player.isPlaying()) player.pause(); } - @Override public void play () { + @Override + public void play () { if (player.isPlaying()) return; try { @@ -75,19 +81,22 @@ public class AndroidMusic implements Music { } } - @Override public void setLooping (boolean isLooping) { + @Override + public void setLooping (boolean isLooping) { player.setLooping(isLooping); } - @Override public void setVolume (float volume) { + @Override + public void setVolume (float volume) { player.setVolume(volume, volume); } - @Override public void stop () { - if(isPrepared) { + @Override + public void stop () { + if (isPrepared) { player.seekTo(0); } - player.stop(); + player.stop(); isPrepared = false; } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPreferences.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPreferences.java index ccba6730dd9..e1748458b56 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPreferences.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidPreferences.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; -import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -26,112 +26,127 @@ public class AndroidPreferences implements Preferences { SharedPreferences sharedPrefs; - - public AndroidPreferences(SharedPreferences preferences) { + + public AndroidPreferences (SharedPreferences preferences) { this.sharedPrefs = preferences; } - @Override public void putBoolean (String key, boolean val) { + @Override + public void putBoolean (String key, boolean val) { Editor edit = this.sharedPrefs.edit(); edit.putBoolean(key, val); edit.commit(); } - @Override public void putInteger (String key, int val) { + @Override + public void putInteger (String key, int val) { Editor edit = this.sharedPrefs.edit(); edit.putInt(key, val); edit.commit(); } - @Override public void putLong (String key, long val) { + @Override + public void putLong (String key, long val) { Editor edit = this.sharedPrefs.edit(); edit.putLong(key, val); edit.commit(); } - @Override public void putFloat (String key, float val) { + @Override + public void putFloat (String key, float val) { Editor edit = this.sharedPrefs.edit(); edit.putFloat(key, val); edit.commit(); } - - @Override public void putString(String key, String val) { + + @Override + public void putString (String key, String val) { Editor edit = this.sharedPrefs.edit(); edit.putString(key, val); edit.commit(); } - @Override public void put (Map vals) { + @Override + public void put (Map vals) { Editor edit = this.sharedPrefs.edit(); - for(Entry val: vals.entrySet()) { - if(val.getValue() instanceof Boolean) - putBoolean(val.getKey(), (Boolean)val.getValue()); - if(val.getValue() instanceof Integer) - putInteger(val.getKey(), (Integer)val.getValue()); - if(val.getValue() instanceof Long) - putLong(val.getKey(), (Long)val.getValue()); - if(val.getValue() instanceof String) - putString(val.getKey(), (String)val.getValue()); - if(val.getValue() instanceof Float) - putFloat(val.getKey(), (Float)val.getValue()); + for (Entry val : vals.entrySet()) { + if (val.getValue() instanceof Boolean) putBoolean(val.getKey(), (Boolean)val.getValue()); + if (val.getValue() instanceof Integer) putInteger(val.getKey(), (Integer)val.getValue()); + if (val.getValue() instanceof Long) putLong(val.getKey(), (Long)val.getValue()); + if (val.getValue() instanceof String) putString(val.getKey(), (String)val.getValue()); + if (val.getValue() instanceof Float) putFloat(val.getKey(), (Float)val.getValue()); } edit.commit(); } - @Override public boolean getBoolean (String key) { + @Override + public boolean getBoolean (String key) { return sharedPrefs.getBoolean(key, false); } - @Override public int getInteger (String key) { + @Override + public int getInteger (String key) { return sharedPrefs.getInt(key, 0); } - @Override public long getLong (String key) { + @Override + public long getLong (String key) { return sharedPrefs.getLong(key, 0); } - @Override public float getFloat (String key) { + @Override + public float getFloat (String key) { return sharedPrefs.getFloat(key, 0); } - @Override public String getString (String key) { + @Override + public String getString (String key) { return sharedPrefs.getString(key, ""); } - @Override public boolean getBoolean (String key, boolean defValue) { + @Override + public boolean getBoolean (String key, boolean defValue) { return sharedPrefs.getBoolean(key, defValue); } - @Override public int getInteger (String key, int defValue) { + @Override + public int getInteger (String key, int defValue) { return sharedPrefs.getInt(key, defValue); } - @Override public long getLong (String key, long defValue) { + @Override + public long getLong (String key, long defValue) { return sharedPrefs.getLong(key, defValue); } - @Override public float getFloat (String key, float defValue) { + @Override + public float getFloat (String key, float defValue) { return sharedPrefs.getFloat(key, defValue); } - @Override public String getString (String key, String defValue) { + @Override + public String getString (String key, String defValue) { return sharedPrefs.getString(key, defValue); } - @Override public Map get () { - return sharedPrefs.getAll(); + @Override + public Map get () { + return sharedPrefs.getAll(); } - @Override public boolean contains (String key) { + @Override + public boolean contains (String key) { return sharedPrefs.contains(key); } - @Override public void clear () { + @Override + public void clear () { Editor edit = sharedPrefs.edit(); edit.clear(); edit.commit(); } - - @Override public void flush () { + + @Override + public void flush () { } } 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 dd41ce486d0..00e1d420d78 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 @@ -13,18 +13,16 @@ * 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.TouchEvent; -/** - * Single touch handler for devices running <= 1.6 - * - * @author badlogicgames@gmail.com +/** Single touch handler for devices running <= 1.6 * - */ + * @author badlogicgames@gmail.com */ public class AndroidSingleTouchHandler implements AndroidTouchHandler { public void onTouch (MotionEvent event, AndroidInput input) { int x = (int)event.getX(); @@ -39,17 +37,17 @@ public void onTouch (MotionEvent event, AndroidInput input) { input.touched[0] = true; input.deltaX[0] = 0; input.deltaY[0] = 0; - }else if (event.getAction() == MotionEvent.ACTION_MOVE) { + } else if (event.getAction() == MotionEvent.ACTION_MOVE) { postTouchEvent(input, TouchEvent.TOUCH_DRAGGED, x, y, 0); input.touched[0] = true; input.deltaX[0] = x - oldX; input.deltaY[0] = y - oldY; - }else if (event.getAction() == MotionEvent.ACTION_UP) { + } else if (event.getAction() == MotionEvent.ACTION_UP) { postTouchEvent(input, TouchEvent.TOUCH_UP, x, y, 0); input.touched[0] = false; input.deltaX[0] = 0; input.deltaY[0] = 0; - }else if (event.getAction() == MotionEvent.ACTION_CANCEL) { + } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { postTouchEvent(input, TouchEvent.TOUCH_UP, x, y, 0); input.touched[0] = false; input.deltaX[0] = 0; @@ -69,7 +67,7 @@ private void postTouchEvent (AndroidInput input, int type, int x, int y, int poi input.touchEvents.add(event); } } - + public boolean supportsMultitouch (AndroidApplication activity) { return false; } 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 a146471d1e4..6ee9789a4fc 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 @@ -34,15 +34,18 @@ final class AndroidSound implements Sound { this.soundId = soundId; } - @Override public void dispose () { + @Override + public void dispose () { soundPool.unload(soundId); } - @Override public void play () { + @Override + public void play () { play(1); } - @Override public void play (float volume) { + @Override + public void play (float volume) { if (streamIds.size == 8) streamIds.pop(); streamIds.add(soundPool.play(soundId, volume, volume, 1, 0, 1)); } 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 633ffade136..eb9b0771465 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 @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android; -import android.content.Context; import android.view.MotionEvent; public interface AndroidTouchHandler { public void onTouch (MotionEvent event, AndroidInput input); - public boolean supportsMultitouch(AndroidApplication app); + + public boolean supportsMultitouch (AndroidApplication app); } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/DefaultGLSurfaceView.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/DefaultGLSurfaceView.java index b3f680ca1c2..53591db6e38 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/DefaultGLSurfaceView.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/DefaultGLSurfaceView.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android.surfaceview; import android.content.Context; @@ -21,22 +22,21 @@ public class DefaultGLSurfaceView extends GLSurfaceView { + final ResolutionStrategy resolutionStrategy; - final ResolutionStrategy resolutionStrategy; - - public DefaultGLSurfaceView(Context context, ResolutionStrategy resolutionStrategy) { - super(context); - this.resolutionStrategy = resolutionStrategy; - } + public DefaultGLSurfaceView (Context context, ResolutionStrategy resolutionStrategy) { + super(context); + this.resolutionStrategy = resolutionStrategy; + } - public DefaultGLSurfaceView(Context context, AttributeSet attrs, ResolutionStrategy resolutionStrategy) { - super(context, attrs); - this.resolutionStrategy = resolutionStrategy; - } + public DefaultGLSurfaceView (Context context, AttributeSet attrs, ResolutionStrategy resolutionStrategy) { + super(context, attrs); + this.resolutionStrategy = resolutionStrategy; + } - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - ResolutionStrategy.MeasuredDimension measures = resolutionStrategy.calcMeasures(widthMeasureSpec, heightMeasureSpec); - setMeasuredDimension(measures.width, measures.height); - } + @Override + protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { + ResolutionStrategy.MeasuredDimension measures = resolutionStrategy.calcMeasures(widthMeasureSpec, heightMeasureSpec); + setMeasuredDimension(measures.width, measures.height); + } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FillResolutionStrategy.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FillResolutionStrategy.java index e9cb9f1ca1f..52e3a216b59 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FillResolutionStrategy.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FillResolutionStrategy.java @@ -15,21 +15,18 @@ import android.view.View; -/** - * This {@link ResolutionStrategy} will stretch the GLSurfaceView to full screen. - * FillResolutionStrategy is the default {@link ResolutionStrategy} if none is specified. - * - * @author christoph widulle - */ +/** This {@link ResolutionStrategy} will stretch the GLSurfaceView to full screen. FillResolutionStrategy is the default + * {@link ResolutionStrategy} if none is specified. + * + * @author christoph widulle */ public class FillResolutionStrategy implements ResolutionStrategy { + @Override + public MeasuredDimension calcMeasures (int widthMeasureSpec, int heightMeasureSpec) { - @Override - public MeasuredDimension calcMeasures(int widthMeasureSpec, int heightMeasureSpec) { - - final int width = View.MeasureSpec.getSize(widthMeasureSpec); - final int height = View.MeasureSpec.getSize(heightMeasureSpec); + final int width = View.MeasureSpec.getSize(widthMeasureSpec); + final int height = View.MeasureSpec.getSize(heightMeasureSpec); - return new MeasuredDimension(width, height); - } + return new MeasuredDimension(width, height); + } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FixedResolutionStrategy.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FixedResolutionStrategy.java index f86ed012b6a..aa84a3d6259 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FixedResolutionStrategy.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/FixedResolutionStrategy.java @@ -13,23 +13,21 @@ package com.badlogic.gdx.backends.android.surfaceview; -/** - * This {@link ResolutionStrategy} will place the GLSurfaceView with the given height and width in the center the screen. - * - * @author christoph widulle - */ +/** This {@link ResolutionStrategy} will place the GLSurfaceView with the given height and width in the center the screen. + * + * @author christoph widulle */ public class FixedResolutionStrategy implements ResolutionStrategy { - private final int width; - private final int height; + private final int width; + private final int height; - public FixedResolutionStrategy(int width, int height) { - this.width = width; - this.height = height; - } + public FixedResolutionStrategy (int width, int height) { + this.width = width; + this.height = height; + } - @Override - public MeasuredDimension calcMeasures(int widthMeasureSpec, int heightMeasureSpec) { - return new MeasuredDimension(width, height); - } + @Override + public MeasuredDimension calcMeasures (int widthMeasureSpec, int heightMeasureSpec) { + return new MeasuredDimension(width, height); + } } 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 4a3587490ef..a59a410519b 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 @@ -31,8 +31,7 @@ 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: *

@@ -125,59 +124,46 @@ * * * - * * - */ + * */ 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. + /** The renderer only renders when the surface is created, or when {@link #requestRender} is called. * * @see #getRenderMode() - * @see #setRenderMode(int) - */ + * @see #setRenderMode(int) */ public final static int RENDERMODE_WHEN_DIRTY = 0; - /** - * The renderer is called continuously to re-render the scene. + /** The renderer is called continuously to re-render the scene. * * @see #getRenderMode() * @see #setRenderMode(int) - * @see #requestRender() - */ + * @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 + /** 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 - */ + * @see #setDebugFlags */ public final static int DEBUG_CHECK_GL_ERROR = 1; - /** - * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". + /** Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". * * @see #getDebugFlags - * @see #setDebugFlags - */ + * @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. - */ + /** 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. - */ + /** 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(); @@ -190,41 +176,34 @@ private void init () { holder.addCallback(this); } - /** - * Set the glWrapper. If the glWrapper is not null, its {@link GLWrapper#wrap(GL)} method is called whenever a surface is + /** 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 - */ + * @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 + /** 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 - */ + * @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. - */ + /** 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 + /** 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. @@ -246,8 +225,7 @@ public int getDebugFlags () { *

  • {@link #setRenderMode(int)} * * - * @param renderer the renderer to use to perform OpenGL drawing. - */ + * @param renderer the renderer to use to perform OpenGL drawing. */ public void setRenderer (Renderer renderer) { checkRenderThreadState(); if (mEGLConfigChooser == null) { @@ -263,47 +241,40 @@ public void setRenderer (Renderer renderer) { mGLThread.start(); } - /** - * Install a custom EGLContextFactory. + /** 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. - */ + * list. */ public void setEGLContextFactory (EGLContextFactory factory) { checkRenderThreadState(); mEGLContextFactory = factory; } - /** - * Install a custom EGLWindowSurfaceFactory. + /** 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. - */ + * 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. + /** 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 - */ + * @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 + /** 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. @@ -311,28 +282,23 @@ public void setEGLConfigChooser (EGLConfigChooser configChooser) { * 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 - */ + * @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 + /** 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. - * - */ + * 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 + /** 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. *

    @@ -343,95 +309,76 @@ public void setEGLConfigChooser (int redSize, int greenSize, int blueSize, int a * * @param renderMode one of the RENDERMODE_X constants * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ + * @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. + /** 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 - */ + * @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 + /** 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. - */ + * 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. - */ + /** 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. - */ + /** 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. - */ + /** 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. - */ + /** 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. + /** 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. - */ + * 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 + /** 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. - */ + * @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 () { + /** 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. + /** 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 @@ -448,23 +395,18 @@ public void queueEvent (Runnable r) { * } * } * - * @see #setGLWrapper(GLWrapper) - */ + * @see #setGLWrapper(GLWrapper) */ public interface GLWrapper { - /** - * Wraps a gl interface in another gl interface. + /** 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. - */ + * @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. + /** An interface for customizing the eglCreateContext and eglDestroyContext calls. *

    * This interface must be implemented by clients wishing to call - * {@link GLBaseSurfaceView#setEGLContextFactory(EGLContextFactory)} - */ + * {@link GLBaseSurfaceView#setEGLContextFactory(EGLContextFactory)} */ public interface EGLContextFactory { EGLContext createContext (EGL10 egl, EGLDisplay display, EGLConfig eglConfig); @@ -482,12 +424,10 @@ public void destroyContext (EGL10 egl, EGLDisplay display, EGLContext context) { } } - /** - * An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls. + /** An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls. *

    * This interface must be implemented by clients wishing to call - * {@link GLBaseSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)} - */ + * {@link GLBaseSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)} */ public interface EGLWindowSurfaceFactory { EGLSurface createWindowSurface (EGL10 egl, EGLDisplay display, EGLConfig config, Object nativeWindow); @@ -549,7 +489,8 @@ public ComponentSizeChooser (int redSize, int greenSize, int blueSize, int alpha mStencilSize = stencilSize; } - @Override public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { + @Override + public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { EGLConfig closestConfig = null; int closestDistance = 1000; for (EGLConfig config : configs) { @@ -589,10 +530,7 @@ private int findConfigAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, i protected int mStencilSize; } - /** - * This class will choose a supported surface as close to RGB565 as possible, with or without a depth buffer. - * - */ + /** 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); @@ -604,18 +542,14 @@ public SimpleEGLConfigChooser (boolean withDepthBuffer) { } } - /** - * An EGL helper class. - */ + /** An EGL helper class. */ private class EglHelper { public EglHelper () { } - /** - * Initialize EGL for a given configuration spec. - */ + /** Initialize EGL for a given configuration spec. */ public void start () { /* * Get an EGL instance @@ -696,10 +630,8 @@ public GL createSurface (SurfaceHolder holder) { return gl; } - /** - * Display the current render surface. - * @return false if the context has been lost. - */ + /** Display the current render surface. + * @return false if the context has been lost. */ public boolean swap () { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); @@ -740,14 +672,11 @@ private void throwEglException (String function) { EGLContext mEglContext; } - /** - * A generic GL Thread. Takes care of initializing EGL and GL. Delegates to a Renderer instance to do the actual drawing. Can + /** 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. - * - */ + * issues. */ class GLThread extends Thread { GLThread (Renderer renderer) { super(); @@ -758,7 +687,8 @@ class GLThread extends Thread { mRenderer = renderer; } - @Override public void run () { + @Override + public void run () { setName("GLThread " + getId()); if (LOG_THREADS) { Log.i("GLThread", "starting tid=" + getId()); @@ -1040,10 +970,8 @@ public void requestExitAndWait () { } } - /** - * Queue an "event" to be run on the GL rendering thread. - * @param r the runnable to be run on the GL rendering thread. - */ + /** 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"); @@ -1076,15 +1004,18 @@ public void queueEvent (Runnable r) { static class LogWriter extends Writer { - @Override public void close () { + @Override + public void close () { flushBuilder(); } - @Override public void flush () { + @Override + public void flush () { flushBuilder(); } - @Override public void write (char[] buf, int offset, int count) { + @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') { 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 73050b2ac79..8ce82ed2a3b 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 @@ -18,16 +18,12 @@ import javax.microedition.khronos.egl.EGL; import javax.microedition.khronos.opengles.GL; -/** - * A helper class for debugging OpenGL ES applications. +/** 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. + /** 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. @@ -41,28 +37,19 @@ public class GLDebugHelper { * @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. - */ + * @return the wrapped GL instance. */ - /** - * Check glError() after every call. - */ + /** Check glError() after every call. */ public static final int CONFIG_CHECK_GL_ERROR = (1 << 0); - /** - * Check if all calls are on the same thread. - */ + /** 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. - */ + /** 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. - */ + /** 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) { @@ -76,13 +63,11 @@ public static GL wrap (GL gl, int configFlags, Writer log) { return gl; } - /** - * Wrap an existing EGL interface in a new EGL interface that adds support for error checking and/or logging. + /** 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. - */ + * @return the wrapped EGL interface. */ public static EGL wrap (EGL egl, int configFlags, Writer log) { if (log != null) { egl = new EGLLogWrapper(egl, configFlags, log); 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 77affb55f88..933a96ae6ec 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 @@ -20,11 +20,9 @@ import javax.microedition.khronos.opengles.GL; -/** - * Implement an error checking wrapper. The wrapper will automatically call glError after each GL operation, and throw a +/** 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. - */ + * checking is an alternative to manually calling glError after every GL operation. */ class GLErrorWrapper extends GLWrapperBase { boolean mCheckError; boolean mCheckThread; 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 cad8f8c5c5c..8fced7fe070 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 @@ -15,11 +15,9 @@ import android.opengl.GLU; -/** - * An exception class for OpenGL errors. - * - */ -@SuppressWarnings("serial") public class GLException extends RuntimeException { +/** An exception class for OpenGL errors. */ +@SuppressWarnings("serial") +public class GLException extends RuntimeException { public GLException (final int error) { super(getErrorString(error)); mError = error; 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 d929305735c..64a2ba39d2b 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 @@ -28,10 +28,7 @@ import javax.microedition.khronos.opengles.GL; -/** - * A wrapper that logs all GL calls (and results) in human-readable form. - * - */ +/** 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; @@ -682,7 +679,7 @@ private int getIntegerStateSize (int pname) { case GL_BLUE_BITS: return 1; case GL_COMPRESSED_TEXTURE_FORMATS: - // Have to ask the implementation for the size + // Have to ask the implementation for the size { int[] buffer = new int[1]; mgl.glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, buffer, 0); @@ -2954,17 +2951,11 @@ public void glTexParameterxv (int target, int pname, IntBuffer params) { } private class PointerInfo { - /** - * The number of coordinates per vertex. 1..4 - */ + /** The number of coordinates per vertex. 1..4 */ public int mSize; - /** - * The type of each coordinate. - */ + /** The type of each coordinate. */ public int mType; - /** - * The byte offset between consecutive vertices. 0 means mSize * sizeof(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 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 7e627b8d1e6..129294449be 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 @@ -26,18 +26,17 @@ * governing permissions and limitations under the License. */ -import android.content.Context; -import android.graphics.PixelFormat; -import android.opengl.GLSurfaceView; -import android.util.Log; - import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; -/** - * A simple GLSurfaceView sub-class that demonstrate how to perform OpenGL ES 2.0 rendering into a GL Surface. Note the following +import android.content.Context; +import android.graphics.PixelFormat; +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. @@ -47,209 +46,207 @@ * 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. - */ + * red/green/blue/alpha channels bit depths). Failure to do so would result in an EGL_BAD_MATCH error. */ public class GLSurfaceView20 extends GLSurfaceView { - static String TAG = "GL2JNIView"; - private static final boolean DEBUG = false; - - final ResolutionStrategy resolutionStrategy; - - public GLSurfaceView20(Context context, ResolutionStrategy resolutionStrategy) { - super(context); - this.resolutionStrategy = resolutionStrategy; - init(false, 16, 0); - } - - public GLSurfaceView20(Context context, boolean translucent, int depth, int stencil, ResolutionStrategy resolutionStrategy) { - super(context); - this.resolutionStrategy = resolutionStrategy; - init(translucent, depth, stencil); - - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - ResolutionStrategy.MeasuredDimension measures = resolutionStrategy.calcMeasures(widthMeasureSpec, heightMeasureSpec); - setMeasuredDimension(measures.width, measures.height); - } - - 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 */ - } - - - 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); - } - } - - 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]; - } + static String TAG = "GL2JNIView"; + private static final boolean DEBUG = false; + + final ResolutionStrategy resolutionStrategy; + + public GLSurfaceView20 (Context context, ResolutionStrategy resolutionStrategy) { + super(context); + this.resolutionStrategy = resolutionStrategy; + init(false, 16, 0); + } + + public GLSurfaceView20 (Context context, boolean translucent, int depth, int stencil, ResolutionStrategy resolutionStrategy) { + super(context); + this.resolutionStrategy = resolutionStrategy; + init(translucent, depth, stencil); + + } + + @Override + protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { + ResolutionStrategy.MeasuredDimension measures = resolutionStrategy.calcMeasures(widthMeasureSpec, heightMeasureSpec); + setMeasuredDimension(measures.width, measures.height); + } + + 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 */ + } + + 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); + } + } + + 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 e9f183be75a..2bf1574c9ad 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 @@ -34,8 +34,7 @@ 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: *

    @@ -128,69 +127,55 @@ * * * - * * - */ + * */ public class GLSurfaceViewCupcake extends SurfaceView implements SurfaceHolder.Callback { - /** - * The renderer only renders when the surface is created, or when {@link #requestRender} is called. + /** The renderer only renders when the surface is created, or when {@link #requestRender} is called. * * @see #getRenderMode() - * @see #setRenderMode(int) - */ + * @see #setRenderMode(int) */ public final static int RENDERMODE_WHEN_DIRTY = 0; - /** - * The renderer is called continuously to re-render the scene. + /** The renderer is called continuously to re-render the scene. * * @see #getRenderMode() * @see #setRenderMode(int) - * @see #requestRender() - */ + * @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 + /** 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 - */ + * @see #setDebugFlags */ public final static int DEBUG_CHECK_GL_ERROR = 1; - /** - * Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". + /** Log GL calls to the system log at "verbose" level with tag "GLSurfaceView". * * @see #getDebugFlags - * @see #setDebugFlags - */ + * @see #setDebugFlags */ public final static int DEBUG_LOG_GL_CALLS = 2; - final ResolutionStrategy resolutionStrategy; + final ResolutionStrategy resolutionStrategy; - /** - * Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. - */ + /** Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. */ public GLSurfaceViewCupcake (Context context, ResolutionStrategy resolutionStrategy) { super(context); - this.resolutionStrategy = resolutionStrategy; + this.resolutionStrategy = resolutionStrategy; init(); } - /** - * Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. - */ + /** Standard View constructor. In order to render something, you must call {@link #setRenderer} to register a renderer. */ public GLSurfaceViewCupcake (Context context, AttributeSet attrs, ResolutionStrategy resolutionStrategy) { super(context, attrs); - this.resolutionStrategy = resolutionStrategy; + this.resolutionStrategy = resolutionStrategy; init(); } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - ResolutionStrategy.MeasuredDimension measures = resolutionStrategy.calcMeasures(widthMeasureSpec, heightMeasureSpec); - setMeasuredDimension(measures.width, measures.height); - } + @Override + protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) { + ResolutionStrategy.MeasuredDimension measures = resolutionStrategy.calcMeasures(widthMeasureSpec, heightMeasureSpec); + setMeasuredDimension(measures.width, measures.height); + } private void init () { // Install a SurfaceHolder.Callback so we get notified when the @@ -201,41 +186,34 @@ private void init () { mRenderMode = RENDERMODE_CONTINUOUSLY; } - /** - * Set the glWrapper. If the glWrapper is not null, its {@link GLWrapper#wrap(GL)} method is called whenever a surface is + /** 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 - */ + * @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 + /** 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 - */ + * @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. - */ + /** 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 + /** 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. @@ -257,8 +235,7 @@ public int getDebugFlags () { *

  • {@link #setRenderMode(int)} * * - * @param renderer the renderer to use to perform OpenGL drawing. - */ + * @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."); @@ -267,15 +244,13 @@ public void setRenderer (Renderer renderer) { mRenderer = renderer; } - /** - * Install a custom EGLConfigChooser. + /** 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 - */ + * @param configChooser */ public void setEGLConfigChooser (EGLConfigChooser configChooser) { if (mRenderer != null) { throw new IllegalStateException("setRenderer has already been called for this instance."); @@ -283,8 +258,7 @@ public void setEGLConfigChooser (EGLConfigChooser configChooser) { 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 + /** 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. @@ -292,28 +266,23 @@ public void setEGLConfigChooser (EGLConfigChooser configChooser) { * 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 - */ + * @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 + /** 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. - * - */ + * 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 + /** 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. *

    @@ -324,8 +293,7 @@ public void setEGLConfigChooser (int redSize, int greenSize, int blueSize, int a * * @param renderMode one of the RENDERMODE_X constants * @see #RENDERMODE_CONTINUOUSLY - * @see #RENDERMODE_WHEN_DIRTY - */ + * @see #RENDERMODE_WHEN_DIRTY */ public void setRenderMode (int renderMode) { mRenderMode = renderMode; if (mGLThread != null) { @@ -333,29 +301,23 @@ public void setRenderMode (int renderMode) { } } - /** - * Get the current rendering mode. May be called from any thread. Must not be called before a renderer has been set. + /** 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 - */ + * @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 + /** 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(). - */ + * 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. - */ + /** 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(); @@ -363,10 +325,8 @@ public void surfaceCreated (SurfaceHolder holder) { mHasSurface = true; } - /** - * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of - * GLSurfaceView. - */ + /** 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) { @@ -375,10 +335,8 @@ public void surfaceDestroyed (SurfaceHolder holder) { mHasSurface = false; } - /** - * This method is part of the SurfaceHolder.Callback interface, and is not normally called or subclassed by clients of - * GLSurfaceView. - */ + /** 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); @@ -387,21 +345,17 @@ public void surfaceChanged (SurfaceHolder holder, int format, int w, int h) { 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. - */ + /** 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. + /** 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. - */ + * has been set. */ public void onResume () { if (mEGLConfigChooser == null) { mEGLConfigChooser = new SimpleEGLConfigChooser(true); @@ -418,11 +372,9 @@ 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 + /** 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. - */ + * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent (Runnable r) { if (mGLThread != null) { mGLThread.queueEvent(r); @@ -431,8 +383,7 @@ public void queueEvent (Runnable r) { // ---------------------------------------------------------------------- - /** - * An interface used to wrap a GL interface. + /** 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 @@ -449,14 +400,11 @@ public void queueEvent (Runnable r) { * } * } * - * @see #setGLWrapper(GLWrapper) - */ + * @see #setGLWrapper(GLWrapper) */ public interface GLWrapper { - /** - * Wraps a gl interface in another gl interface. + /** 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. - */ + * @return either the input argument or another GL object that wraps the input argument. */ GL wrap (GL gl); } @@ -504,7 +452,8 @@ public ComponentSizeChooser (int redSize, int greenSize, int blueSize, int alpha mStencilSize = stencilSize; } - @Override public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { + @Override + public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { EGLConfig closestConfig = null; int closestDistance = 1000; for (EGLConfig config : configs) { @@ -542,10 +491,7 @@ private int findConfigAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, i protected int mStencilSize; } - /** - * This class will choose a supported surface as close to RGB565 as possible, with or without a depth buffer. - * - */ + /** 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); @@ -557,18 +503,14 @@ public SimpleEGLConfigChooser (boolean withDepthBuffer) { } } - /** - * An EGL helper class. - */ + /** An EGL helper class. */ private class EglHelper { public EglHelper () { } - /** - * Initialize EGL for a given configuration spec. - */ + /** Initialize EGL for a given configuration spec. */ public void start () { /* * Get an EGL instance @@ -635,10 +577,8 @@ public GL createSurface (SurfaceHolder holder) { return gl; } - /** - * Display the current render surface. - * @return false if the context has been lost. - */ + /** Display the current render surface. + * @return false if the context has been lost. */ public boolean swap () { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); @@ -672,11 +612,8 @@ public void finish () { 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. - * - */ + /** 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(); @@ -690,7 +627,8 @@ class GLThread extends Thread { setName("GLThread"); } - @Override public void run () { + @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(). @@ -876,10 +814,8 @@ public void requestExitAndWait () { } } - /** - * Queue an "event" to be run on the GL rendering thread. - * @param r the runnable to be run on the GL rendering thread. - */ + /** 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); @@ -911,15 +847,18 @@ private Runnable getEvent () { static class LogWriter extends Writer { - @Override public void close () { + @Override + public void close () { flushBuilder(); } - @Override public void flush () { + @Override + public void flush () { flushBuilder(); } - @Override public void write (char[] buf, int offset, int count) { + @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') { 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 49c8a07a1d3..b5fdf626ad5 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 @@ -24,9 +24,7 @@ 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; diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GdxEglConfigChooser.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GdxEglConfigChooser.java index 733d3d3f515..3b73c0b473f 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GdxEglConfigChooser.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/GdxEglConfigChooser.java @@ -21,16 +21,13 @@ import android.opengl.GLSurfaceView.EGLConfigChooser; import android.util.Log; -/** - * {@link EGLConfigChooser} implementation for GLES 1.x and 2.0. Let's hope this really works for all devices. Includes MSAA/CSAA +/** {@link EGLConfigChooser} implementation for GLES 1.x and 2.0. Let's hope this really works for all devices. Includes MSAA/CSAA * config selection if requested. Taken from GLSurfaceView20, heavily modified to accommodate MSAA/CSAA. - * @author mzechner - * - */ + * @author mzechner */ public class GdxEglConfigChooser implements GLSurfaceView.EGLConfigChooser { private static final int EGL_OPENGL_ES2_BIT = 4; public static final int EGL_COVERAGE_BUFFERS_NV = 0x30E0; - public static final int EGL_COVERAGE_SAMPLES_NV = 0x30E1; + public static final int EGL_COVERAGE_SAMPLES_NV = 0x30E1; private static final String TAG = "GdxEglConfigChooser"; protected int mRedSize; @@ -55,16 +52,10 @@ public GdxEglConfigChooser (int r, int g, int b, int a, int depth, int stencil, mUseGL20 = useGL20; if (useGL20) { - mConfigAttribs = new int[] {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}; + mConfigAttribs = new int[] {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}; } else { - mConfigAttribs = new int[] {EGL10.EGL_RED_SIZE, 4, - EGL10.EGL_GREEN_SIZE, 4, - EGL10.EGL_BLUE_SIZE, 4, - EGL10.EGL_NONE}; + mConfigAttribs = new int[] {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_NONE}; } } @@ -78,26 +69,26 @@ public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) { if (numConfigs <= 0) { throw new IllegalArgumentException("No configs match configSpec"); } - + // now actually read the configurations. EGLConfig[] configs = new EGLConfig[numConfigs]; egl.eglChooseConfig(display, mConfigAttribs, configs, numConfigs, num_config); - + // FIXME remove this. - //printConfigs(egl, display, configs); - + // printConfigs(egl, display, configs); + // chose the best one, taking into account multi sampling. EGLConfig config = chooseConfig(egl, display, configs); - + // FIXME print the chosen config - //printConfigs(egl, display, new EGLConfig[] { config }); + // printConfigs(egl, display, new EGLConfig[] { config }); return config; } public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] configs) { EGLConfig best = null; EGLConfig bestAA = null; - + 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); @@ -115,39 +106,43 @@ public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display, EGLConfig[] config // isn't set already. if (best == null && r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize) { best = config; - + // if no AA is requested we can bail out here. - if(mNumSamples == 0) { + if (mNumSamples == 0) { break; - } + } } - + // now check for MSAA support int hasSampleBuffers = findConfigAttrib(egl, display, config, EGL10.EGL_SAMPLE_BUFFERS, 0); - int numSamples = findConfigAttrib(egl, display, config, EGL10.EGL_SAMPLES, 0); - + int numSamples = findConfigAttrib(egl, display, config, EGL10.EGL_SAMPLES, 0); + // We take the first sort of matching config, thank you. - if(bestAA == null && hasSampleBuffers == 1 && numSamples >= mNumSamples && r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize) { + if (bestAA == null && hasSampleBuffers == 1 && numSamples >= mNumSamples && r == mRedSize && g == mGreenSize + && b == mBlueSize && a == mAlphaSize) { bestAA = config; continue; } - + // for this to work we need to call the extension glCoverageMaskNV which is not // exposed in the Android bindings. We'd have to link agains the NVidia SDK and // that is simply not going to happen. -// // still no luck, let's try CSAA support +// // still no luck, let's try CSAA support hasSampleBuffers = findConfigAttrib(egl, display, config, EGL_COVERAGE_BUFFERS_NV, 0); numSamples = findConfigAttrib(egl, display, config, EGL_COVERAGE_SAMPLES_NV, 0); - + // We take the first sort of matching config, thank you. - if(bestAA == null && hasSampleBuffers == 1 && numSamples >= mNumSamples && r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize) { + if (bestAA == null && hasSampleBuffers == 1 && numSamples >= mNumSamples && r == mRedSize && g == mGreenSize + && b == mBlueSize && a == mAlphaSize) { bestAA = config; continue; } } - - if(bestAA != null) return bestAA; - else return best; + + if (bestAA != null) + return bestAA; + else + return best; } private int findConfigAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) { @@ -180,15 +175,15 @@ private void printConfig (EGL10 egl, EGLDisplay display, EGLConfig config) { EGL10.EGL_LUMINANCE_SIZE, EGL10.EGL_ALPHA_MASK_SIZE, EGL10.EGL_COLOR_BUFFER_TYPE, EGL10.EGL_RENDERABLE_TYPE, 0x3042, // EGL10.EGL_CONFORMANT EGL_COVERAGE_BUFFERS_NV, /* true */ - EGL_COVERAGE_SAMPLES_NV - }; + EGL_COVERAGE_SAMPLES_NV}; 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", "EGL_COVERAGE_BUFFERS_NV", "EGL_COVERAGE_SAMPLES_NV"}; + "EGL_LUMINANCE_SIZE", "EGL_ALPHA_MASK_SIZE", "EGL_COLOR_BUFFER_TYPE", "EGL_RENDERABLE_TYPE", "EGL_CONFORMANT", + "EGL_COVERAGE_BUFFERS_NV", "EGL_COVERAGE_SAMPLES_NV"}; int[] value = new int[1]; for (int i = 0; i < attributes.length; i++) { int attribute = attributes[i]; @@ -198,8 +193,8 @@ private void printConfig (EGL10 egl, EGLDisplay display, EGLConfig config) { } else { // Log.w(TAG, String.format(" %s: failed\n", name)); egl.eglGetError(); -// while (egl.eglGetError() != EGL10.EGL_SUCCESS) -// ; +// while (egl.eglGetError() != EGL10.EGL_SUCCESS) +// ; } } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/RatioResolutionStrategy.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/RatioResolutionStrategy.java index 853afc058a2..ccb2a2362d4 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/RatioResolutionStrategy.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/RatioResolutionStrategy.java @@ -13,46 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.android.surfaceview; import android.view.View; -/** - * This {@link ResolutionStrategy} will maintain a given aspect ratio and stretch the GLSurfaceView to the maximum available screen size. - * - * @author christoph widulle - */ +/** This {@link ResolutionStrategy} will maintain a given aspect ratio and stretch the GLSurfaceView to the maximum available + * screen size. + * + * @author christoph widulle */ public class RatioResolutionStrategy implements ResolutionStrategy { - private final float ratio; + private final float ratio; - public RatioResolutionStrategy(float ratio) { - this.ratio = ratio; - } + public RatioResolutionStrategy (float ratio) { + this.ratio = ratio; + } - public RatioResolutionStrategy(final float width, final float height) { - this.ratio = width / height; - } + public RatioResolutionStrategy (final float width, final float height) { + this.ratio = width / height; + } - @Override - public MeasuredDimension calcMeasures(int widthMeasureSpec, int heightMeasureSpec) { + @Override + public MeasuredDimension calcMeasures (int widthMeasureSpec, int heightMeasureSpec) { - final int specWidth = View.MeasureSpec.getSize(widthMeasureSpec); - final int specHeight = View.MeasureSpec.getSize(heightMeasureSpec); + final int specWidth = View.MeasureSpec.getSize(widthMeasureSpec); + final int specHeight = View.MeasureSpec.getSize(heightMeasureSpec); - final float desiredRatio = ratio; - final float realRatio = (float) specWidth / specHeight; + final float desiredRatio = ratio; + final float realRatio = (float)specWidth / specHeight; - int width; - int height; - if (realRatio < desiredRatio) { - width = specWidth; - height = Math.round(width / desiredRatio); - } else { - height = specHeight; - width = Math.round(height * desiredRatio); - } + int width; + int height; + if (realRatio < desiredRatio) { + width = specWidth; + height = Math.round(width / desiredRatio); + } else { + height = specHeight; + width = Math.round(height * desiredRatio); + } - return new MeasuredDimension(width, height); - } + return new MeasuredDimension(width, height); + } } diff --git a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/ResolutionStrategy.java b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/ResolutionStrategy.java index ff5f34b2522..cd17d41831e 100644 --- a/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/ResolutionStrategy.java +++ b/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/surfaceview/ResolutionStrategy.java @@ -13,33 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.backends.android.surfaceview; +package com.badlogic.gdx.backends.android.surfaceview; -/** - * Will manipulate the GLSurfaceView. Gravity is always center. - * The width and height of the View will be determinded by the classes implementing {@link ResolutionStrategy}. - * - * @author christoph widulle - */ +/** Will manipulate the GLSurfaceView. Gravity is always center. The width and height of the View will be determinded by the + * classes implementing {@link ResolutionStrategy}. + * + * @author christoph widulle */ public interface ResolutionStrategy { + public MeasuredDimension calcMeasures (final int widthMeasureSpec, final int heightMeasureSpec); - public MeasuredDimension calcMeasures( final int widthMeasureSpec, final int heightMeasureSpec); - - - public static class MeasuredDimension { - public final int width; - public final int height; - - public MeasuredDimension(int width, int height) { - this.width = width; - this.height = height; - } - - } - + public static class MeasuredDimension { + public final int width; + public final int height; + public MeasuredDimension (int width, int height) { + this.width = width; + this.height = height; + } + } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglAnimator.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglAnimator.java index 58c5e571142..89d993d4fbe 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglAnimator.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglAnimator.java @@ -48,16 +48,14 @@ import javax.swing.RepaintManager; import javax.swing.SwingUtilities; -/** - *

    +/**

    * An Animator can be attached to one or more {@link GLAutoDrawable}s to drive their display() methods in a loop. *

    * *

    * The Animator class creates a background thread in which the calls to display() are performed. After each drawable * has been redrawn, a brief pause is performed to avoid swamping the CPU, unless {@link #setRunAsFastAsPossible} has been called. - *

    - */ + *

    */ public class JoglAnimator { volatile ArrayList/* */drawables = new ArrayList(); @@ -98,42 +96,32 @@ public synchronized void remove (GLAutoDrawable drawable) { drawables = newList; } - /** - * Returns an iterator over the drawables managed by this Animator. - */ + /** Returns an iterator over the drawables managed by this Animator. */ public Iterator/* */drawableIterator () { return drawables.iterator(); } - /** - * Sets a flag causing this Animator to ignore exceptions produced while redrawing the drawables. By default this flag is set - * to false, causing any exception thrown to halt the Animator. - */ + /** Sets a flag causing this Animator to ignore exceptions produced while redrawing the drawables. By default this flag is set + * to false, causing any exception thrown to halt the Animator. */ public void setIgnoreExceptions (boolean ignoreExceptions) { this.ignoreExceptions = ignoreExceptions; } - /** - * Sets a flag indicating that when exceptions are being ignored by this Animator (see {@link #setIgnoreExceptions}), to print - * the exceptions' stack traces for diagnostic information. Defaults to false. - */ + /** Sets a flag indicating that when exceptions are being ignored by this Animator (see {@link #setIgnoreExceptions}), to print + * the exceptions' stack traces for diagnostic information. Defaults to false. */ public void setPrintExceptions (boolean printExceptions) { this.printExceptions = printExceptions; } - /** - * Sets a flag in this Animator indicating that it is to run as fast as possible. By default there is a brief pause in the - * animation loop which prevents the CPU from getting swamped. This method may not have an effect on subclasses. - */ + /** Sets a flag in this Animator indicating that it is to run as fast as possible. By default there is a brief pause in the + * animation loop which prevents the CPU from getting swamped. This method may not have an effect on subclasses. */ public final void setRunAsFastAsPossible (boolean runFast) { runAsFastAsPossible = runFast; } - /** - * Called every frame to cause redrawing of all of the GLAutoDrawables this Animator manages. Subclasses should call this to + /** Called every frame to cause redrawing of all of the GLAutoDrawables this Animator manages. Subclasses should call this to * get the most optimized painting behavior for the set of components this Animator manages, in particular when multiple - * lightweight widgets are continually being redrawn. - */ + * lightweight widgets are continually being redrawn. */ protected void display () { Iterator iter = drawableIterator(); while (iter.hasNext()) { @@ -211,18 +199,14 @@ public synchronized void start () { thread.start(); } - /** - * Indicates whether this animator is currently running. This should only be used as a heuristic to applications because in - * some circumstances the Animator may be in the process of shutting down and this method will still return true. - */ + /** Indicates whether this animator is currently running. This should only be used as a heuristic to applications because in + * some circumstances the Animator may be in the process of shutting down and this method will still return true. */ public synchronized boolean isAnimating () { return (thread != null); } - /** - * Stops this animator. In most situations this method blocks until completion, except when called from the animation thread - * itself or in some cases from an implementation-internal thread like the AWT event queue thread. - */ + /** Stops this animator. In most situations this method blocks until completion, except when called from the animation thread + * itself or in some cases from an implementation-internal thread like the AWT event queue thread. */ public synchronized void stop () { shouldStop = true; notifyAll(); diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplication.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplication.java index 6212eb74ba8..f8916632be0 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplication.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplication.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import java.awt.BorderLayout; @@ -43,13 +44,10 @@ import com.badlogic.gdx.backends.openal.OpenALAudio; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate this class with +/** 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} or {@link InputProcessor} instances. * - * @author mzechner - * - */ + * @author mzechner */ public final class JoglApplication implements Application { JoglGraphics graphics; JoglInput input; @@ -59,8 +57,7 @@ public final class JoglApplication implements Application { List runnables = new ArrayList(); int logLevel = LOG_INFO; - /** - * Creates a new {@link JoglApplication} with the given title and dimensions. If useGL20IfAvailable is set the JoglApplication + /** 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 JoglApplication.getGraphics().getGL20(). To query * whether enabling OpenGL 2.0 was successful use the JoglApplication.getGraphics().isGL20Available() method. * @@ -68,8 +65,7 @@ public final class JoglApplication implements Application { * @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 - */ + * @param useGL20IfAvailable wheter to use OpenGL 2.0 if it is available or not */ public JoglApplication (final ApplicationListener listener, final String title, final int width, final int height, final boolean useGL20IfAvailable) { final JoglApplicationConfiguration config = new JoglApplicationConfiguration(); @@ -77,24 +73,24 @@ public JoglApplication (final ApplicationListener listener, final String title, config.width = width; config.height = height; config.useGL20 = useGL20IfAvailable; - + if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeAndWait(new Runnable() { - public void run () { + public void run () { initialize(listener, config); } }); } catch (Exception e) { throw new GdxRuntimeException("Creating window failed", e); } - } else { + } else { config.useGL20 = useGL20IfAvailable; initialize(listener, config); } } - public JoglApplication(final ApplicationListener listener, final JoglApplicationConfiguration config) { + public JoglApplication (final ApplicationListener listener, final JoglApplicationConfiguration config) { if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeAndWait(new Runnable() { @@ -109,7 +105,7 @@ public void run () { initialize(listener, config); } } - + void initialize (ApplicationListener listener, JoglApplicationConfiguration config) { JoglNativesLoader.load(); graphics = new JoglGraphics(listener, config); @@ -123,16 +119,16 @@ void initialize (ApplicationListener listener, JoglApplicationConfiguration conf Gdx.audio = JoglApplication.this.getAudio(); Gdx.files = JoglApplication.this.getFiles(); - if(!config.fullscreen) { + if (!config.fullscreen) { frame = new JFrame(config.title); graphics.getCanvas().setPreferredSize(new Dimension(config.width, config.height)); - frame.setSize(config.width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom - + config.height); + frame.setSize(config.width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + + frame.getInsets().bottom + config.height); frame.add(graphics.getCanvas(), BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLocationRelativeTo(null); frame.addWindowListener(windowListener); - + frame.pack(); frame.setVisible(true); graphics.create(); @@ -141,8 +137,8 @@ void initialize (ApplicationListener listener, JoglApplicationConfiguration conf GraphicsDevice device = genv.getDefaultScreenDevice(); frame = new JFrame(config.title); graphics.getCanvas().setPreferredSize(new Dimension(config.width, config.height)); - frame.setSize(config.width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom - + config.height); + frame.setSize(config.width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + + frame.getInsets().bottom + config.height); frame.add(graphics.getCanvas(), BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLocationRelativeTo(null); @@ -155,10 +151,11 @@ void initialize (ApplicationListener listener, JoglApplicationConfiguration conf try { device.setFullScreenWindow(frame); JoglDisplayMode mode = graphics.findBestMatch(config.width, config.height); - if(mode == null) throw new GdxRuntimeException("Couldn't set fullscreen mode " + config.width + "x" + config.height); + if (mode == null) + throw new GdxRuntimeException("Couldn't set fullscreen mode " + config.width + "x" + config.height); device.setDisplayMode(mode.mode); - } catch(Throwable e) { - e.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); device.setDisplayMode(desktopMode); device.setFullScreenWindow(null); frame.dispose(); @@ -168,20 +165,24 @@ void initialize (ApplicationListener listener, JoglApplicationConfiguration conf graphics.create(); } } - + final WindowAdapter windowListener = new WindowAdapter() { - @Override public void windowOpened (WindowEvent arg0) { + @Override + public void windowOpened (WindowEvent arg0) { graphics.getCanvas().requestFocus(); graphics.getCanvas().requestFocusInWindow(); } - @Override public void windowIconified (WindowEvent arg0) { + @Override + public void windowIconified (WindowEvent arg0) { } - @Override public void windowDeiconified (WindowEvent arg0) { + @Override + public void windowDeiconified (WindowEvent arg0) { } - @Override public void windowClosing (WindowEvent arg0) { + @Override + public void windowClosing (WindowEvent arg0) { graphics.pause(); graphics.destroy(); audio.dispose(); @@ -189,71 +190,66 @@ void initialize (ApplicationListener listener, JoglApplicationConfiguration conf } }; - /** - * {@inheritDoc} - */ - @Override public Audio getAudio () { + /** {@inheritDoc} */ + @Override + public Audio getAudio () { return audio; } - /** - * {@inheritDoc} - */ - @Override public Files getFiles () { + /** {@inheritDoc} */ + @Override + public Files getFiles () { return files; } - /** - * {@inheritDoc} - */ - @Override public Graphics getGraphics () { + /** {@inheritDoc} */ + @Override + public Graphics getGraphics () { return graphics; } - /** - * {@inheritDoc} - */ - @Override public Input getInput () { + /** {@inheritDoc} */ + @Override + public Input getInput () { return input; } - - /** - * {@inheritDoc} - */ - @Override public ApplicationType getType () { + /** {@inheritDoc} */ + @Override + public ApplicationType getType () { return ApplicationType.Desktop; } - @Override public int getVersion () { + @Override + public int getVersion () { return 0; } - @Override public long getJavaHeap () { + @Override + public long getJavaHeap () { return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } - @Override public long getNativeHeap () { + @Override + public long getNativeHeap () { return getJavaHeap(); } - - /** - * @return the JFrame of the application. - */ - public JFrame getJFrame() { + + /** @return the JFrame of the application. */ + public JFrame getJFrame () { return frame; } - - /** - * @return the GLCanvas of the application. - */ - public GLCanvas getGLCanvas() { + + /** @return the GLCanvas of the application. */ + public GLCanvas getGLCanvas () { return graphics.canvas; } Map preferences = new HashMap(); - @Override public Preferences getPreferences (String name) { - if(preferences.containsKey(name)) { + + @Override + public Preferences getPreferences (String name) { + if (preferences.containsKey(name)) { return preferences.get(name); } else { Preferences prefs = new JoglPreferences(name); @@ -262,51 +258,56 @@ public GLCanvas getGLCanvas() { } } - @Override public void postRunnable (Runnable runnable) { - synchronized(runnables) { + @Override + public void postRunnable (Runnable runnable) { + synchronized (runnables) { runnables.add(runnable); } } - public void log(String tag, String message) { - if(logLevel >= LOG_INFO) { - System.out.println(tag + ":" + message); + public void log (String tag, String message) { + if (logLevel >= LOG_INFO) { + System.out.println(tag + ":" + message); } - } + } - @Override public void log (String tag, String message, Exception exception) { - if(logLevel >= LOG_INFO) { + @Override + public void log (String tag, String message, Exception exception) { + if (logLevel >= LOG_INFO) { System.out.println(tag + ":" + message); exception.printStackTrace(System.out); } } - - @Override public void error (String tag, String message) { - if(logLevel >= LOG_ERROR) { - System.err.println(tag + ":" + message); + + @Override + public void error (String tag, String message) { + if (logLevel >= LOG_ERROR) { + System.err.println(tag + ":" + message); } } - - @Override public void error (String tag, String message, Exception exception) { - if(logLevel >= LOG_ERROR) { + @Override + public void error (String tag, String message, Exception exception) { + if (logLevel >= LOG_ERROR) { System.err.println(tag + ":" + message); exception.printStackTrace(System.err); } } - - @Override public void setLogLevel (int logLevel) { + @Override + public void setLogLevel (int logLevel) { this.logLevel = logLevel; } - - @Override public void exit () { + + @Override + public void exit () { postRunnable(new Runnable() { - @Override public void run () { + @Override + public void run () { JoglApplication.this.graphics.listener.pause(); JoglApplication.this.graphics.listener.dispose(); System.exit(-1); - } + } }); } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplicationConfiguration.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplicationConfiguration.java index 48992f1316a..1e1caad10ae 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplicationConfiguration.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplicationConfiguration.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.jogl; import java.awt.GraphicsDevice; @@ -10,7 +11,7 @@ public class JoglApplicationConfiguration { /** whether to use OpenGL ES 2.0 or not. default: false **/ - public boolean useGL20 = false; + public boolean useGL20 = false; /** number of bits per color channel **/ public int r = 8, g = 8, b = 8, a = 8; /** number of bits for depth and stencil buffer **/ @@ -24,29 +25,26 @@ public class JoglApplicationConfiguration { /** whether to enable vsync, can be changed at runtime via {@link Graphics#setVSync(boolean)} **/ public boolean vSyncEnabled = false; /** title of application **/ - public String title = "Jogl Application"; - - /** - * Sets the r, g, b and a bits per channel based on the given - * {@link DisplayMode} and sets the fullscreen flag to true. - * @param mode - */ - public void setFromDisplayMode(DisplayMode mode) { + public String title = "Jogl Application"; + + /** Sets the r, g, b and a bits per channel based on the given {@link DisplayMode} and sets the fullscreen flag to true. + * @param mode */ + public void setFromDisplayMode (DisplayMode mode) { this.width = mode.width; this.height = mode.height; - if(mode.bitsPerPixel == 16) { + if (mode.bitsPerPixel == 16) { this.r = 5; this.g = 6; this.b = 5; this.a = 0; } - if(mode.bitsPerPixel == 24) { + if (mode.bitsPerPixel == 24) { this.r = 8; this.g = 8; this.b = 8; this.a = 0; } - if(mode.bitsPerPixel == 32) { + if (mode.bitsPerPixel == 32) { this.r = 8; this.g = 8; this.b = 8; @@ -54,36 +52,35 @@ public void setFromDisplayMode(DisplayMode mode) { } this.fullscreen = true; } - + public static DisplayMode getDesktopDisplayMode () { GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = genv.getDefaultScreenDevice(); java.awt.DisplayMode mode = device.getDisplayMode(); return new JoglDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth(), mode); } - - public static DisplayMode[] getDisplayModes() { + + public static DisplayMode[] getDisplayModes () { GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = genv.getDefaultScreenDevice(); java.awt.DisplayMode desktopMode = device.getDisplayMode(); java.awt.DisplayMode[] displayModes = device.getDisplayModes(); ArrayList modes = new ArrayList(); int idx = 0; - for(java.awt.DisplayMode mode: displayModes) { + for (java.awt.DisplayMode mode : displayModes) { boolean duplicate = false; - for(int i = 0; i < modes.size(); i++) { - if(modes.get(i).width == mode.getWidth() && - modes.get(i).height == mode.getHeight() && - modes.get(i).bitsPerPixel == mode.getBitDepth()) { + for (int i = 0; i < modes.size(); i++) { + if (modes.get(i).width == mode.getWidth() && modes.get(i).height == mode.getHeight() + && modes.get(i).bitsPerPixel == mode.getBitDepth()) { duplicate = true; break; } } - if(duplicate) continue; - if(mode.getBitDepth() != desktopMode.getBitDepth()) continue; + if (duplicate) continue; + if (mode.getBitDepth() != desktopMode.getBitDepth()) continue; modes.add(new JoglDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth(), mode)); } - + return modes.toArray(new DisplayMode[modes.size()]); } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFileHandle.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFileHandle.java index 15999bc3e39..2effd9a8779 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFileHandle.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFileHandle.java @@ -21,10 +21,8 @@ import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.files.FileHandle; -/** - * @author mzechner - * @author Nathan Sweet - */ +/** @author mzechner + * @author Nathan Sweet */ public class JoglFileHandle extends FileHandle { JoglFileHandle (String fileName, FileType type) { super(fileName, type); diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFiles.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFiles.java index 1dfb7b4301a..98ff652fd88 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFiles.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglFiles.java @@ -13,43 +13,49 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import com.badlogic.gdx.Files; import com.badlogic.gdx.files.FileHandle; -/** - * @author mzechner - * @author Nathan Sweet - */ +/** @author mzechner + * @author Nathan Sweet */ final class JoglFiles implements Files { private final String externalPath = System.getProperty("user.home") + "/"; - @Override public FileHandle getFileHandle (String fileName, FileType type) { + @Override + public FileHandle getFileHandle (String fileName, FileType type) { return new JoglFileHandle(fileName, type); } - @Override public FileHandle classpath (String path) { + @Override + public FileHandle classpath (String path) { return new JoglFileHandle(path, FileType.Classpath); } - @Override public FileHandle internal (String path) { + @Override + public FileHandle internal (String path) { return new JoglFileHandle(path, FileType.Internal); } - @Override public FileHandle external (String path) { + @Override + public FileHandle external (String path) { return new JoglFileHandle(path, FileType.External); } - @Override public FileHandle absolute (String path) { + @Override + public FileHandle absolute (String path) { return new JoglFileHandle(path, FileType.Absolute); } - @Override public String getExternalStoragePath () { + @Override + public String getExternalStoragePath () { return externalPath; } - @Override public boolean isExternalStorageAvailable () { + @Override + public boolean isExternalStorageAvailable () { return true; } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL10.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL10.java index 7a873a17860..ab9cac04d27 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL10.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL10.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import java.nio.Buffer; @@ -23,12 +24,9 @@ import com.badlogic.gdx.graphics.GL10; -/** - * An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex arrays are emulated. - * - * @author mzechner +/** An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex arrays are emulated. * - */ + * @author mzechner */ class JoglGL10 implements GL10 { protected final javax.media.opengl.GL gl; @@ -36,39 +34,48 @@ public JoglGL10 (javax.media.opengl.GL gl) { this.gl = gl; } - @Override public final void glActiveTexture (int texture) { + @Override + public final void glActiveTexture (int texture) { gl.glActiveTexture(texture); } - @Override public final void glAlphaFunc (int func, float ref) { + @Override + public final void glAlphaFunc (int func, float ref) { gl.glAlphaFunc(func, ref); } - @Override public final void glBindTexture (int target, int texture) { + @Override + public final void glBindTexture (int target, int texture) { gl.glBindTexture(target, texture); } - @Override public final void glBlendFunc (int sfactor, int dfactor) { + @Override + public final void glBlendFunc (int sfactor, int dfactor) { gl.glBlendFunc(sfactor, dfactor); } - @Override public final void glClear (int mask) { + @Override + public final void glClear (int mask) { gl.glClear(mask); } - @Override public final void glClearColor (float red, float green, float blue, float alpha) { + @Override + public final void glClearColor (float red, float green, float blue, float alpha) { gl.glClearColor(red, green, blue, alpha); } - @Override public final void glClearDepthf (float depth) { + @Override + public final void glClearDepthf (float depth) { gl.glClearDepth(depth); } - @Override public final void glClearStencil (int 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) { try { gl.glClientActiveTexture(texture); } catch (Throwable ex) { @@ -76,328 +83,405 @@ public JoglGL10 (javax.media.opengl.GL gl) { } } - @Override public final void glColor4f (float red, float green, float blue, float alpha) { + @Override + public final void glColor4f (float red, float green, float blue, float alpha) { gl.glColor4f(red, green, blue, alpha); } - @Override public final void glColorMask (boolean red, boolean green, boolean blue, boolean 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) { + @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) { + @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, + @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) { + @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) { + @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) { + @Override + public final void glCullFace (int mode) { gl.glCullFace(mode); } - @Override public final void glDeleteTextures (int n, IntBuffer textures) { + @Override + public final void glDeleteTextures (int n, IntBuffer textures) { gl.glDeleteTextures(n, textures); } - @Override public final void glDepthFunc (int func) { + @Override + public final void glDepthFunc (int func) { gl.glDepthFunc(func); } - @Override public final void glDepthMask (boolean flag) { + @Override + public final void glDepthMask (boolean flag) { gl.glDepthMask(flag); } - @Override public final void glDepthRangef (float zNear, float zFar) { + @Override + public final void glDepthRangef (float zNear, float zFar) { gl.glDepthRange(zNear, zFar); } - @Override public final void glDisable (int cap) { + @Override + public final void glDisable (int cap) { gl.glDisable(cap); } - @Override public final void glDisableClientState (int array) { + @Override + public final void glDisableClientState (int array) { gl.glDisableClientState(array); } - @Override public final void glDrawArrays (int mode, int first, int 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) { + @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) { + @Override + public final void glEnable (int cap) { gl.glEnable(cap); } - @Override public final void glEnableClientState (int 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) { + @Override + public final void glFogf (int pname, float param) { gl.glFogf(pname, param); } - @Override public final void glFogfv (int pname, FloatBuffer params) { + @Override + public final void glFogfv (int pname, FloatBuffer params) { gl.glFogfv(pname, params); } - @Override public final void glFrontFace (int 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) { + @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 glGenTextures (int n, IntBuffer 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) { + @Override + public final void glGetIntegerv (int pname, IntBuffer params) { gl.glGetIntegerv(pname, params); } - @Override public final String glGetString (int name) { + @Override + public final String glGetString (int name) { return gl.glGetString(name); } - @Override public final void glHint (int target, int mode) { + @Override + public final void glHint (int target, int mode) { gl.glHint(target, mode); } - @Override public final void glLightModelf (int pname, float param) { + @Override + public final void glLightModelf (int pname, float param) { gl.glLightModelf(pname, param); } - @Override public final void glLightModelfv (int pname, FloatBuffer params) { + @Override + public final void glLightModelfv (int pname, FloatBuffer params) { gl.glLightModelfv(pname, params); } - @Override public final void glLightf (int light, int pname, float 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) { + @Override + public final void glLightfv (int light, int pname, FloatBuffer params) { gl.glLightfv(light, pname, params); } - @Override public final void glLineWidth (float width) { + @Override + public final void glLineWidth (float width) { gl.glLineWidth(width); } - @Override public final void glLoadIdentity () { + @Override + public final void glLoadIdentity () { gl.glLoadIdentity(); } - @Override public final void glLoadMatrixf (FloatBuffer m) { + @Override + public final void glLoadMatrixf (FloatBuffer m) { gl.glLoadMatrixf(m); } - @Override public final void glLogicOp (int opcode) { + @Override + public final void glLogicOp (int opcode) { gl.glLogicOp(opcode); } - @Override public final void glMaterialf (int face, int pname, float 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) { + @Override + public final void glMaterialfv (int face, int pname, FloatBuffer params) { gl.glMaterialfv(face, pname, params); } - @Override public final void glMatrixMode (int mode) { + @Override + public final void glMatrixMode (int mode) { gl.glMatrixMode(mode); } - @Override public final void glMultMatrixf (FloatBuffer m) { + @Override + public final void glMultMatrixf (FloatBuffer m) { gl.glMultMatrixf(m); } - @Override public final void glMultiTexCoord4f (int target, float s, float t, float r, float 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 glNormal3f (float nx, float ny, float nz) { + @Override + public final void glNormal3f (float nx, float ny, float nz) { gl.glNormal3f(nx, ny, nz); } - @Override public final void glNormalPointer (int type, int stride, Buffer 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) { + @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 glPixelStorei (int pname, int param) { + @Override + public final void glPixelStorei (int pname, int param) { gl.glPixelStorei(pname, param); } - @Override public final void glPointSize (float size) { + @Override + public final void glPointSize (float size) { gl.glPointSize(size); } - @Override public final void glPolygonOffset (float factor, float units) { + @Override + public final void glPolygonOffset (float factor, float units) { gl.glPolygonOffset(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) { + @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) { + @Override + public final void glRotatef (float angle, float x, float y, float z) { gl.glRotatef(angle, x, y, z); } - @Override public final void glSampleCoverage (float value, boolean invert) { + @Override + public final void glSampleCoverage (float value, boolean invert) { gl.glSampleCoverage(value, invert); } - @Override public final void glScalef (float x, float y, float z) { + @Override + public final void glScalef (float x, float y, float z) { gl.glScalef(x, y, z); } - @Override public final void glScissor (int x, int y, int width, int 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) { + @Override + public final void glStencilFunc (int func, int ref, int mask) { gl.glStencilFunc(func, ref, mask); } - @Override public final void glStencilMask (int mask) { + @Override + public final void glStencilMask (int mask) { gl.glStencilMask(mask); } - @Override public final void glStencilOp (int fail, int zfail, int 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) { + @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) { + @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) { + @Override + public final void glTexEnvfv (int target, int pname, FloatBuffer params) { gl.glTexEnvfv(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) { + @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) { + @Override + public final void glTexParameterf (int target, int pname, float param) { // JoglGL10.major is should to be 1 if we are in JoglGL10. if (JoglGraphics.minor < 2 && param == GL.GL_CLAMP_TO_EDGE) param = GL.GL_CLAMP; gl.glTexParameterf(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) { + @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) { + @Override + public final void glTranslatef (float x, float y, float z) { gl.glTranslatef(x, y, z); } - @Override public final void glVertexPointer (int size, int type, int stride, Buffer pointer) { + @Override + public final void glVertexPointer (int size, int type, int stride, Buffer pointer) { gl.glVertexPointer(size, GL10.GL_FLOAT, stride, pointer); } - @Override public final void glViewport (int x, int y, int width, int 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) { + @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) { + @Override + public final void glFogfv (int pname, float[] params, int offset) { gl.glFogfv(pname, params, offset); } - @Override public final void glGenTextures (int n, int[] textures, int 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) { + @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) { + @Override + public final void glLightModelfv (int pname, float[] params, int offset) { gl.glLightModelfv(pname, params, offset); } - @Override public final void glLightfv (int light, int pname, float[] params, int offset) { + @Override + public final void glLightfv (int light, int pname, float[] params, int offset) { gl.glLightfv(light, pname, params, offset); } - @Override public final void glLoadMatrixf (float[] m, int offset) { + @Override + public final void glLoadMatrixf (float[] m, int offset) { gl.glLoadMatrixf(m, offset); } - @Override public final void glMaterialfv (int face, int pname, float[] params, int offset) { + @Override + public final void glMaterialfv (int face, int pname, float[] params, int offset) { gl.glMaterialfv(face, pname, params, offset); } - @Override public final void glMultMatrixf (float[] m, int offset) { + @Override + public final void glMultMatrixf (float[] m, int offset) { gl.glMultMatrixf(m, offset); } - @Override public final void glTexEnvfv (int target, int pname, float[] params, int offset) { + @Override + public final void glTexEnvfv (int target, int pname, float[] params, int offset) { gl.glTexEnvfv(target, pname, params, offset); } - @Override public void glPolygonMode (int face, int mode) { + @Override + public void glPolygonMode (int face, int mode) { gl.glPolygonMode(face, mode); } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL11.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL11.java index 0f6544e814b..402e3650c26 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL11.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL11.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import java.nio.Buffer; @@ -23,212 +24,258 @@ 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 +/** An implementation of the {@link GL11} interface based on Jogl. Fixed point vertex arrays are emulated. Some glGetXXX methods * are not implemented. * - * @author mzechner - * - */ + * @author mzechner */ public final class JoglGL11 extends JoglGL10 implements GL11 { public JoglGL11 (GL gl) { super(gl); } - @Override public void glBindBuffer (int target, int 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) { + @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) { + @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) { + @Override + public void glClipPlanef (int plane, float[] equation, int offset) { throw new UnsupportedOperationException("not implemented"); } - @Override public void glClipPlanef (int plane, FloatBuffer equation) { + @Override + public void glClipPlanef (int plane, FloatBuffer equation) { throw new UnsupportedOperationException("not implemented"); } - @Override public void glColor4ub (byte red, byte green, byte blue, byte alpha) { + @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) { + @Override + public void glDeleteBuffers (int n, int[] buffers, int offset) { gl.glDeleteBuffers(n, buffers, offset); } - @Override public void glDeleteBuffers (int n, IntBuffer buffers) { + @Override + public void glDeleteBuffers (int n, IntBuffer buffers) { gl.glDeleteBuffers(n, buffers); } - @Override public void glGenBuffers (int n, int[] buffers, int offset) { + @Override + public void glGenBuffers (int n, int[] buffers, int offset) { gl.glGenBuffers(n, buffers, offset); } - @Override public void glGenBuffers (int n, IntBuffer buffers) { + @Override + public void glGenBuffers (int n, IntBuffer buffers) { gl.glGenBuffers(n, buffers); } - @Override public void glGetBooleanv (int pname, boolean[] params, int offset) { + @Override + public void glGetBooleanv (int pname, boolean[] params, int offset) { throw new UnsupportedOperationException("not implemented"); } - @Override public void glGetBooleanv (int pname, IntBuffer params) { + @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) { + @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) { + @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) { + @Override + public void glGetClipPlanef (int pname, float[] eqn, int offset) { throw new UnsupportedOperationException("not implemented"); } - @Override public void glGetClipPlanef (int pname, FloatBuffer eqn) { + @Override + public void glGetClipPlanef (int pname, FloatBuffer eqn) { throw new UnsupportedOperationException("not implemented"); } - @Override public void glGetFloatv (int pname, float[] params, int offset) { + @Override + public void glGetFloatv (int pname, float[] params, int offset) { gl.glGetFloatv(pname, params, offset); } - @Override public void glGetFloatv (int pname, FloatBuffer 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) { + @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) { + @Override + public void glGetLightfv (int light, int pname, FloatBuffer params) { gl.glGetLightfv(light, pname, params); } - @Override public void glGetMaterialfv (int face, int pname, float[] params, int 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) { + @Override + public void glGetMaterialfv (int face, int pname, FloatBuffer params) { gl.glGetMaterialfv(face, pname, params); } - @Override public void glGetPointerv (int pname, Buffer[] params) { + @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) { + @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) { + @Override + public void glGetTexEnviv (int env, int pname, IntBuffer params) { gl.glGetTexEnviv(env, pname, params); } - @Override public void glGetTexParameterfv (int target, int pname, float[] params, int 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) { + @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) { + @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) { + @Override + public void glGetTexParameteriv (int target, int pname, IntBuffer params) { gl.glGetTexParameteriv(target, pname, params); } - @Override public boolean glIsBuffer (int buffer) { + @Override + public boolean glIsBuffer (int buffer) { return gl.glIsBuffer(buffer); } - @Override public boolean glIsEnabled (int cap) { + @Override + public boolean glIsEnabled (int cap) { return gl.glIsEnabled(cap); } - @Override public boolean glIsTexture (int texture) { + @Override + public boolean glIsTexture (int texture) { return gl.glIsTexture(texture); } - @Override public void glPointParameterf (int pname, float param) { + @Override + public void glPointParameterf (int pname, float param) { gl.glPointParameterf(pname, param); } - @Override public void glPointParameterfv (int pname, float[] params, int offset) { + @Override + public void glPointParameterfv (int pname, float[] params, int offset) { gl.glPointParameterfv(pname, params, offset); } - @Override public void glPointParameterfv (int pname, FloatBuffer params) { + @Override + public void glPointParameterfv (int pname, FloatBuffer params) { gl.glPointParameterfv(pname, params); } - @Override public void glPointSizePointerOES (int type, int stride, Buffer pointer) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public void glTexParameteriv (int target, int pname, IntBuffer params) { gl.glTexParameteriv(target, pname, params); } - @Override public void glColorPointer (int size, int type, int stride, int 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) { + @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) { + @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) { + @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) { + @Override + public void glDrawElements (int mode, int count, int type, int indices) { gl.glDrawElements(mode, count, type, indices); } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL20.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL20.java index 4bdc1d1eb0b..25cd0c5c701 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL20.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGL20.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import java.nio.Buffer; @@ -25,13 +26,10 @@ 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% +/** 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 - * - */ + * @author mzechner */ final class JoglGL20 implements GL20 { private final GL gl; @@ -39,282 +37,346 @@ public JoglGL20 (GL gl) { this.gl = gl; } - @Override public void glActiveTexture (int texture) { + @Override + public void glActiveTexture (int texture) { gl.glActiveTexture(texture); } - @Override public void glAttachShader (int program, int shader) { + @Override + public void glAttachShader (int program, int shader) { gl.glAttachShader(program, shader); } - @Override public void glBindAttribLocation (int program, int index, String name) { + @Override + public void glBindAttribLocation (int program, int index, String name) { gl.glBindAttribLocation(program, index, name); } - @Override public void glBindBuffer (int target, int buffer) { + @Override + public void glBindBuffer (int target, int buffer) { gl.glBindBuffer(target, buffer); } - @Override public void glBindFramebuffer (int target, int framebuffer) { + @Override + public void glBindFramebuffer (int target, int framebuffer) { gl.glBindFramebufferEXT(target, framebuffer); } - @Override public void glBindRenderbuffer (int target, int renderbuffer) { + @Override + public void glBindRenderbuffer (int target, int renderbuffer) { gl.glBindRenderbufferEXT(target, renderbuffer); } - @Override public void glBindTexture (int target, int 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) { + @Override + public void glBlendColor (float red, float green, float blue, float alpha) { gl.glBlendColor(red, green, blue, alpha); } - @Override public void glBlendEquation (int mode) { + @Override + public void glBlendEquation (int mode) { gl.glBlendEquation(mode); } - @Override public void glBlendEquationSeparate (int modeRGB, int modeAlpha) { + @Override + public void glBlendEquationSeparate (int modeRGB, int modeAlpha) { gl.glBlendEquationSeparate(modeRGB, modeAlpha); } - @Override public void glBlendFunc (int sfactor, int 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) { + @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) { + @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) { + @Override + public void glBufferSubData (int target, int offset, int size, Buffer data) { gl.glBufferSubData(target, offset, size, data); } - @Override public int glCheckFramebufferStatus (int target) { + @Override + public int glCheckFramebufferStatus (int target) { return gl.glCheckFramebufferStatusEXT(target); } - @Override public void glClear (int mask) { + @Override + public void glClear (int mask) { gl.glClear(mask); } - @Override public void glClearColor (float red, float green, float blue, float 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) { + @Override + public void glClearDepthf (float depth) { gl.glClearDepth(depth); } - @Override public void glClearStencil (int s) { + @Override + public void glClearStencil (int s) { gl.glClearStencil(s); } - @Override public void glColorMask (boolean red, boolean green, boolean blue, boolean 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) { + @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, + @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) { + @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) { + @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) { + @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) { + @Override + public int glCreateShader (int type) { return gl.glCreateShader(type); } - @Override public void glCullFace (int mode) { + @Override + public void glCullFace (int mode) { gl.glCullFace(mode); } - @Override public void glDeleteBuffers (int n, IntBuffer buffers) { + @Override + public void glDeleteBuffers (int n, IntBuffer buffers) { gl.glDeleteBuffers(n, buffers); } - @Override public void glDeleteFramebuffers (int n, IntBuffer framebuffers) { + @Override + public void glDeleteFramebuffers (int n, IntBuffer framebuffers) { gl.glDeleteFramebuffersEXT(n, framebuffers); } - @Override public void glDeleteProgram (int program) { + @Override + public void glDeleteProgram (int program) { gl.glDeleteProgram(program); } - @Override public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) { + @Override + public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) { gl.glDeleteRenderbuffersEXT(n, renderbuffers); } - @Override public void glDeleteShader (int shader) { + @Override + public void glDeleteShader (int shader) { gl.glDeleteShader(shader); } - @Override public void glDeleteTextures (int n, IntBuffer textures) { + @Override + public void glDeleteTextures (int n, IntBuffer textures) { gl.glDeleteTextures(n, textures); } - @Override public void glDepthFunc (int func) { + @Override + public void glDepthFunc (int func) { gl.glDepthFunc(func); } - @Override public void glDepthMask (boolean flag) { + @Override + public void glDepthMask (boolean flag) { gl.glDepthMask(flag); } - @Override public void glDepthRangef (float zNear, float zFar) { + @Override + public void glDepthRangef (float zNear, float zFar) { gl.glDepthRange(zNear, zFar); } - @Override public void glDetachShader (int program, int shader) { + @Override + public void glDetachShader (int program, int shader) { gl.glDetachShader(program, shader); } - @Override public void glDisable (int cap) { + @Override + public void glDisable (int cap) { gl.glDisable(cap); } - @Override public void glDisableVertexAttribArray (int index) { + @Override + public void glDisableVertexAttribArray (int index) { gl.glDisableVertexAttribArray(index); } - @Override public void glDrawArrays (int mode, int first, int 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) { + @Override + public void glDrawElements (int mode, int count, int type, Buffer indices) { gl.glDrawElements(mode, count, type, indices); } - @Override public void glEnable (int cap) { + @Override + public void glEnable (int cap) { gl.glEnable(cap); } - @Override public void glEnableVertexAttribArray (int index) { + @Override + public void glEnableVertexAttribArray (int index) { gl.glEnableVertexAttribArray(index); } - @Override public void glFinish () { + @Override + public void glFinish () { gl.glFinish(); } - @Override public void glFlush () { + @Override + public void glFlush () { gl.glFlush(); } - @Override public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int 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) { + @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) { + @Override + public void glFrontFace (int mode) { gl.glFrontFace(mode); } - @Override public void glGenBuffers (int n, IntBuffer buffers) { + @Override + public void glGenBuffers (int n, IntBuffer buffers) { gl.glGenBuffers(n, buffers); } - @Override public void glGenFramebuffers (int n, IntBuffer framebuffers) { + @Override + public void glGenFramebuffers (int n, IntBuffer framebuffers) { gl.glGenFramebuffersEXT(n, framebuffers); } - @Override public void glGenRenderbuffers (int n, IntBuffer renderbuffers) { + @Override + public void glGenRenderbuffers (int n, IntBuffer renderbuffers) { gl.glGenRenderbuffersEXT(n, renderbuffers); } - @Override public void glGenTextures (int n, IntBuffer textures) { + @Override + public void glGenTextures (int n, IntBuffer textures) { gl.glGenTextures(n, textures); } - @Override public void glGenerateMipmap (int target) { + @Override + public void glGenerateMipmap (int target) { gl.glGenerateMipmapEXT(target); } - @Override public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) { + @Override + public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) { int[] length = new int[1]; int[] sizeTmp = new int[2]; int[] typeTmp = new int[1]; byte[] name = new byte[256]; gl.glGetActiveAttrib(program, index, 256, length, 0, sizeTmp, 0, typeTmp, 0, name, 0); - + size.put(sizeTmp[0]); - if(type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp[0]); + if (type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp[0]); return new String(name, 0, length[0]); } - @Override public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) { + @Override + public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) { int[] length = new int[1]; int[] sizeTmp = new int[2]; int[] typeTmp = new int[1]; byte[] name = new byte[256]; gl.glGetActiveUniform(program, index, 256, length, 0, sizeTmp, 0, typeTmp, 0, name, 0); - + size.put(sizeTmp[0]); - if(type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp[0]); + if (type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp[0]); return new String(name, 0, length[0]); } - @Override public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer 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) { + @Override + public int glGetAttribLocation (int program, String name) { return gl.glGetAttribLocation(program, name); } - @Override public void glGetBooleanv (int pname, Buffer params) { + @Override + public void glGetBooleanv (int pname, Buffer params) { throw new UnsupportedOperationException("not implemented"); // FIXME } - @Override public void glGetBufferParameteriv (int target, int pname, IntBuffer 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) { + @Override + public void glGetFloatv (int pname, FloatBuffer params) { gl.glGetFloatv(pname, params); } - @Override public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer 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) { + @Override + public void glGetIntegerv (int pname, IntBuffer params) { gl.glGetIntegerv(pname, params); } - @Override public String glGetProgramInfoLog (int program) { + @Override + public String glGetProgramInfoLog (int program) { ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10); buffer.order(ByteOrder.nativeOrder()); ByteBuffer tmp = ByteBuffer.allocateDirect(4); @@ -328,15 +390,18 @@ public JoglGL20 (GL gl) { return new String(bytes); } - @Override public void glGetProgramiv (int program, int pname, IntBuffer 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) { + @Override + public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params) { gl.glGetRenderbufferParameterivEXT(target, pname, params); } - @Override public String glGetShaderInfoLog (int shader) { + @Override + public String glGetShaderInfoLog (int shader) { ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10); buffer.order(ByteOrder.nativeOrder()); ByteBuffer tmp = ByteBuffer.allocateDirect(4); @@ -350,310 +415,386 @@ public JoglGL20 (GL gl) { return new String(bytes); } - @Override public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) { + @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) { + @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) { + @Override + public void glGetShaderiv (int shader, int pname, IntBuffer params) { gl.glGetShaderiv(shader, pname, params); } - @Override public String glGetString (int name) { + @Override + public String glGetString (int name) { return gl.glGetString(name); } - @Override public void glGetTexParameterfv (int target, int pname, FloatBuffer 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) { + @Override + public void glGetTexParameteriv (int target, int pname, IntBuffer params) { gl.glGetTexParameteriv(target, pname, params); } - @Override public int glGetUniformLocation (int program, String name) { + @Override + public int glGetUniformLocation (int program, String name) { return gl.glGetUniformLocation(program, name); } - @Override public void glGetUniformfv (int program, int location, FloatBuffer 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) { + @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) { + @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) { + @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) { + @Override + public void glGetVertexAttribiv (int index, int pname, IntBuffer params) { gl.glGetVertexAttribiv(index, pname, params); } - @Override public void glHint (int target, int mode) { + @Override + public void glHint (int target, int mode) { gl.glHint(target, mode); } - @Override public boolean glIsBuffer (int buffer) { + @Override + public boolean glIsBuffer (int buffer) { return gl.glIsBuffer(buffer); } - @Override public boolean glIsEnabled (int 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) { + @Override + public boolean glIsProgram (int program) { return gl.glIsProgram(program); } - @Override public boolean glIsRenderbuffer (int renderbuffer) { + @Override + public boolean glIsRenderbuffer (int renderbuffer) { return gl.glIsRenderbufferEXT(renderbuffer); } - @Override public boolean glIsShader (int shader) { + @Override + public boolean glIsShader (int shader) { return gl.glIsShader(shader); } - @Override public boolean glIsTexture (int texture) { + @Override + public boolean glIsTexture (int texture) { return gl.glIsTexture(texture); } - @Override public void glLineWidth (float width) { + @Override + public void glLineWidth (float width) { gl.glLineWidth(width); } - @Override public void glLinkProgram (int program) { + @Override + public void glLinkProgram (int program) { gl.glLinkProgram(program); } - @Override public void glPixelStorei (int pname, int param) { + @Override + public void glPixelStorei (int pname, int param) { gl.glPixelStorei(pname, param); } - @Override public void glPolygonOffset (float factor, float 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) { + @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) { + @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) { + @Override + public void glSampleCoverage (float value, boolean invert) { gl.glSampleCoverage(value, invert); } - @Override public void glScissor (int x, int y, int width, int 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) { + @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) { + @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) { + @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) { + @Override + public void glStencilFuncSeparate (int face, int func, int ref, int mask) { gl.glStencilFuncSeparate(face, func, ref, mask); } - @Override public void glStencilMask (int mask) { + @Override + public void glStencilMask (int mask) { gl.glStencilMask(mask); } - @Override public void glStencilMaskSeparate (int face, int mask) { + @Override + public void glStencilMaskSeparate (int face, int mask) { gl.glStencilMaskSeparate(face, mask); } - @Override public void glStencilOp (int fail, int zfail, int 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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public void glUniform1f (int location, float x) { gl.glUniform1f(location, x); } - @Override public void glUniform1fv (int location, int count, FloatBuffer v) { + @Override + public void glUniform1fv (int location, int count, FloatBuffer v) { gl.glUniform1fv(location, count, v); } - @Override public void glUniform1i (int location, int x) { + @Override + public void glUniform1i (int location, int x) { gl.glUniform1i(location, x); } - @Override public void glUniform1iv (int location, int count, IntBuffer 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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value) { gl.glUniformMatrix4fv(location, count, transpose, value); } - @Override public void glUseProgram (int program) { + @Override + public void glUseProgram (int program) { gl.glUseProgram(program); } - @Override public void glValidateProgram (int program) { + @Override + public void glValidateProgram (int program) { gl.glValidateProgram(program); } - @Override public void glVertexAttrib1f (int indx, float x) { + @Override + public void glVertexAttrib1f (int indx, float x) { gl.glVertexAttrib1f(indx, x); } - @Override public void glVertexAttrib1fv (int indx, FloatBuffer values) { + @Override + public void glVertexAttrib1fv (int indx, FloatBuffer values) { gl.glVertexAttrib1fv(indx, values); } - @Override public void glVertexAttrib2f (int indx, float x, float y) { + @Override + public void glVertexAttrib2f (int indx, float x, float y) { gl.glVertexAttrib2f(indx, x, y); } - @Override public void glVertexAttrib2fv (int indx, FloatBuffer 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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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-jogl/src/com/badlogic/gdx/backends/jogl/JoglGLU.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGLU.java index 53ce2feb976..511acff842f 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGLU.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGLU.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import javax.media.opengl.glu.GLU; @@ -25,20 +26,24 @@ public class JoglGLU implements com.badlogic.gdx.graphics.GLU { double projectd[] = new double[16]; double wind[] = new double[3]; - @Override public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, - float upX, float upY, float upZ) { + @Override + public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, + float upY, float upZ) { glu.gluLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } - @Override public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { + @Override + public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { glu.gluOrtho2D(left, right, bottom, top); } - @Override public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { + @Override + public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { glu.gluPerspective(fovy, aspect, zNear, zFar); } - @Override public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] win, int winOffset) { for (int i = 0; i < 16; i++) { modeld[i] = model[modelOffset + i]; @@ -51,7 +56,8 @@ public class JoglGLU implements com.badlogic.gdx.graphics.GLU { return result; } - @Override public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] obj, int objOffset) { for (int i = 0; i < 16; i++) { modeld[i] = model[modelOffset + i]; diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphics.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphics.java index cfe8ceb5afc..ae9d49a1cfe 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphics.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphics.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import java.awt.BorderLayout; @@ -25,7 +26,6 @@ import java.awt.Toolkit; import java.util.List; -import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLCapabilities; @@ -41,19 +41,16 @@ import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Implements the {@link Graphics} interface with Jogl. - * - * @author mzechner +/** Implements the {@link Graphics} interface with Jogl. * - */ + * @author mzechner */ public class JoglGraphics extends JoglGraphicsBase implements GLEventListener { ApplicationListener listener = null; boolean useGL2; - boolean created = false; + boolean created = false; boolean exclusiveMode = false; final JoglDisplayMode desktopMode; - final JoglApplicationConfiguration config; + final JoglApplicationConfiguration config; String extensions; public JoglGraphics (ApplicationListener listener, JoglApplicationConfiguration config) { @@ -61,12 +58,12 @@ public JoglGraphics (ApplicationListener listener, JoglApplicationConfiguration if (listener == null) throw new GdxRuntimeException("RenderListener must not be null"); this.listener = listener; this.config = config; - + desktopMode = (JoglDisplayMode)JoglApplicationConfiguration.getDesktopDisplayMode(); } public void create () { - super.create(); + super.create(); } public void pause () { @@ -81,10 +78,11 @@ public void resume () { super.resume(); } - @Override public void init (GLAutoDrawable drawable) { + @Override + public void init (GLAutoDrawable drawable) { initializeGLInstances(drawable); setVSync(config.vSyncEnabled); - + if (!created) { listener.create(); synchronized (this) { @@ -94,17 +92,19 @@ public void resume () { } } - @Override public void reshape (GLAutoDrawable drawable, int x, int y, int width, int height) { - listener.resize(width, height); + @Override + public void reshape (GLAutoDrawable drawable, int x, int y, int width, int height) { + listener.resize(width, height); } - @Override public void display (GLAutoDrawable arg0) { + @Override + public void display (GLAutoDrawable arg0) { synchronized (this) { if (!paused) { updateTimes(); synchronized (((JoglApplication)Gdx.app).runnables) { List runnables = ((JoglApplication)Gdx.app).runnables; - for(int i = 0; i < runnables.size(); i++) { + for (int i = 0; i < runnables.size(); i++) { runnables.get(i).run(); } runnables.clear(); @@ -116,7 +116,8 @@ public void resume () { } } - @Override public void displayChanged (GLAutoDrawable arg0, boolean arg1, boolean arg2) { + @Override + public void displayChanged (GLAutoDrawable arg0, boolean arg1, boolean arg2) { } @@ -128,49 +129,57 @@ public void destroy () { device.setFullScreenWindow(null); } - @Override public float getPpiX () { + @Override + public float getPpiX () { return Toolkit.getDefaultToolkit().getScreenResolution(); } - @Override public float getPpiY () { + @Override + public float getPpiY () { return Toolkit.getDefaultToolkit().getScreenResolution(); } - @Override public float getPpcX () { + @Override + public float getPpcX () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f); } - @Override public float getPpcY () { + @Override + public float getPpcY () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f); } - - @Override public float getDensity () { + + @Override + public float getDensity () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 160f); } - - @Override public boolean supportsDisplayModeChange () { + + @Override + public boolean supportsDisplayModeChange () { GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = genv.getDefaultScreenDevice(); - return device.isFullScreenSupported() && (Gdx.app instanceof JoglApplication); + return device.isFullScreenSupported() && (Gdx.app instanceof JoglApplication); } - + protected static class JoglDisplayMode extends DisplayMode { final java.awt.DisplayMode mode; - + protected JoglDisplayMode (int width, int height, int refreshRate, int bitsPerPixel, java.awt.DisplayMode mode) { super(width, height, refreshRate, bitsPerPixel); this.mode = mode; - } + } } - - @Override public DisplayMode[] getDisplayModes () { + + @Override + public DisplayMode[] getDisplayModes () { return JoglApplicationConfiguration.getDisplayModes(); } - @Override public void setTitle (String title) { + @Override + public void setTitle (String title) { Container parent = canvas.getParent(); - while(parent != null) { - if(parent instanceof JFrame) { + while (parent != null) { + if (parent instanceof JFrame) { ((JFrame)parent).setTitle(title); return; } @@ -178,167 +187,180 @@ protected JoglDisplayMode (int width, int height, int refreshRate, int bitsPerPi } } - @Override public void setIcon (Pixmap pixmap) { - + @Override + public void setIcon (Pixmap pixmap) { + } - @Override public DisplayMode getDesktopDisplayMode () { + @Override + public DisplayMode getDesktopDisplayMode () { return desktopMode; } - - - @Override public boolean setDisplayMode (int width, int height, boolean fullscreen) { - if(!supportsDisplayModeChange()) return false; - - if(!fullscreen) { - setWindowedMode(width, height); + + @Override + public boolean setDisplayMode (int width, int height, boolean fullscreen) { + if (!supportsDisplayModeChange()) return false; + + if (!fullscreen) { + setWindowedMode(width, height); } else { DisplayMode mode = findBestMatch(width, height); - if(mode == null) return false; + if (mode == null) return false; setDisplayMode(mode); } return false; } - - protected JoglDisplayMode findBestMatch(int width, int height) { + + protected JoglDisplayMode findBestMatch (int width, int height) { DisplayMode[] modes = getDisplayModes(); int maxBitDepth = 0; DisplayMode best = null; - for(DisplayMode mode: modes) { - if(mode.width == width && mode.height == height && mode.bitsPerPixel == desktopMode.bitsPerPixel) { + for (DisplayMode mode : modes) { + if (mode.width == width && mode.height == height && mode.bitsPerPixel == desktopMode.bitsPerPixel) { maxBitDepth = mode.bitsPerPixel; - best = mode; + best = mode; } } return (JoglDisplayMode)best; } - - @Override public boolean setDisplayMode (DisplayMode displayMode) { - if(!supportsDisplayModeChange()) return false; - + + @Override + public boolean setDisplayMode (DisplayMode displayMode) { + if (!supportsDisplayModeChange()) return false; + GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = genv.getDefaultScreenDevice(); final JFrame frame = findJFrame(canvas); - if(frame == null) return false; - + if (frame == null) return false; + // create new canvas, sharing the rendering context with the old canvas // and pause the animator - super.pause(); + super.pause(); GLCanvas newCanvas = new GLCanvas(canvas.getChosenGLCapabilities(), null, canvas.getContext(), device); newCanvas.addGLEventListener(this); - - JFrame newframe = new JFrame(frame.getTitle()); + + JFrame newframe = new JFrame(frame.getTitle()); newframe.setUndecorated(true); newframe.setResizable(false); newframe.add(newCanvas, BorderLayout.CENTER); newframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); newframe.setLocationRelativeTo(null); newframe.pack(); - newframe.setVisible(true); - + newframe.setVisible(true); + device.setFullScreenWindow(newframe); - device.setDisplayMode(((JoglDisplayMode)displayMode).mode); - + device.setDisplayMode(((JoglDisplayMode)displayMode).mode); + initializeGLInstances(canvas); - this.canvas = newCanvas; + this.canvas = newCanvas; ((JoglInput)Gdx.input).setListeners(canvas); - canvas.requestFocus(); + canvas.requestFocus(); newframe.addWindowListener(((JoglApplication)Gdx.app).windowListener); ((JoglApplication)Gdx.app).frame = newframe; resume(); - + Gdx.app.postRunnable(new Runnable() { - public void run() { + public void run () { SwingUtilities.invokeLater(new Runnable() { - @Override public void run () { + @Override + public void run () { frame.dispose(); - } + } }); } - }); - - return true; + }); + + return true; } - - private boolean setWindowedMode(int width, int height) { - + + private boolean setWindowedMode (int width, int height) { + GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = genv.getDefaultScreenDevice(); - if(device.isDisplayChangeSupported()) { + if (device.isDisplayChangeSupported()) { device.setDisplayMode(desktopMode.mode); - device.setFullScreenWindow(null); - + device.setFullScreenWindow(null); + final JFrame frame = findJFrame(canvas); - if(frame == null) return false; - + if (frame == null) return false; + // create new canvas, sharing the rendering context with the old canvas // and pause the animator - super.pause(); + super.pause(); GLCanvas newCanvas = new GLCanvas(canvas.getChosenGLCapabilities(), null, canvas.getContext(), device); newCanvas.setBackground(Color.BLACK); - newCanvas.setPreferredSize(new Dimension(width, height)); + newCanvas.setPreferredSize(new Dimension(width, height)); newCanvas.addGLEventListener(this); - - JFrame newframe = new JFrame(frame.getTitle()); + + JFrame newframe = new JFrame(frame.getTitle()); newframe.setUndecorated(false); newframe.setResizable(true); - newframe.setSize(width + newframe.getInsets().left + newframe.getInsets().right, newframe.getInsets().top + newframe.getInsets().bottom + height); + newframe.setSize(width + newframe.getInsets().left + newframe.getInsets().right, + newframe.getInsets().top + newframe.getInsets().bottom + height); newframe.add(newCanvas, BorderLayout.CENTER); newframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); newframe.setLocationRelativeTo(null); newframe.pack(); - newframe.setVisible(true); - + newframe.setVisible(true); + initializeGLInstances(canvas); - this.canvas = newCanvas; + this.canvas = newCanvas; ((JoglInput)Gdx.input).setListeners(canvas); - canvas.requestFocus(); + canvas.requestFocus(); newframe.addWindowListener(((JoglApplication)Gdx.app).windowListener); ((JoglApplication)Gdx.app).frame = newframe; resume(); - + Gdx.app.postRunnable(new Runnable() { - public void run() { + public void run () { SwingUtilities.invokeLater(new Runnable() { - @Override public void run () { + @Override + public void run () { frame.dispose(); - } + } }); } - }); + }); } else { final JFrame frame = findJFrame(canvas); - if(frame == null) return false; - frame.setSize(width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom + height); + if (frame == null) return false; + frame.setSize(width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom + + height); } - - return true; + + return true; } - - protected static JFrame findJFrame(Component component) { + + protected static JFrame findJFrame (Component component) { Container parent = component.getParent(); - while(parent != null) { - if(parent instanceof JFrame) { + while (parent != null) { + if (parent instanceof JFrame) { return (JFrame)parent; } parent = parent.getParent(); } - + return null; } - @Override public void setVSync (boolean vsync) { - if(vsync) canvas.getGL().setSwapInterval(1); - else canvas.getGL().setSwapInterval(0); + @Override + public void setVSync (boolean vsync) { + if (vsync) + canvas.getGL().setSwapInterval(1); + else + canvas.getGL().setSwapInterval(0); } - @Override public BufferFormat getBufferFormat () { + @Override + public BufferFormat getBufferFormat () { GLCapabilities caps = canvas.getChosenGLCapabilities(); - return new BufferFormat(caps.getRedBits(), caps.getGreenBits(), caps.getBlueBits(), caps.getAlphaBits(), caps.getDepthBits(), caps.getStencilBits(), caps.getNumSamples(), false); + return new BufferFormat(caps.getRedBits(), caps.getGreenBits(), caps.getBlueBits(), caps.getAlphaBits(), + caps.getDepthBits(), caps.getStencilBits(), caps.getNumSamples(), false); } - - @Override public boolean supportsExtension (String extension) { - if(extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); - return extensions.contains(extension); + + @Override + public boolean supportsExtension (String extension) { + if (extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); + return extensions.contains(extension); } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphicsBase.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphicsBase.java index 659e5e2c9f4..9b26ae7d097 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphicsBase.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglGraphicsBase.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import java.awt.Color; @@ -30,10 +31,6 @@ import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.GLU; -import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.Pixmap.Format; -import com.badlogic.gdx.math.MathUtils; -import com.badlogic.gdx.math.WindowedMean; public abstract class JoglGraphicsBase implements Graphics, GLEventListener { static int major, minor; @@ -43,10 +40,10 @@ public abstract class JoglGraphicsBase implements Graphics, GLEventListener { boolean useGL2; long frameStart = System.nanoTime(); long lastFrameTime = System.nanoTime(); - float deltaTime = 0; + float deltaTime = 0; int fps; int frames; - boolean paused = true; + boolean paused = true; GLCommon gl; GL10 gl10; @@ -72,7 +69,7 @@ void initialize (JoglApplicationConfiguration config) { this.useGL2 = config.useGL20; this.glu = new JoglGLU(); Gdx.glu = glu; - + } GLCanvas getCanvas () { @@ -82,7 +79,7 @@ GLCanvas getCanvas () { void create () { frameStart = System.nanoTime(); lastFrameTime = frameStart; - deltaTime = 0; + deltaTime = 0; animator = new JoglAnimator(canvas); animator.start(); } @@ -98,7 +95,7 @@ void resume () { paused = false; frameStart = System.nanoTime(); lastFrameTime = frameStart; - deltaTime = 0; + deltaTime = 0; animator = new JoglAnimator(canvas); animator.setRunAsFastAsPossible(true); animator.start(); @@ -114,7 +111,7 @@ void initializeGLInstances (GLAutoDrawable drawable) { gl20 = new JoglGL20(drawable.getGL()); gl = gl20; } else { - + if (major == 1 && minor < 5 || renderer.equals("Mirage Graphics3")) { gl10 = new JoglGL10(drawable.getGL()); } else { @@ -132,7 +129,7 @@ void initializeGLInstances (GLAutoDrawable drawable) { void updateTimes () { deltaTime = (System.nanoTime() - lastFrameTime) / 1000000000.0f; - lastFrameTime = System.nanoTime(); + lastFrameTime = System.nanoTime(); if (System.nanoTime() - frameStart > 1000000000) { fps = frames; @@ -142,51 +139,63 @@ void updateTimes () { frames++; } - @Override public float getDeltaTime () { + @Override + public float getDeltaTime () { return deltaTime; } - @Override public int getFramesPerSecond () { + @Override + public int getFramesPerSecond () { return fps; } - @Override public int getHeight () { + @Override + public int getHeight () { return canvas.getHeight(); } - @Override public int getWidth () { + @Override + public int getWidth () { return canvas.getWidth(); } - @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 GLCommon getGLCommon () { + @Override + public GLCommon getGLCommon () { return gl; } - @Override public GLU getGLU() { + @Override + public GLU getGLU () { return glu; } - - @Override public boolean isGL11Available () { + + @Override + public boolean isGL11Available () { return gl11 != null; } - @Override public boolean isGL20Available () { + @Override + public boolean isGL20Available () { return gl20 != null; } - @Override public GraphicsType getType () { + @Override + public GraphicsType getType () { return GraphicsType.JoglGL; - } + } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglInput.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglInput.java index aaf4db4a50f..21e79f76caf 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglInput.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglInput.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; -import java.awt.AWTEvent; import java.awt.AWTException; import java.awt.Cursor; import java.awt.GraphicsEnvironment; @@ -24,7 +24,6 @@ import java.awt.Point; import java.awt.Robot; import java.awt.Toolkit; -import java.awt.event.AWTEventListener; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; @@ -96,8 +95,8 @@ protected TouchEvent newObject () { Set pressedButtons = new HashSet(); InputProcessor processor; GLCanvas canvas; - boolean catched = false; - Robot robot = null; + boolean catched = false; + Robot robot = null; public JoglInput (GLCanvas canvas) { setListeners(canvas); @@ -105,73 +104,83 @@ public JoglInput (GLCanvas canvas) { robot = new Robot(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()); } catch (HeadlessException e) { } catch (AWTException e) { - } + } } - - public void setListeners(GLCanvas canvas) { - if(this.canvas != null) { + + public void setListeners (GLCanvas canvas) { + if (this.canvas != null) { canvas.removeMouseListener(this); canvas.removeMouseMotionListener(this); canvas.removeMouseWheelListener(this); canvas.removeKeyListener(this); JFrame frame = JoglGraphics.findJFrame(canvas); - + } canvas.addMouseListener(this); canvas.addMouseMotionListener(this); canvas.addMouseWheelListener(this); - canvas.addKeyListener(this); + canvas.addKeyListener(this); this.canvas = canvas; } - @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) { + @Override + public void getTextInput (final TextInputListener listener, final String title, final String text) { SwingUtilities.invokeLater(new Runnable() { - @Override public void run () { + @Override + public void run () { String output = JOptionPane.showInputDialog(null, title, text); - if (output != null) + if (output != null) listener.input(output); else listener.canceled(); - + } }); } - @Override public int getX () { + @Override + public int getX () { return touchX; } - @Override public int getX (int pointer) { + @Override + public int getX (int pointer) { if (pointer == 0) return touchX; else return 0; } - @Override public int getY () { + @Override + public int getY () { return touchY; } - @Override public int getY (int pointer) { + @Override + public int getY (int pointer) { if (pointer == 0) return touchY; else return 0; } - @Override public boolean isKeyPressed (int key) { + @Override + public boolean isKeyPressed (int key) { synchronized (this) { if (key == Input.Keys.ANY_KEY) return keys.size() > 0; @@ -180,21 +189,23 @@ public void setListeners(GLCanvas canvas) { } } - @Override public boolean isTouched () { + @Override + public boolean isTouched () { return touchDown; } - @Override public boolean isTouched (int pointer) { + @Override + public boolean isTouched (int pointer) { if (pointer == 0) return touchDown; else return false; } - void processEvents () { + void processEvents () { synchronized (this) { justTouched = false; - + if (processor != null) { InputProcessor processor = this.processor; @@ -219,11 +230,11 @@ void processEvents () { TouchEvent e = touchEvents.get(i); switch (e.type) { case TouchEvent.TOUCH_DOWN: - processor.touchDown(e.x, e.y, e.pointer, e.button); - justTouched = true; + processor.touchDown(e.x, e.y, e.pointer, e.button); + justTouched = true; break; case TouchEvent.TOUCH_UP: - processor.touchUp(e.x, e.y, e.pointer, e.button); + processor.touchUp(e.x, e.y, e.pointer, e.button); break; case TouchEvent.TOUCH_DRAGGED: processor.touchDragged(e.x, e.y, e.pointer); @@ -241,8 +252,7 @@ void processEvents () { int len = touchEvents.size(); for (int i = 0; i < len; i++) { TouchEvent event = touchEvents.get(i); - if(event.type == TouchEvent.TOUCH_DOWN) - justTouched = true; + if (event.type == TouchEvent.TOUCH_DOWN) justTouched = true; usedTouchEvents.free(event); } @@ -252,25 +262,28 @@ void processEvents () { } } - if(touchEvents.size() == 0) { + if (touchEvents.size() == 0) { deltaX = 0; deltaY = 0; } - + keyEvents.clear(); touchEvents.clear(); - } + } } - @Override public void setCatchBackKey (boolean catchBack) { + @Override + public void setCatchBackKey (boolean catchBack) { } - @Override public void setOnscreenKeyboardVisible (boolean visible) { + @Override + public void setOnscreenKeyboardVisible (boolean visible) { } - @Override public void mouseDragged (MouseEvent e) { + @Override + public void mouseDragged (MouseEvent e) { synchronized (this) { TouchEvent event = usedTouchEvents.obtain(); event.pointer = 0; @@ -287,9 +300,10 @@ void processEvents () { } } - @Override public void mouseMoved (MouseEvent e) { + @Override + public void mouseMoved (MouseEvent e) { synchronized (this) { - TouchEvent event = usedTouchEvents.obtain(); + TouchEvent event = usedTouchEvents.obtain(); event.pointer = 0; event.x = e.getX(); event.y = e.getY(); @@ -299,47 +313,48 @@ void processEvents () { deltaX = event.x - touchX; deltaY = event.y - touchY; touchX = event.x; - touchY = event.y; + touchY = event.y; checkCatched(e); } } - @Override public void mouseClicked (MouseEvent arg0) { + @Override + public void mouseClicked (MouseEvent arg0) { } - @Override public void mouseEntered (MouseEvent e) { + @Override + public void mouseEntered (MouseEvent e) { touchX = e.getX(); - touchY = e.getY(); + touchY = e.getY(); checkCatched(e); } - @Override public void mouseExited (MouseEvent e) { + @Override + public void mouseExited (MouseEvent e) { checkCatched(e); } - - private void checkCatched(MouseEvent e) { - if(catched && robot != null && canvas.isShowing()) { + + private void checkCatched (MouseEvent e) { + if (catched && robot != null && canvas.isShowing()) { int x = Math.max(0, Math.min(e.getX(), canvas.getWidth()) - 1) + canvas.getLocationOnScreen().x; int y = Math.max(0, Math.min(e.getY(), canvas.getHeight()) - 1) + canvas.getLocationOnScreen().y; deltaX = e.getLocationOnScreen().x - x; deltaY = e.getLocationOnScreen().y - y; - if(e.getX() < 0 || e.getX() >= canvas.getWidth() || e.getY() < 0 || e.getY() >= canvas.getHeight()) { + if (e.getX() < 0 || e.getX() >= canvas.getWidth() || e.getY() < 0 || e.getY() >= canvas.getHeight()) { robot.mouseMove(x - deltaX, y - deltaY); - } + } } } - private int toGdxButton(int swingButton) { - if(swingButton == MouseEvent.BUTTON1) - return Buttons.LEFT; - if(swingButton == MouseEvent.BUTTON2) - return Buttons.MIDDLE; - if(swingButton == MouseEvent.BUTTON3) - return Buttons.RIGHT; + private int toGdxButton (int swingButton) { + if (swingButton == MouseEvent.BUTTON1) return Buttons.LEFT; + if (swingButton == MouseEvent.BUTTON2) return Buttons.MIDDLE; + if (swingButton == MouseEvent.BUTTON3) return Buttons.RIGHT; return Buttons.LEFT; } - - @Override public void mousePressed (MouseEvent e) { + + @Override + public void mousePressed (MouseEvent e) { synchronized (this) { TouchEvent event = usedTouchEvents.obtain(); event.pointer = 0; @@ -352,13 +367,14 @@ private int toGdxButton(int swingButton) { deltaX = event.x - touchX; deltaY = event.y - touchY; touchX = event.x; - touchY = event.y; + touchY = event.y; touchDown = true; - pressedButtons.add(event.button); + pressedButtons.add(event.button); } } - @Override public void mouseReleased (MouseEvent e) { + @Override + public void mouseReleased (MouseEvent e) { synchronized (this) { TouchEvent event = usedTouchEvents.obtain(); event.pointer = 0; @@ -366,29 +382,30 @@ private int toGdxButton(int swingButton) { event.y = e.getY(); event.button = toGdxButton(e.getButton()); event.type = TouchEvent.TOUCH_UP; - touchEvents.add(event); + touchEvents.add(event); deltaX = event.x - touchX; deltaY = event.y - touchY; touchX = event.x; - touchY = event.y; + touchY = event.y; pressedButtons.remove(event.button); - if(pressedButtons.size()==0) - touchDown = false; + if (pressedButtons.size() == 0) touchDown = false; } } - - @Override public void mouseWheelMoved (MouseWheelEvent e) { + + @Override + public void mouseWheelMoved (MouseWheelEvent e) { synchronized (this) { TouchEvent event = usedTouchEvents.obtain(); - event.pointer = 0; + event.pointer = 0; event.type = TouchEvent.TOUCH_SCROLLED; event.scrollAmount = e.getWheelRotation(); - touchEvents.add(event); + touchEvents.add(event); } } - @Override public void keyPressed (java.awt.event.KeyEvent e) { + @Override + public void keyPressed (java.awt.event.KeyEvent e) { synchronized (this) { KeyEvent event = usedKeyEvents.obtain(); event.keyChar = 0; @@ -399,18 +416,20 @@ private int toGdxButton(int swingButton) { } } - @Override public void keyReleased (java.awt.event.KeyEvent e) { + @Override + public void keyReleased (java.awt.event.KeyEvent e) { synchronized (this) { KeyEvent event = usedKeyEvents.obtain(); event.keyChar = 0; event.keyCode = translateKeyCode(e.getKeyCode()); event.type = KeyEvent.KEY_UP; keyEvents.add(event); - keys.remove(event.keyCode); + keys.remove(event.keyCode); } } - @Override public void keyTyped (java.awt.event.KeyEvent e) { + @Override + public void keyTyped (java.awt.event.KeyEvent e) { synchronized (this) { KeyEvent event = usedKeyEvents.obtain(); event.keyChar = e.getKeyChar(); @@ -422,7 +441,7 @@ private int toGdxButton(int swingButton) { protected static int translateKeyCode (int keyCode) { if (keyCode == java.awt.event.KeyEvent.VK_ADD) return Input.Keys.PLUS; - if (keyCode == java.awt.event.KeyEvent.VK_SUBTRACT) return Input.Keys.MINUS; + if (keyCode == java.awt.event.KeyEvent.VK_SUBTRACT) return Input.Keys.MINUS; if (keyCode == java.awt.event.KeyEvent.VK_0) return Input.Keys.NUM_0; if (keyCode == java.awt.event.KeyEvent.VK_1) return Input.Keys.NUM_1; if (keyCode == java.awt.event.KeyEvent.VK_2) return Input.Keys.NUM_2; @@ -489,79 +508,93 @@ protected static int translateKeyCode (int keyCode) { if (keyCode == java.awt.event.KeyEvent.VK_F1) return Input.Keys.F1; if (keyCode == java.awt.event.KeyEvent.VK_F2) return Input.Keys.F2; if (keyCode == java.awt.event.KeyEvent.VK_F3) return Input.Keys.F3; - if (keyCode == java.awt.event.KeyEvent.VK_F4) return Input.Keys.F4; + if (keyCode == java.awt.event.KeyEvent.VK_F4) return Input.Keys.F4; if (keyCode == java.awt.event.KeyEvent.VK_F5) return Input.Keys.F5; if (keyCode == java.awt.event.KeyEvent.VK_F6) return Input.Keys.F6; if (keyCode == java.awt.event.KeyEvent.VK_F7) return Input.Keys.F7; if (keyCode == java.awt.event.KeyEvent.VK_F8) return Input.Keys.F8; - if (keyCode == java.awt.event.KeyEvent.VK_F9) return Input.Keys.F9; + if (keyCode == java.awt.event.KeyEvent.VK_F9) return Input.Keys.F9; if (keyCode == java.awt.event.KeyEvent.VK_F10) return Input.Keys.F10; if (keyCode == java.awt.event.KeyEvent.VK_F11) return Input.Keys.F11; if (keyCode == java.awt.event.KeyEvent.VK_F12) return Input.Keys.F12; - if (keyCode == java.awt.event.KeyEvent.VK_COLON) return Input.Keys.COLON; + if (keyCode == java.awt.event.KeyEvent.VK_COLON) return Input.Keys.COLON; return Input.Keys.UNKNOWN; } - @Override public void setInputProcessor (InputProcessor processor) { + @Override + public void setInputProcessor (InputProcessor processor) { synchronized (this) { this.processor = processor; } } - - @Override public InputProcessor getInputProcessor() { + + @Override + public InputProcessor getInputProcessor () { return this.processor; } - @Override public void vibrate (int milliseconds) { + @Override + public void vibrate (int milliseconds) { } - @Override public boolean justTouched () { + @Override + public boolean justTouched () { return justTouched; } - @Override public boolean isButtonPressed (int button) { + @Override + public boolean isButtonPressed (int button) { return pressedButtons.contains(button); } - @Override public void vibrate (long[] pattern, int repeat) { + @Override + public void vibrate (long[] pattern, int repeat) { } - @Override public void cancelVibrate () { + @Override + public void cancelVibrate () { } - @Override public float getAzimuth () { + @Override + public float getAzimuth () { return 0; } - @Override public float getPitch () { + @Override + public float getPitch () { return 0; } - @Override public float getRoll () { + @Override + public float getRoll () { return 0; } - - @Override public boolean isPeripheralAvailable (Peripheral peripheral) { - if(peripheral == Peripheral.HardwareKeyboard) return true; + + @Override + public boolean isPeripheralAvailable (Peripheral peripheral) { + if (peripheral == Peripheral.HardwareKeyboard) return true; return false; } - @Override public int getRotation () { + @Override + public int getRotation () { return 0; } - @Override public Orientation getNativeOrientation () { + @Override + public Orientation getNativeOrientation () { return Orientation.Landscape; } - @Override public void setCursorCatched (boolean catched) { + @Override + public void setCursorCatched (boolean catched) { this.catched = catched; showCursor(!catched); } - - private void showCursor(boolean visible) { - if(!visible) { + + private void showCursor (boolean visible) { + if (!visible) { Toolkit t = Toolkit.getDefaultToolkit(); Image i = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Cursor noCursor = t.createCustomCursor(i, new Point(0, 0), "none"); @@ -573,37 +606,43 @@ private void showCursor(boolean visible) { } } - @Override public boolean isCursorCatched () { + @Override + public boolean isCursorCatched () { return catched; } - @Override public int getDeltaX () { + @Override + public int getDeltaX () { return deltaX; } - @Override public int getDeltaX (int pointer) { - if(pointer == 0) return deltaX; + @Override + public int getDeltaX (int pointer) { + if (pointer == 0) return deltaX; return 0; } - @Override public int getDeltaY () { + @Override + public int getDeltaY () { return deltaY; } - @Override public int getDeltaY (int pointer) { - if(pointer == 0) return deltaY; + @Override + public int getDeltaY (int pointer) { + if (pointer == 0) return deltaY; return 0; } - @Override public void setCursorPosition (int x, int y) { - if(robot != null) { + @Override + public void setCursorPosition (int x, int y) { + if (robot != null) { robot.mouseMove(canvas.getLocationOnScreen().x + x, canvas.getLocationOnScreen().y + y); } } @Override - public void setCatchMenuKey(boolean catchMenu) { + public void setCatchMenuKey (boolean catchMenu) { // TODO Auto-generated method stub - + } } diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglNativesLoader.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglNativesLoader.java index 70b1433c934..749962f3995 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglNativesLoader.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglNativesLoader.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import com.badlogic.gdx.utils.GdxNativesLoader; @@ -23,12 +24,10 @@ public class JoglNativesLoader { static private boolean nativesLoaded = false; - /** - * loads the necessary libraries depending on the operating system - */ + /** loads the necessary libraries depending on the operating system */ public static void load () { GdxNativesLoader.load(); - if(GdxNativesLoader.disableNativesLoading) return; + if (GdxNativesLoader.disableNativesLoading) return; if (nativesLoaded) return; diff --git a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglPreferences.java b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglPreferences.java index 9e602649126..3480dc683a1 100644 --- a/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglPreferences.java +++ b/backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglPreferences.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.jogl; import java.io.BufferedInputStream; @@ -31,133 +32,151 @@ public class JoglPreferences implements Preferences { private final String name; private final Properties properties = new Properties(); - JoglPreferences(String name) { + JoglPreferences (String name) { this.name = name; InputStream in = null; try { in = new BufferedInputStream(Gdx.files.external(name).read()); properties.loadFromXML(in); - } catch(Throwable t) { + } catch (Throwable t) { } finally { - if(in != null) try { in.close(); } catch(Exception e) { } + if (in != null) try { + in.close(); + } catch (Exception e) { + } } - + Runtime.getRuntime().addShutdownHook(new Thread() { - @Override public void run() { + @Override + public void run () { flush(); } }); - } - - @Override public void putBoolean (String key, boolean val) { + } + + @Override + public void putBoolean (String key, boolean val) { properties.put(key, Boolean.toString(val)); } - @Override public void putInteger (String key, int val) { + @Override + public void putInteger (String key, int val) { properties.put(key, Integer.toString(val)); } - @Override public void putLong (String key, long val) { + @Override + public void putLong (String key, long val) { properties.put(key, Long.toString(val)); } - @Override public void putFloat (String key, float val) { + @Override + public void putFloat (String key, float val) { properties.put(key, Float.toString(val)); } - @Override public void putString (String key, String val) { + @Override + public void putString (String key, String val) { properties.put(key, val); } - @Override public void put (Map vals) { - for(Entry val: vals.entrySet()) { - if(val.getValue() instanceof Boolean) - putBoolean(val.getKey(), (Boolean)val.getValue()); - if(val.getValue() instanceof Integer) - putInteger(val.getKey(), (Integer)val.getValue()); - if(val.getValue() instanceof Long) - putLong(val.getKey(), (Long)val.getValue()); - if(val.getValue() instanceof String) - putString(val.getKey(), (String)val.getValue()); - if(val.getValue() instanceof Float) - putFloat(val.getKey(), (Float)val.getValue()); + @Override + public void put (Map vals) { + for (Entry val : vals.entrySet()) { + if (val.getValue() instanceof Boolean) putBoolean(val.getKey(), (Boolean)val.getValue()); + if (val.getValue() instanceof Integer) putInteger(val.getKey(), (Integer)val.getValue()); + if (val.getValue() instanceof Long) putLong(val.getKey(), (Long)val.getValue()); + if (val.getValue() instanceof String) putString(val.getKey(), (String)val.getValue()); + if (val.getValue() instanceof Float) putFloat(val.getKey(), (Float)val.getValue()); } } - @Override public boolean getBoolean (String key) { + @Override + public boolean getBoolean (String key) { return getBoolean(key, false); } - @Override public int getInteger (String key) { + @Override + public int getInteger (String key) { return getInteger(key, 0); } - @Override public long getLong (String key) { + @Override + public long getLong (String key) { return getLong(key, 0); } - @Override public float getFloat (String key) { + @Override + public float getFloat (String key) { return getFloat(key, 0); } - @Override public String getString (String key) { + @Override + public String getString (String key) { return getString(key, ""); } - @Override public boolean getBoolean (String key, boolean defValue) { + @Override + public boolean getBoolean (String key, boolean defValue) { return Boolean.parseBoolean(properties.getProperty(key, Boolean.toString(defValue))); } - @Override public int getInteger (String key, int defValue) { + @Override + public int getInteger (String key, int defValue) { return Integer.parseInt(properties.getProperty(key, Integer.toString(defValue))); } - @Override public long getLong (String key, long defValue) { + @Override + public long getLong (String key, long defValue) { return Long.parseLong(properties.getProperty(key, Long.toString(defValue))); } - @Override public float getFloat (String key, float defValue) { + @Override + public float getFloat (String key, float defValue) { return Float.parseFloat(properties.getProperty(key, Float.toString(defValue))); } - @Override public String getString (String key, String defValue) { + @Override + public String getString (String key, String defValue) { return properties.getProperty(key, defValue); } - @Override public Map get () { + @Override + public Map get () { Map map = new HashMap(); - for(Entry val: properties.entrySet()) { - if(val.getValue() instanceof Boolean) - map.put((String)val.getKey(), (Boolean)Boolean.parseBoolean((String)val.getValue())); - if(val.getValue() instanceof Integer) - map.put((String)val.getKey(), (Integer)Integer.parseInt((String)val.getValue())); - if(val.getValue() instanceof Long) - map.put((String)val.getKey(), (Long)Long.parseLong((String)val.getValue())); - if(val.getValue() instanceof String) - map.put((String)val.getKey(), (String)val.getValue()); - if(val.getValue() instanceof Float) - map.put((String)val.getKey(), (Float)Float.parseFloat((String)val.getValue())); + for (Entry val : properties.entrySet()) { + if (val.getValue() instanceof Boolean) + map.put((String)val.getKey(), (Boolean)Boolean.parseBoolean((String)val.getValue())); + if (val.getValue() instanceof Integer) map.put((String)val.getKey(), (Integer)Integer.parseInt((String)val.getValue())); + if (val.getValue() instanceof Long) map.put((String)val.getKey(), (Long)Long.parseLong((String)val.getValue())); + if (val.getValue() instanceof String) map.put((String)val.getKey(), (String)val.getValue()); + if (val.getValue() instanceof Float) map.put((String)val.getKey(), (Float)Float.parseFloat((String)val.getValue())); } - + return map; } - @Override public boolean contains (String key) { + @Override + public boolean contains (String key) { return properties.containsKey(key); } - @Override public void clear () { + @Override + public void clear () { properties.clear(); } - - @Override public void flush () { + + @Override + public void flush () { OutputStream out = null; try { out = new BufferedOutputStream(Gdx.files.external(JoglPreferences.this.name).write(false)); properties.storeToXML(out, null); - } catch(Throwable t) { + } catch (Throwable t) { } finally { - if(out != null) try { out.close(); } catch(Exception e) { } + if (out != null) try { + out.close(); + } catch (Exception e) { + } } } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplet.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplet.java index 295cd316018..e842e3396a4 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplet.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplet.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.applet.Applet; @@ -21,10 +22,8 @@ import com.badlogic.gdx.ApplicationListener; -/** - * An OpenGL surface in an applet. - * @author Nathan Sweet - */ +/** An OpenGL surface in an applet. + * @author Nathan Sweet */ public class LwjglApplet extends Applet { final Canvas canvas; LwjglApplication app; @@ -32,14 +31,15 @@ public class LwjglApplet extends Applet { class LwjglAppletApplication extends LwjglApplication { public LwjglAppletApplication (ApplicationListener listener, boolean useGL2, Canvas canvas) { - super(listener, useGL2, canvas); + super(listener, useGL2, canvas); } - - @Override public ApplicationType getType() { + + @Override + public ApplicationType getType () { return ApplicationType.Applet; } } - + public LwjglApplet (final ApplicationListener listener, final boolean useGL2) { LwjglNativesLoader.load = false; canvas = new Canvas() { diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplication.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplication.java index 30f6cc104ca..811794fe7b6 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplication.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplication.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.awt.Canvas; @@ -23,7 +24,6 @@ import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; -import org.lwjgl.opengl.GL11; import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationListener; @@ -34,12 +34,9 @@ import com.badlogic.gdx.Input; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.backends.openal.OpenALAudio; -import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * An OpenGL surface fullscreen or in a lightweight window. - */ +/** An OpenGL surface fullscreen or in a lightweight window. */ public class LwjglApplication implements Application { LwjglGraphics graphics; OpenALAudio audio; @@ -73,23 +70,23 @@ public LwjglApplication (ApplicationListener listener, String title, int width, Gdx.input = input; initialize(); } - + public LwjglApplication (ApplicationListener listener, LwjglApplicationConfiguration config) { LwjglNativesLoader.load(); - + graphics = new LwjglGraphics(config); audio = new OpenALAudio(); files = new LwjglFiles(); input = new LwjglInput(); - this.listener = listener; - + this.listener = listener; + Gdx.app = this; Gdx.graphics = graphics; Gdx.audio = audio; Gdx.files = files; Gdx.input = input; initialize(); - + } public LwjglApplication (ApplicationListener listener, boolean useGL2, Canvas canvas) { @@ -111,7 +108,8 @@ public LwjglApplication (ApplicationListener listener, boolean useGL2, Canvas ca private void initialize () { mainLoopThread = new Thread("LWJGL Application") { - @SuppressWarnings("synthetic-access") public void run () { + @SuppressWarnings("synthetic-access") + public void run () { graphics.setVSync(graphics.config.vSyncEnabled); LwjglApplication.this.mainLoop(); } @@ -131,21 +129,21 @@ private void mainLoop () { graphics.resize = false; int lastWidth = graphics.getWidth(); - int lastHeight = graphics.getHeight(); - + int lastHeight = graphics.getHeight(); + graphics.lastTime = System.nanoTime(); while (running) { - if(Display.isCloseRequested()) { + if (Display.isCloseRequested()) { exit(); } - + graphics.updateTime(); - if(graphics.resize) { + if (graphics.resize) { graphics.resize = false; listener.resize(graphics.getWidth(), graphics.getHeight()); } - synchronized(runnables) { - for(int i = 0; i < runnables.size(); i++) { + synchronized (runnables) { + for (int i = 0; i < runnables.size(); i++) { runnables.get(i).run(); } runnables.clear(); @@ -166,7 +164,7 @@ private void mainLoop () { listener.render(); audio.update(); Display.update(); - if (graphics.vsync && graphics.config.useCPUSynch) { + if (graphics.vsync && graphics.config.useCPUSynch) { Display.sync(60); } } @@ -175,30 +173,36 @@ private void mainLoop () { listener.dispose(); Display.destroy(); audio.dispose(); - if(graphics.config.forceExit) System.exit(-1); + if (graphics.config.forceExit) System.exit(-1); } - @Override public Audio getAudio () { + @Override + public Audio getAudio () { return audio; } - @Override public Files getFiles () { + @Override + public Files getFiles () { return files; } - @Override public Graphics getGraphics () { + @Override + public Graphics getGraphics () { return graphics; } - @Override public Input getInput () { + @Override + public Input getInput () { return input; } - @Override public ApplicationType getType () { + @Override + public ApplicationType getType () { return ApplicationType.Desktop; } - @Override public int getVersion () { + @Override + public int getVersion () { return 0; } @@ -210,17 +214,21 @@ public void stop () { } } - @Override public long getJavaHeap () { + @Override + public long getJavaHeap () { return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } - @Override public long getNativeHeap () { + @Override + public long getNativeHeap () { return getJavaHeap(); } Map preferences = new HashMap(); - @Override public Preferences getPreferences (String name) { - if(preferences.containsKey(name)) { + + @Override + public Preferences getPreferences (String name) { + if (preferences.containsKey(name)) { return preferences.get(name); } else { Preferences prefs = new LwjglPreferences(name); @@ -229,49 +237,54 @@ public void stop () { } } - @Override public void postRunnable (Runnable runnable) { + @Override + public void postRunnable (Runnable runnable) { synchronized (runnables) { runnables.add(runnable); } } - - public void log(String tag, String message) { - if(logLevel >= LOG_INFO) { - System.out.println(tag + ":" + message); + + public void log (String tag, String message) { + if (logLevel >= LOG_INFO) { + System.out.println(tag + ":" + message); } - } + } - @Override public void log (String tag, String message, Exception exception) { - if(logLevel >= LOG_INFO) { + @Override + public void log (String tag, String message, Exception exception) { + if (logLevel >= LOG_INFO) { System.out.println(tag + ":" + message); exception.printStackTrace(System.out); } } - - @Override public void error (String tag, String message) { - if(logLevel >= LOG_ERROR) { - System.err.println(tag + ":" + message); + + @Override + public void error (String tag, String message) { + if (logLevel >= LOG_ERROR) { + System.err.println(tag + ":" + message); } } - - @Override public void error (String tag, String message, Exception exception) { - if(logLevel >= LOG_ERROR) { + @Override + public void error (String tag, String message, Exception exception) { + if (logLevel >= LOG_ERROR) { System.err.println(tag + ":" + message); exception.printStackTrace(System.err); } } - - @Override public void setLogLevel (int logLevel) { + @Override + public void setLogLevel (int logLevel) { this.logLevel = logLevel; } - - @Override public void exit () { + + @Override + public void exit () { postRunnable(new Runnable() { - @Override public void run () { + @Override + public void run () { running = false; - } + } }); } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplicationConfiguration.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplicationConfiguration.java index cd18487af3e..f47e3073acc 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplicationConfiguration.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglApplicationConfiguration.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.lwjgl; import java.awt.GraphicsDevice; @@ -9,7 +10,7 @@ public class LwjglApplicationConfiguration { /** whether to use OpenGL ES 2.0 or not. default: false **/ - public boolean useGL20 = false; + public boolean useGL20 = false; /** number of bits per color channel **/ public int r = 8, g = 8, b = 8, a = 8; /** number of bits for depth and stencil buffer **/ @@ -27,29 +28,26 @@ public class LwjglApplicationConfiguration { /** title of application **/ public String title = "Lwjgl Application"; /** whether to call System.exit() on tear-down. Needed for Webstarts on some versions of Mac OS X it seems **/ - public boolean forceExit = true; - - /** - * Sets the r, g, b and a bits per channel based on the given - * {@link DisplayMode} and sets the fullscreen flag to true. - * @param mode - */ - public void setFromDisplayMode(DisplayMode mode) { + public boolean forceExit = true; + + /** Sets the r, g, b and a bits per channel based on the given {@link DisplayMode} and sets the fullscreen flag to true. + * @param mode */ + public void setFromDisplayMode (DisplayMode mode) { this.width = mode.width; this.height = mode.height; - if(mode.bitsPerPixel == 16) { + if (mode.bitsPerPixel == 16) { this.r = 5; this.g = 6; this.b = 5; this.a = 0; } - if(mode.bitsPerPixel == 24) { + if (mode.bitsPerPixel == 24) { this.r = 8; this.g = 8; this.b = 8; this.a = 0; } - if(mode.bitsPerPixel == 32) { + if (mode.bitsPerPixel == 32) { this.r = 8; this.g = 8; this.b = 8; @@ -57,42 +55,43 @@ public void setFromDisplayMode(DisplayMode mode) { } this.fullscreen = true; } - + protected static class LwjglApplicationConfigurationDisplayMode extends DisplayMode { protected LwjglApplicationConfigurationDisplayMode (int width, int height, int refreshRate, int bitsPerPixel) { super(width, height, refreshRate, bitsPerPixel); - } + } } - + public static DisplayMode getDesktopDisplayMode () { GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = genv.getDefaultScreenDevice(); java.awt.DisplayMode mode = device.getDisplayMode(); - return new LwjglApplicationConfigurationDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth()); + return new LwjglApplicationConfigurationDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), + mode.getBitDepth()); } - - public static DisplayMode[] getDisplayModes() { + + public static DisplayMode[] getDisplayModes () { GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = genv.getDefaultScreenDevice(); java.awt.DisplayMode desktopMode = device.getDisplayMode(); java.awt.DisplayMode[] displayModes = device.getDisplayModes(); ArrayList modes = new ArrayList(); int idx = 0; - for(java.awt.DisplayMode mode: displayModes) { + for (java.awt.DisplayMode mode : displayModes) { boolean duplicate = false; - for(int i = 0; i < modes.size(); i++) { - if(modes.get(i).width == mode.getWidth() && - modes.get(i).height == mode.getHeight() && - modes.get(i).bitsPerPixel == mode.getBitDepth()) { + for (int i = 0; i < modes.size(); i++) { + if (modes.get(i).width == mode.getWidth() && modes.get(i).height == mode.getHeight() + && modes.get(i).bitsPerPixel == mode.getBitDepth()) { duplicate = true; break; } } - if(duplicate) continue; - if(mode.getBitDepth() != desktopMode.getBitDepth()) continue; - modes.add(new LwjglApplicationConfigurationDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode.getBitDepth())); + if (duplicate) continue; + if (mode.getBitDepth() != desktopMode.getBitDepth()) continue; + modes.add(new LwjglApplicationConfigurationDisplayMode(mode.getWidth(), mode.getHeight(), mode.getRefreshRate(), mode + .getBitDepth())); } - + return modes.toArray(new DisplayMode[modes.size()]); } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglCanvas.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglCanvas.java index 78a0c6aee98..9ecb3098bab 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglCanvas.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglCanvas.java @@ -25,7 +25,6 @@ import java.util.Map; import org.lwjgl.LWJGLException; -import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import com.badlogic.gdx.Application; diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFileHandle.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFileHandle.java index e304adc4a21..1fced99486e 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFileHandle.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFileHandle.java @@ -21,10 +21,8 @@ import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.files.FileHandle; -/** - * @author mzechner - * @author Nathan Sweet - */ +/** @author mzechner + * @author Nathan Sweet */ public final class LwjglFileHandle extends FileHandle { public LwjglFileHandle (String fileName, FileType type) { super(fileName, type); diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFiles.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFiles.java index bf9e439454b..1efd17cf47c 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFiles.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFiles.java @@ -13,43 +13,49 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import com.badlogic.gdx.Files; import com.badlogic.gdx.files.FileHandle; -/** - * @author mzechner - * @author Nathan Sweet - */ +/** @author mzechner + * @author Nathan Sweet */ public final class LwjglFiles implements Files { private final String externalPath = System.getProperty("user.home") + "/"; - @Override public FileHandle getFileHandle (String fileName, FileType type) { + @Override + public FileHandle getFileHandle (String fileName, FileType type) { return new LwjglFileHandle(fileName, type); } - @Override public FileHandle classpath (String path) { + @Override + public FileHandle classpath (String path) { return new LwjglFileHandle(path, FileType.Classpath); } - @Override public FileHandle internal (String path) { + @Override + public FileHandle internal (String path) { return new LwjglFileHandle(path, FileType.Internal); } - @Override public FileHandle external (String path) { + @Override + public FileHandle external (String path) { return new LwjglFileHandle(path, FileType.External); } - @Override public FileHandle absolute (String path) { + @Override + public FileHandle absolute (String path) { return new LwjglFileHandle(path, FileType.Absolute); } - @Override public String getExternalStoragePath () { + @Override + public String getExternalStoragePath () { return externalPath; } - @Override public boolean isExternalStorageAvailable () { + @Override + public boolean isExternalStorageAvailable () { return true; } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFrame.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFrame.java index bbe7c86e01f..633ad4a65ed 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFrame.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglFrame.java @@ -7,7 +7,6 @@ import javax.swing.JFrame; import com.badlogic.gdx.ApplicationListener; -import com.badlogic.gdx.Gdx; /** Wraps an {@link LwjglCanvas} in a resizable {@link JFrame}. */ public class LwjglFrame extends JFrame { diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL10.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL10.java index f133edb07da..d85aa209590 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL10.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL10.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.nio.Buffer; @@ -30,12 +31,9 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex arrays are emulated. - * - * @author mzechner +/** An implementation of the {@link GL10} interface based on Jogl. Fixed point vertex arrays are emulated. * - */ + * @author mzechner */ class LwjglGL10 implements GL10 { private IntBuffer tempInt; private FloatBuffer tempFloat; @@ -493,12 +491,13 @@ public final void glGenTextures (int n, int[] textures, int offset) { textures[i] = GL11.glGenTextures(); } - IntBuffer getBuffer = BufferUtils.createIntBuffer(100); - public final void glGetIntegerv (int pname, int[] params, int offset) { + IntBuffer getBuffer = BufferUtils.createIntBuffer(100); + + public final void glGetIntegerv (int pname, int[] params, int offset) { GL11.glGetInteger(pname, getBuffer); - // FIXME Yeah, so. This sucks as well :D LWJGL does not set pos/lim. - for(int i = offset, j = 0; i < params.length; i++, j++) { - if(j == getBuffer.capacity()) return; + // FIXME Yeah, so. This sucks as well :D LWJGL does not set pos/lim. + for (int i = offset, j = 0; i < params.length; i++, j++) { + if (j == getBuffer.capacity()) return; params[i] = getBuffer.get(j); } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL11.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL11.java index 4cb20b4e969..cd6b62a0b8d 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL11.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL11.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.nio.Buffer; @@ -28,13 +29,10 @@ import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL15; -/** - * An implementation of the {@link GL11} interface based on Jogl. Fixed point vertex arrays are emulated. Some glGetXXX methods +/** An implementation of the {@link GL11} interface based on Jogl. Fixed point vertex arrays are emulated. Some glGetXXX methods * are not implemented. * - * @author mzechner - * - */ + * @author mzechner */ final class LwjglGL11 extends LwjglGL10 implements com.badlogic.gdx.graphics.GL11 { private IntBuffer tempInt; private FloatBuffer tempFloat; diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java index 217c8d80c1b..c9fb9b8ba00 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.nio.Buffer; @@ -34,13 +35,10 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * An implementation of the {@link GL20} interface based on Jogl. Note that Jogl shaders and OpenGL ES shaders will not be 100% +/** 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 - * - */ + * @author mzechner */ final class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { public void glActiveTexture (int texture) { GL13.glActiveTexture(texture); @@ -287,18 +285,18 @@ public void glGenerateMipmap (int target) { } public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) { - // FIXME this is less than ideal of course... - IntBuffer typeTmp = BufferUtils.createIntBuffer(2); + // FIXME this is less than ideal of course... + IntBuffer typeTmp = BufferUtils.createIntBuffer(2); String name = GL20.glGetActiveAttrib(program, index, 256, typeTmp); - if(type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp.get(0)); + if (type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp.get(0)); return name; } public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) { - // FIXME this is less than ideal of course... - IntBuffer typeTmp = BufferUtils.createIntBuffer(2); + // FIXME this is less than ideal of course... + IntBuffer typeTmp = BufferUtils.createIntBuffer(2); String name = GL20.glGetActiveUniform(program, index, 256, typeTmp); - if(type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp.get(0)); + if (type instanceof IntBuffer) ((IntBuffer)type).put(typeTmp.get(0)); return name; } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGLU.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGLU.java index 31d68e8b6a5..3290184bb8d 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGLU.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGLU.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.nio.FloatBuffer; @@ -24,57 +25,68 @@ import com.badlogic.gdx.graphics.GLU; public class LwjglGLU implements GLU { - + FloatBuffer modelb; FloatBuffer projectb; IntBuffer viewb; FloatBuffer winb; - - public LwjglGLU() { + + public LwjglGLU () { modelb = BufferUtils.createFloatBuffer(16); projectb = BufferUtils.createFloatBuffer(16); viewb = BufferUtils.createIntBuffer(4); winb = BufferUtils.createFloatBuffer(3); } - @Override public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, - float upX, float upY, float upZ) { + @Override + public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, + float upY, float upZ) { org.lwjgl.util.glu.GLU.gluLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } - @Override public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { + @Override + public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { org.lwjgl.util.glu.GLU.gluOrtho2D(left, right, bottom, top); } - @Override public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { + @Override + public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { org.lwjgl.util.glu.GLU.gluPerspective(fovy, aspect, zNear, zFar); } - @Override public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] win, int winOffset) { - modelb.clear(); modelb.put(model, modelOffset, 16); - projectb.clear(); projectb.put(project, projectOffset, 16); - viewb.clear(); viewb.put(view, viewOffset, 4); + modelb.clear(); + modelb.put(model, modelOffset, 16); + projectb.clear(); + projectb.put(project, projectOffset, 16); + viewb.clear(); + viewb.put(view, viewOffset, 4); winb.clear(); - + boolean result = org.lwjgl.util.glu.GLU.gluProject(objX, objY, objZ, modelb, projectb, viewb, winb); win[winOffset] = winb.get(0); - win[winOffset+1] = winb.get(1); - win[winOffset+2] = winb.get(2); + win[winOffset + 1] = winb.get(1); + win[winOffset + 2] = winb.get(2); return result; } - @Override public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] obj, int objOffset) { - modelb.clear(); modelb.put(model, modelOffset, 16); - projectb.clear(); projectb.put(project, projectOffset, 16); - viewb.clear(); viewb.put(view, viewOffset, 4); + modelb.clear(); + modelb.put(model, modelOffset, 16); + projectb.clear(); + projectb.put(project, projectOffset, 16); + viewb.clear(); + viewb.put(view, viewOffset, 4); winb.clear(); - + boolean result = org.lwjgl.util.glu.GLU.gluUnProject(winX, winY, winZ, modelb, projectb, viewb, winb); obj[objOffset] = winb.get(0); - obj[objOffset+1] = winb.get(1); - obj[objOffset+2] = winb.get(2); + obj[objOffset + 1] = winb.get(1); + obj[objOffset + 2] = winb.get(2); return result; } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java index 33c237c3ff5..0f3f8457a41 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java @@ -34,10 +34,8 @@ import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * An implementation of the {@link Graphics} interface based on Lwjgl. - * @author mzechner - */ +/** An implementation of the {@link Graphics} interface based on Lwjgl. + * @author mzechner */ public final class LwjglGraphics implements Graphics { static int major, minor; @@ -45,12 +43,12 @@ public final class LwjglGraphics implements Graphics { GL10 gl10; GL11 gl11; GL20 gl20; - GLU glu; + GLU glu; float deltaTime = 0; long frameStart = 0; int frames = 0; int fps; - long lastTime = System.nanoTime(); + long lastTime = System.nanoTime(); Canvas canvas; boolean vsync = false; boolean resize = false; @@ -58,7 +56,7 @@ public final class LwjglGraphics implements Graphics { BufferFormat bufferFormat = new BufferFormat(8, 8, 8, 8, 16, 8, 0, false); String extensions; - LwjglGraphics (LwjglApplicationConfiguration config) { + LwjglGraphics (LwjglApplicationConfiguration config) { this.config = config; } @@ -120,7 +118,8 @@ public int getFramesPerSecond () { return fps; } - @Override public GLCommon getGLCommon () { + @Override + public GLCommon getGLCommon () { return gl; } @@ -141,43 +140,45 @@ void setupDisplay () throws LWJGLException { if (canvas != null) { Display.setParent(canvas); } else { - if(!setDisplayMode(config.width, config.height, config.fullscreen)) - throw new GdxRuntimeException("Couldn't set display mode " + config.width + "x" + config.height + ", fullscreen: " + config.fullscreen); + if (!setDisplayMode(config.width, config.height, config.fullscreen)) + throw new GdxRuntimeException("Couldn't set display mode " + config.width + "x" + config.height + ", fullscreen: " + + config.fullscreen); } Display.setTitle(config.title); - createDisplayPixelFormat(); + createDisplayPixelFormat(); initiateGLInstances(); } - - private void createDisplayPixelFormat() { + + private void createDisplayPixelFormat () { int samples = 0; try { Display.create(new PixelFormat(config.r + config.g + config.b, config.a, config.depth, config.stencil, config.samples)); - bufferFormat = new BufferFormat(config.r, config.g, config.b, config.a, config.depth, config.stencil, config.samples, false); + bufferFormat = new BufferFormat(config.r, config.g, config.b, config.a, config.depth, config.stencil, config.samples, + false); } catch (Exception ex) { Display.destroy(); try { Display.create(new PixelFormat(0, 16, 8)); - if(getDesktopDisplayMode().bitsPerPixel == 16) { + if (getDesktopDisplayMode().bitsPerPixel == 16) { bufferFormat = new BufferFormat(5, 6, 5, 0, 16, 8, 0, false); } - if(getDesktopDisplayMode().bitsPerPixel == 24) { + if (getDesktopDisplayMode().bitsPerPixel == 24) { bufferFormat = new BufferFormat(8, 8, 8, 0, 16, 8, 0, false); } - if(getDesktopDisplayMode().bitsPerPixel == 32) { + if (getDesktopDisplayMode().bitsPerPixel == 32) { bufferFormat = new BufferFormat(8, 8, 8, 8, 16, 8, 0, false); } } catch (Exception ex2) { Display.destroy(); try { Display.create(new PixelFormat()); - if(getDesktopDisplayMode().bitsPerPixel == 16) { + if (getDesktopDisplayMode().bitsPerPixel == 16) { bufferFormat = new BufferFormat(5, 6, 5, 0, 8, 0, 0, false); } - if(getDesktopDisplayMode().bitsPerPixel == 24) { + if (getDesktopDisplayMode().bitsPerPixel == 24) { bufferFormat = new BufferFormat(8, 8, 8, 0, 8, 0, 0, false); } - if(getDesktopDisplayMode().bitsPerPixel == 32) { + if (getDesktopDisplayMode().bitsPerPixel == 32) { bufferFormat = new BufferFormat(8, 8, 8, 8, 8, 0, 0, false); } } catch (Exception ex3) { @@ -216,42 +217,48 @@ private void initiateGLInstances () { Gdx.gl20 = gl20; } - @Override public float getPpiX () { + @Override + public float getPpiX () { return Toolkit.getDefaultToolkit().getScreenResolution(); } - @Override public float getPpiY () { + @Override + public float getPpiY () { return Toolkit.getDefaultToolkit().getScreenResolution(); } - @Override public float getPpcX () { + @Override + public float getPpcX () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f); } - @Override public float getPpcY () { + @Override + public float getPpcY () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f); } - - @Override public float getDensity () { + + @Override + public float getDensity () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 160f); } - @Override public boolean supportsDisplayModeChange () { + @Override + public boolean supportsDisplayModeChange () { return true; } private class LwjglDisplayMode extends DisplayMode { org.lwjgl.opengl.DisplayMode mode; - public LwjglDisplayMode (int width, int height, int refreshRate, int bitsPerPixel, - org.lwjgl.opengl.DisplayMode mode) { + public LwjglDisplayMode (int width, int height, int refreshRate, int bitsPerPixel, org.lwjgl.opengl.DisplayMode mode) { super(width, height, refreshRate, bitsPerPixel); this.mode = mode; } } - @Override public boolean setDisplayMode (DisplayMode displayMode) { + @Override + public boolean setDisplayMode (DisplayMode displayMode) { org.lwjgl.opengl.DisplayMode mode = ((LwjglDisplayMode)displayMode).mode; try { if (!mode.isFullscreenCapable()) { @@ -259,7 +266,7 @@ public LwjglDisplayMode (int width, int height, int refreshRate, int bitsPerPixe } else { Display.setDisplayModeAndFullscreen(mode); } - if(Gdx.gl != null) Gdx.gl.glViewport(0, 0, displayMode.width, displayMode.height); + if (Gdx.gl != null) Gdx.gl.glViewport(0, 0, displayMode.width, displayMode.height); config.width = displayMode.width; config.height = displayMode.height; resize = true; @@ -269,10 +276,9 @@ public LwjglDisplayMode (int width, int height, int refreshRate, int bitsPerPixe } } - /** - * Kindly stolen from http://lwjgl.org/wiki/index.php?title=LWJGL_Basics_5_(Fullscreen), not perfect but will do. - */ - @Override public boolean setDisplayMode (int width, int height, boolean fullscreen) { + /** Kindly stolen from http://lwjgl.org/wiki/index.php?title=LWJGL_Basics_5_(Fullscreen), not perfect but will do. */ + @Override + public boolean setDisplayMode (int width, int height, boolean fullscreen) { if ((Display.getDisplayMode().getWidth() == width) && (Display.getDisplayMode().getHeight() == height) && (Display.isFullscreen() == fullscreen)) { return true; @@ -310,13 +316,13 @@ public LwjglDisplayMode (int width, int height, int refreshRate, int bitsPerPixe targetDisplayMode = new org.lwjgl.opengl.DisplayMode(width, height); } - if (targetDisplayMode == null) { + if (targetDisplayMode == null) { return false; } Display.setDisplayMode(targetDisplayMode); Display.setFullscreen(fullscreen); - if(Gdx.gl != null) Gdx.gl.glViewport(0, 0, targetDisplayMode.getWidth(), targetDisplayMode.getHeight()); + if (Gdx.gl != null) Gdx.gl.glViewport(0, 0, targetDisplayMode.getWidth(), targetDisplayMode.getHeight()); config.width = targetDisplayMode.getWidth(); config.height = targetDisplayMode.getHeight(); resize = true; @@ -326,15 +332,17 @@ public LwjglDisplayMode (int width, int height, int refreshRate, int bitsPerPixe } } - @Override public DisplayMode[] getDisplayModes () { + @Override + public DisplayMode[] getDisplayModes () { try { org.lwjgl.opengl.DisplayMode[] availableDisplayModes = Display.getAvailableDisplayModes(); DisplayMode[] modes = new DisplayMode[availableDisplayModes.length]; int idx = 0; for (org.lwjgl.opengl.DisplayMode mode : availableDisplayModes) { - if(mode.isFullscreenCapable()) { - modes[idx++] = new LwjglDisplayMode(mode.getWidth(), mode.getHeight(), mode.getFrequency(), mode.getBitsPerPixel(), mode); + if (mode.isFullscreenCapable()) { + modes[idx++] = new LwjglDisplayMode(mode.getWidth(), mode.getHeight(), mode.getFrequency(), + mode.getBitsPerPixel(), mode); } } @@ -343,32 +351,38 @@ public LwjglDisplayMode (int width, int height, int refreshRate, int bitsPerPixe throw new GdxRuntimeException("Couldn't fetch available display modes", e); } } - - @Override public DisplayMode getDesktopDisplayMode() { + + @Override + public DisplayMode getDesktopDisplayMode () { org.lwjgl.opengl.DisplayMode mode = Display.getDesktopDisplayMode(); return new LwjglDisplayMode(mode.getWidth(), mode.getHeight(), mode.getFrequency(), mode.getBitsPerPixel(), mode); } - @Override public void setTitle (String title) { + @Override + public void setTitle (String title) { Display.setTitle(title); } - @Override public void setIcon (Pixmap pixmap) { - Display.setIcon(new ByteBuffer[] { pixmap.getPixels().duplicate() } ); + @Override + public void setIcon (Pixmap pixmap) { + Display.setIcon(new ByteBuffer[] {pixmap.getPixels().duplicate()}); } - @Override public BufferFormat getBufferFormat () { + @Override + public BufferFormat getBufferFormat () { return bufferFormat; } - @Override public void setVSync (boolean vsync) { + @Override + public void setVSync (boolean vsync) { this.vsync = vsync; - if(vsync && !config.useCPUSynch) Display.setVSyncEnabled(true); - if(!vsync && !config.useCPUSynch) Display.setVSyncEnabled(false); + if (vsync && !config.useCPUSynch) Display.setVSyncEnabled(true); + if (!vsync && !config.useCPUSynch) Display.setVSyncEnabled(false); } - - @Override public boolean supportsExtension (String extension) { - if(extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); + + @Override + public boolean supportsExtension (String extension) { + if (extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); return extensions.contains(extension); } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglInput.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglInput.java index 47dec0bef8a..c53b91c7d54 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglInput.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglInput.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.util.ArrayList; @@ -29,16 +30,11 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; -import com.badlogic.gdx.Input.Orientation; -import com.badlogic.gdx.Input.Peripheral; import com.badlogic.gdx.utils.Pool; -/** - * An implementation of the {@link Input} interface hooking a Jogl panel for input. - * - * @author mzechner +/** An implementation of the {@link Input} interface hooking a Jogl panel for input. * - */ + * @author mzechner */ final class LwjglInput implements Input { class KeyEvent { static final int KEY_DOWN = 0; @@ -59,7 +55,7 @@ class TouchEvent { int type; int x; - int y; + int y; int scrollAmount; int button; int pointer; @@ -82,7 +78,7 @@ protected TouchEvent newObject () { boolean mousePressed = false; int mouseX, mouseY; int deltaX, deltaY; - int pressedKeys = 0; + int pressedKeys = 0; boolean justTouched = false; Set pressedButtons = new HashSet(); InputProcessor processor; @@ -110,7 +106,7 @@ public void getTextInput (final TextInputListener listener, final String title, SwingUtilities.invokeLater(new Runnable() { public void run () { String output = JOptionPane.showInputDialog(null, title, text); - if(output != null) + if (output != null) listener.input(output); else listener.canceled(); @@ -167,11 +163,13 @@ public boolean supportsMultitouch () { return false; } - @Override public void setOnscreenKeyboardVisible (boolean visible) { + @Override + public void setOnscreenKeyboardVisible (boolean visible) { } - @Override public void setCatchBackKey (boolean catchBack) { + @Override + public void setCatchBackKey (boolean catchBack) { } @@ -235,84 +233,162 @@ void processEvents () { public static int getGdxKeyCode (int lwjglKeyCode) { switch (lwjglKeyCode) { - case Keyboard.KEY_0: return Input.Keys.NUM_0; - case Keyboard.KEY_1: return Input.Keys.NUM_1; - case Keyboard.KEY_2: return Input.Keys.NUM_2; - case Keyboard.KEY_3: return Input.Keys.NUM_3; - case Keyboard.KEY_4: return Input.Keys.NUM_4; - case Keyboard.KEY_5: return Input.Keys.NUM_5; - case Keyboard.KEY_6: return Input.Keys.NUM_6; - case Keyboard.KEY_7: return Input.Keys.NUM_7; - case Keyboard.KEY_8: return Input.Keys.NUM_8; - case Keyboard.KEY_9: return Input.Keys.NUM_9; - case Keyboard.KEY_A: return Input.Keys.A; - case Keyboard.KEY_B: return Input.Keys.B; - case Keyboard.KEY_C: return Input.Keys.C; - case Keyboard.KEY_D: return Input.Keys.D; - case Keyboard.KEY_E: return Input.Keys.E; - case Keyboard.KEY_F: return Input.Keys.F; - case Keyboard.KEY_G: return Input.Keys.G; - case Keyboard.KEY_H: return Input.Keys.H; - case Keyboard.KEY_I: return Input.Keys.I; - case Keyboard.KEY_J: return Input.Keys.J; - case Keyboard.KEY_K: return Input.Keys.K; - case Keyboard.KEY_L: return Input.Keys.L; - case Keyboard.KEY_M: return Input.Keys.M; - case Keyboard.KEY_N: return Input.Keys.N; - case Keyboard.KEY_O: return Input.Keys.O; - case Keyboard.KEY_P: return Input.Keys.P; - case Keyboard.KEY_Q: return Input.Keys.Q; - case Keyboard.KEY_R: return Input.Keys.R; - case Keyboard.KEY_S: return Input.Keys.S; - case Keyboard.KEY_T: return Input.Keys.T; - case Keyboard.KEY_U: return Input.Keys.U; - case Keyboard.KEY_V: return Input.Keys.V; - case Keyboard.KEY_W: return Input.Keys.W; - case Keyboard.KEY_X: return Input.Keys.X; - case Keyboard.KEY_Y: return Input.Keys.Y; - case Keyboard.KEY_Z: return Input.Keys.Z; - case Keyboard.KEY_LMENU: return Input.Keys.ALT_LEFT; - case Keyboard.KEY_RMENU: return Input.Keys.ALT_RIGHT; - case Keyboard.KEY_BACKSLASH: return Input.Keys.BACKSLASH; - case Keyboard.KEY_COMMA: return Input.Keys.COMMA; - case Keyboard.KEY_DELETE: return Input.Keys.FORWARD_DEL; - case Keyboard.KEY_LEFT: return Input.Keys.DPAD_LEFT; - case Keyboard.KEY_RIGHT: return Input.Keys.DPAD_RIGHT; - case Keyboard.KEY_UP: return Input.Keys.DPAD_UP; - case Keyboard.KEY_DOWN: return Input.Keys.DPAD_DOWN; - case Keyboard.KEY_RETURN: return Input.Keys.ENTER; - case Keyboard.KEY_HOME: return Input.Keys.HOME; - case Keyboard.KEY_MINUS: return Input.Keys.MINUS; - case Keyboard.KEY_PERIOD: return Input.Keys.PERIOD; - case Keyboard.KEY_ADD: return Input.Keys.PLUS; - case Keyboard.KEY_SEMICOLON: return Input.Keys.SEMICOLON; - case Keyboard.KEY_LSHIFT: return Input.Keys.SHIFT_LEFT; - case Keyboard.KEY_RSHIFT: return Input.Keys.SHIFT_RIGHT; - case Keyboard.KEY_SLASH: return Input.Keys.SLASH; - case Keyboard.KEY_SPACE: return Input.Keys.SPACE; - case Keyboard.KEY_TAB: return Input.Keys.TAB; - case Keyboard.KEY_LCONTROL: return Input.Keys.CONTROL_LEFT; - case Keyboard.KEY_RCONTROL: return Input.Keys.CONTROL_RIGHT; - case Keyboard.KEY_ESCAPE: return Input.Keys.ESCAPE; - case Keyboard.KEY_END: return Input.Keys.END; - case Keyboard.KEY_INSERT: return Input.Keys.INSERT; - case Keyboard.KEY_NUMPAD5: return Input.Keys.DPAD_CENTER; - case Keyboard.KEY_BACK: return Input.Keys.DEL; - case Keyboard.KEY_SUBTRACT: return Input.Keys.MINUS; - case Keyboard.KEY_APOSTROPHE: return Input.Keys.APOSTROPHE; - case Keyboard.KEY_F1: return Input.Keys.F1; - case Keyboard.KEY_F2: return Input.Keys.F2; - case Keyboard.KEY_F3: return Input.Keys.F3; - case Keyboard.KEY_F4: return Input.Keys.F4; - case Keyboard.KEY_F5: return Input.Keys.F5; - case Keyboard.KEY_F6: return Input.Keys.F6; - case Keyboard.KEY_F7: return Input.Keys.F7; - case Keyboard.KEY_F8: return Input.Keys.F8; - case Keyboard.KEY_F9: return Input.Keys.F9; - case Keyboard.KEY_F10: return Input.Keys.F10; - case Keyboard.KEY_F11: return Input.Keys.F11; - case Keyboard.KEY_F12: return Input.Keys.F12; - case Keyboard.KEY_COLON: return Input.Keys.COLON; + case Keyboard.KEY_0: + return Input.Keys.NUM_0; + case Keyboard.KEY_1: + return Input.Keys.NUM_1; + case Keyboard.KEY_2: + return Input.Keys.NUM_2; + case Keyboard.KEY_3: + return Input.Keys.NUM_3; + case Keyboard.KEY_4: + return Input.Keys.NUM_4; + case Keyboard.KEY_5: + return Input.Keys.NUM_5; + case Keyboard.KEY_6: + return Input.Keys.NUM_6; + case Keyboard.KEY_7: + return Input.Keys.NUM_7; + case Keyboard.KEY_8: + return Input.Keys.NUM_8; + case Keyboard.KEY_9: + return Input.Keys.NUM_9; + case Keyboard.KEY_A: + return Input.Keys.A; + case Keyboard.KEY_B: + return Input.Keys.B; + case Keyboard.KEY_C: + return Input.Keys.C; + case Keyboard.KEY_D: + return Input.Keys.D; + case Keyboard.KEY_E: + return Input.Keys.E; + case Keyboard.KEY_F: + return Input.Keys.F; + case Keyboard.KEY_G: + return Input.Keys.G; + case Keyboard.KEY_H: + return Input.Keys.H; + case Keyboard.KEY_I: + return Input.Keys.I; + case Keyboard.KEY_J: + return Input.Keys.J; + case Keyboard.KEY_K: + return Input.Keys.K; + case Keyboard.KEY_L: + return Input.Keys.L; + case Keyboard.KEY_M: + return Input.Keys.M; + case Keyboard.KEY_N: + return Input.Keys.N; + case Keyboard.KEY_O: + return Input.Keys.O; + case Keyboard.KEY_P: + return Input.Keys.P; + case Keyboard.KEY_Q: + return Input.Keys.Q; + case Keyboard.KEY_R: + return Input.Keys.R; + case Keyboard.KEY_S: + return Input.Keys.S; + case Keyboard.KEY_T: + return Input.Keys.T; + case Keyboard.KEY_U: + return Input.Keys.U; + case Keyboard.KEY_V: + return Input.Keys.V; + case Keyboard.KEY_W: + return Input.Keys.W; + case Keyboard.KEY_X: + return Input.Keys.X; + case Keyboard.KEY_Y: + return Input.Keys.Y; + case Keyboard.KEY_Z: + return Input.Keys.Z; + case Keyboard.KEY_LMENU: + return Input.Keys.ALT_LEFT; + case Keyboard.KEY_RMENU: + return Input.Keys.ALT_RIGHT; + case Keyboard.KEY_BACKSLASH: + return Input.Keys.BACKSLASH; + case Keyboard.KEY_COMMA: + return Input.Keys.COMMA; + case Keyboard.KEY_DELETE: + return Input.Keys.FORWARD_DEL; + case Keyboard.KEY_LEFT: + return Input.Keys.DPAD_LEFT; + case Keyboard.KEY_RIGHT: + return Input.Keys.DPAD_RIGHT; + case Keyboard.KEY_UP: + return Input.Keys.DPAD_UP; + case Keyboard.KEY_DOWN: + return Input.Keys.DPAD_DOWN; + case Keyboard.KEY_RETURN: + return Input.Keys.ENTER; + case Keyboard.KEY_HOME: + return Input.Keys.HOME; + case Keyboard.KEY_MINUS: + return Input.Keys.MINUS; + case Keyboard.KEY_PERIOD: + return Input.Keys.PERIOD; + case Keyboard.KEY_ADD: + return Input.Keys.PLUS; + case Keyboard.KEY_SEMICOLON: + return Input.Keys.SEMICOLON; + case Keyboard.KEY_LSHIFT: + return Input.Keys.SHIFT_LEFT; + case Keyboard.KEY_RSHIFT: + return Input.Keys.SHIFT_RIGHT; + case Keyboard.KEY_SLASH: + return Input.Keys.SLASH; + case Keyboard.KEY_SPACE: + return Input.Keys.SPACE; + case Keyboard.KEY_TAB: + return Input.Keys.TAB; + case Keyboard.KEY_LCONTROL: + return Input.Keys.CONTROL_LEFT; + case Keyboard.KEY_RCONTROL: + return Input.Keys.CONTROL_RIGHT; + case Keyboard.KEY_ESCAPE: + return Input.Keys.ESCAPE; + case Keyboard.KEY_END: + return Input.Keys.END; + case Keyboard.KEY_INSERT: + return Input.Keys.INSERT; + case Keyboard.KEY_NUMPAD5: + return Input.Keys.DPAD_CENTER; + case Keyboard.KEY_BACK: + return Input.Keys.DEL; + case Keyboard.KEY_SUBTRACT: + return Input.Keys.MINUS; + case Keyboard.KEY_APOSTROPHE: + return Input.Keys.APOSTROPHE; + case Keyboard.KEY_F1: + return Input.Keys.F1; + case Keyboard.KEY_F2: + return Input.Keys.F2; + case Keyboard.KEY_F3: + return Input.Keys.F3; + case Keyboard.KEY_F4: + return Input.Keys.F4; + case Keyboard.KEY_F5: + return Input.Keys.F5; + case Keyboard.KEY_F6: + return Input.Keys.F6; + case Keyboard.KEY_F7: + return Input.Keys.F7; + case Keyboard.KEY_F8: + return Input.Keys.F8; + case Keyboard.KEY_F9: + return Input.Keys.F9; + case Keyboard.KEY_F10: + return Input.Keys.F10; + case Keyboard.KEY_F11: + return Input.Keys.F11; + case Keyboard.KEY_F12: + return Input.Keys.F12; + case Keyboard.KEY_COLON: + return Input.Keys.COLON; default: return Input.Keys.UNKNOWN; } @@ -440,19 +516,32 @@ public static int getLwjglKeyCode (int gdxKeyCode) { return Keyboard.KEY_RCONTROL; case Input.Keys.ESCAPE: return Keyboard.KEY_ESCAPE; - case Input.Keys.F1: return Keyboard.KEY_F1; - case Input.Keys.F2: return Keyboard.KEY_F2; - case Input.Keys.F3: return Keyboard.KEY_F3; - case Input.Keys.F4: return Keyboard.KEY_F4; - case Input.Keys.F5: return Keyboard.KEY_F5; - case Input.Keys.F6: return Keyboard.KEY_F6; - case Input.Keys.F7: return Keyboard.KEY_F7; - case Input.Keys.F8: return Keyboard.KEY_F8; - case Input.Keys.F9: return Keyboard.KEY_F9; - case Input.Keys.F10: return Keyboard.KEY_F10; - case Input.Keys.F11: return Keyboard.KEY_F11; - case Input.Keys.F12: return Keyboard.KEY_F12; - case Input.Keys.COLON: return Keyboard.KEY_COLON; + case Input.Keys.F1: + return Keyboard.KEY_F1; + case Input.Keys.F2: + return Keyboard.KEY_F2; + case Input.Keys.F3: + return Keyboard.KEY_F3; + case Input.Keys.F4: + return Keyboard.KEY_F4; + case Input.Keys.F5: + return Keyboard.KEY_F5; + case Input.Keys.F6: + return Keyboard.KEY_F6; + case Input.Keys.F7: + return Keyboard.KEY_F7; + case Input.Keys.F8: + return Keyboard.KEY_F8; + case Input.Keys.F9: + return Keyboard.KEY_F9; + case Input.Keys.F10: + return Keyboard.KEY_F10; + case Input.Keys.F11: + return Keyboard.KEY_F11; + case Input.Keys.F12: + return Keyboard.KEY_F12; + case Input.Keys.COLON: + return Keyboard.KEY_COLON; default: return Keyboard.KEY_NONE; } @@ -463,17 +552,14 @@ public void update () { updateKeyboard(); } - private int toGdxButton(int button) { - if(button == 0) - return Buttons.LEFT; - if(button == 1) - return Buttons.RIGHT; - if(button == 2) - return Buttons.MIDDLE; + private int toGdxButton (int button) { + if (button == 0) return Buttons.LEFT; + if (button == 1) return Buttons.RIGHT; + if (button == 2) return Buttons.MIDDLE; return Buttons.LEFT; - + } - + void updateMouse () { justTouched = false; if (Mouse.isCreated()) { @@ -483,26 +569,26 @@ void updateMouse () { int x = Mouse.getEventX(); int y = Gdx.graphics.getHeight() - Mouse.getEventY() - 1; int button = Mouse.getEventButton(); - + TouchEvent event = usedTouchEvents.obtain(); event.x = x; event.y = y; event.button = toGdxButton(button); event.pointer = 0; - + // could be drag, scroll or move - if(button == -1) { - if(Mouse.getEventDWheel() != 0) { + if (button == -1) { + if (Mouse.getEventDWheel() != 0) { event.type = TouchEvent.TOUCH_SCROLLED; event.scrollAmount = (int)-Math.signum(Mouse.getEventDWheel()); - } else if(pressedButtons .size() > 0) { - event.type = TouchEvent.TOUCH_DRAGGED; + } else if (pressedButtons.size() > 0) { + event.type = TouchEvent.TOUCH_DRAGGED; } else { event.type = TouchEvent.TOUCH_MOVED; } } else { // nope, it's a down or up event. - if(Mouse.getEventButtonState()) { + if (Mouse.getEventButtonState()) { event.type = TouchEvent.TOUCH_DOWN; pressedButtons.add(event.button); justTouched = true; @@ -511,15 +597,15 @@ void updateMouse () { pressedButtons.remove(event.button); } } - + touchEvents.add(event); mouseX = event.x; mouseY = event.y; deltaX = Mouse.getEventDX(); deltaY = Mouse.getEventDY(); } - - if(events == 0) { + + if (events == 0) { deltaX = 0; deltaY = 0; } @@ -551,7 +637,7 @@ void updateKeyboard () { event.keyChar = 0; event.type = KeyEvent.KEY_DOWN; keyEvents.add(event); - + event = usedKeyEvents.obtain(); event.keyCode = 0; event.keyChar = keyChar; @@ -577,99 +663,120 @@ void updateKeyboard () { } } - @Override public void setInputProcessor (InputProcessor processor) { + @Override + public void setInputProcessor (InputProcessor processor) { this.processor = processor; } - - @Override public InputProcessor getInputProcessor() { + + @Override + public InputProcessor getInputProcessor () { return this.processor; } - @Override public void vibrate (int milliseconds) { + @Override + public void vibrate (int milliseconds) { } - @Override public boolean justTouched () { + @Override + public boolean justTouched () { return justTouched; } - - private int toLwjglButton(int button) { - if(button == Buttons.LEFT) - return 0; - if(button == Buttons.RIGHT) - return 1; - if(button == Buttons.MIDDLE) - return 2; + + private int toLwjglButton (int button) { + if (button == Buttons.LEFT) return 0; + if (button == Buttons.RIGHT) return 1; + if (button == Buttons.MIDDLE) return 2; return 0; } - @Override public boolean isButtonPressed (int button) { + @Override + public boolean isButtonPressed (int button) { return Mouse.isButtonDown(toLwjglButton(button)); } - @Override public void vibrate (long[] pattern, int repeat) { + @Override + public void vibrate (long[] pattern, int repeat) { } - @Override public void cancelVibrate () { + @Override + public void cancelVibrate () { } - @Override public float getAzimuth () { + @Override + public float getAzimuth () { return 0; } - @Override public float getPitch () { + @Override + public float getPitch () { return 0; } - @Override public float getRoll () { + @Override + public float getRoll () { return 0; } - - @Override public boolean isPeripheralAvailable (Peripheral peripheral) { - if(peripheral == Peripheral.HardwareKeyboard) return true; + + @Override + public boolean isPeripheralAvailable (Peripheral peripheral) { + if (peripheral == Peripheral.HardwareKeyboard) return true; return false; } - @Override public int getRotation () { + @Override + public int getRotation () { return 0; } - @Override public Orientation getNativeOrientation () { + @Override + public Orientation getNativeOrientation () { return Orientation.Landscape; } - @Override public void setCursorCatched (boolean catched) { + @Override + public void setCursorCatched (boolean catched) { Mouse.setGrabbed(catched); } - @Override public boolean isCursorCatched () { + @Override + public boolean isCursorCatched () { return Mouse.isGrabbed(); } - @Override public int getDeltaX () { + @Override + public int getDeltaX () { return deltaX; } - @Override public int getDeltaX (int pointer) { - if(pointer == 0) return deltaX; - else return 0; + @Override + public int getDeltaX (int pointer) { + if (pointer == 0) + return deltaX; + else + return 0; } - @Override public int getDeltaY () { + @Override + public int getDeltaY () { return deltaY; } - @Override public int getDeltaY (int pointer) { - if(pointer == 0) return deltaY; - else return 0; + @Override + public int getDeltaY (int pointer) { + if (pointer == 0) + return deltaY; + else + return 0; } - @Override public void setCursorPosition (int x, int y) { + @Override + public void setCursorPosition (int x, int y) { Mouse.setCursorPosition(x, y); } @Override - public void setCatchMenuKey(boolean catchMenu) { + public void setCatchMenuKey (boolean catchMenu) { // TODO Auto-generated method stub - + } } diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNativesLoader.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNativesLoader.java index 17e8d3fb4f3..45a6b7d4518 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNativesLoader.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglNativesLoader.java @@ -13,15 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; import java.lang.reflect.Method; -import com.badlogic.gdx.Version; import com.badlogic.gdx.utils.GdxNativesLoader; import static com.badlogic.gdx.utils.GdxNativesLoader.*; @@ -43,7 +39,7 @@ final class LwjglNativesLoader { static void load () { GdxNativesLoader.load(); - if(GdxNativesLoader.disableNativesLoading) return; + if (GdxNativesLoader.disableNativesLoading) return; if (!load) return; if (isWindows) { extractLibrary("OpenAL32.dll", "OpenAL64.dll"); diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglPreferences.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglPreferences.java index 41e556c51ad..84d7e20ef66 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglPreferences.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglPreferences.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.lwjgl; import java.io.BufferedInputStream; @@ -31,133 +32,151 @@ public class LwjglPreferences implements Preferences { private final String name; private final Properties properties = new Properties(); - LwjglPreferences(String name) { + LwjglPreferences (String name) { this.name = name; InputStream in = null; try { in = new BufferedInputStream(Gdx.files.external(name).read()); properties.loadFromXML(in); - } catch(Throwable t) { + } catch (Throwable t) { } finally { - if(in != null) try { in.close(); } catch(Exception e) { } + if (in != null) try { + in.close(); + } catch (Exception e) { + } } - + Runtime.getRuntime().addShutdownHook(new Thread() { - @Override public void run() { + @Override + public void run () { flush(); } }); - } - - @Override public void putBoolean (String key, boolean val) { + } + + @Override + public void putBoolean (String key, boolean val) { properties.put(key, Boolean.toString(val)); } - @Override public void putInteger (String key, int val) { + @Override + public void putInteger (String key, int val) { properties.put(key, Integer.toString(val)); } - @Override public void putLong (String key, long val) { + @Override + public void putLong (String key, long val) { properties.put(key, Long.toString(val)); } - @Override public void putFloat (String key, float val) { + @Override + public void putFloat (String key, float val) { properties.put(key, Float.toString(val)); } - @Override public void putString (String key, String val) { + @Override + public void putString (String key, String val) { properties.put(key, val); } - @Override public void put (Map vals) { - for(Entry val: vals.entrySet()) { - if(val.getValue() instanceof Boolean) - putBoolean(val.getKey(), (Boolean)val.getValue()); - if(val.getValue() instanceof Integer) - putInteger(val.getKey(), (Integer)val.getValue()); - if(val.getValue() instanceof Long) - putLong(val.getKey(), (Long)val.getValue()); - if(val.getValue() instanceof String) - putString(val.getKey(), (String)val.getValue()); - if(val.getValue() instanceof Float) - putFloat(val.getKey(), (Float)val.getValue()); + @Override + public void put (Map vals) { + for (Entry val : vals.entrySet()) { + if (val.getValue() instanceof Boolean) putBoolean(val.getKey(), (Boolean)val.getValue()); + if (val.getValue() instanceof Integer) putInteger(val.getKey(), (Integer)val.getValue()); + if (val.getValue() instanceof Long) putLong(val.getKey(), (Long)val.getValue()); + if (val.getValue() instanceof String) putString(val.getKey(), (String)val.getValue()); + if (val.getValue() instanceof Float) putFloat(val.getKey(), (Float)val.getValue()); } } - @Override public boolean getBoolean (String key) { + @Override + public boolean getBoolean (String key) { return getBoolean(key, false); } - @Override public int getInteger (String key) { + @Override + public int getInteger (String key) { return getInteger(key, 0); } - @Override public long getLong (String key) { + @Override + public long getLong (String key) { return getLong(key, 0); } - @Override public float getFloat (String key) { + @Override + public float getFloat (String key) { return getFloat(key, 0); } - @Override public String getString (String key) { + @Override + public String getString (String key) { return getString(key, ""); } - @Override public boolean getBoolean (String key, boolean defValue) { + @Override + public boolean getBoolean (String key, boolean defValue) { return Boolean.parseBoolean(properties.getProperty(key, Boolean.toString(defValue))); } - @Override public int getInteger (String key, int defValue) { + @Override + public int getInteger (String key, int defValue) { return Integer.parseInt(properties.getProperty(key, Integer.toString(defValue))); } - @Override public long getLong (String key, long defValue) { + @Override + public long getLong (String key, long defValue) { return Long.parseLong(properties.getProperty(key, Long.toString(defValue))); } - @Override public float getFloat (String key, float defValue) { + @Override + public float getFloat (String key, float defValue) { return Float.parseFloat(properties.getProperty(key, Float.toString(defValue))); } - @Override public String getString (String key, String defValue) { + @Override + public String getString (String key, String defValue) { return properties.getProperty(key, defValue); } - @Override public Map get () { + @Override + public Map get () { Map map = new HashMap(); - for(Entry val: properties.entrySet()) { - if(val.getValue() instanceof Boolean) - map.put((String)val.getKey(), (Boolean)Boolean.parseBoolean((String)val.getValue())); - if(val.getValue() instanceof Integer) - map.put((String)val.getKey(), (Integer)Integer.parseInt((String)val.getValue())); - if(val.getValue() instanceof Long) - map.put((String)val.getKey(), (Long)Long.parseLong((String)val.getValue())); - if(val.getValue() instanceof String) - map.put((String)val.getKey(), (String)val.getValue()); - if(val.getValue() instanceof Float) - map.put((String)val.getKey(), (Float)Float.parseFloat((String)val.getValue())); + for (Entry val : properties.entrySet()) { + if (val.getValue() instanceof Boolean) + map.put((String)val.getKey(), (Boolean)Boolean.parseBoolean((String)val.getValue())); + if (val.getValue() instanceof Integer) map.put((String)val.getKey(), (Integer)Integer.parseInt((String)val.getValue())); + if (val.getValue() instanceof Long) map.put((String)val.getKey(), (Long)Long.parseLong((String)val.getValue())); + if (val.getValue() instanceof String) map.put((String)val.getKey(), (String)val.getValue()); + if (val.getValue() instanceof Float) map.put((String)val.getKey(), (Float)Float.parseFloat((String)val.getValue())); } - + return map; } - @Override public boolean contains (String key) { + @Override + public boolean contains (String key) { return properties.containsKey(key); } - @Override public void clear () { + @Override + public void clear () { properties.clear(); } - - @Override public void flush () { + + @Override + public void flush () { OutputStream out = null; try { out = new BufferedOutputStream(Gdx.files.external(LwjglPreferences.this.name).write(false)); properties.storeToXML(out, null); - } catch(Throwable t) { + } catch (Throwable t) { } finally { - if(out != null) try { out.close(); } catch(Exception e) { } + if (out != null) try { + out.close(); + } catch (Exception e) { + } } } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleApplication.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleApplication.java index 78b15a0d8c1..63377c29fd0 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleApplication.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleApplication.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.util.ArrayList; @@ -68,59 +69,71 @@ public void run () { }).run(); } - @Override public Graphics getGraphics () { + @Override + public Graphics getGraphics () { return graphics; } - @Override public Audio getAudio () { + @Override + public Audio getAudio () { return audio; } - @Override public Input getInput () { + @Override + public Input getInput () { return input; } - @Override public Files getFiles () { + @Override + public Files getFiles () { return files; } - @Override public ApplicationType getType () { + @Override + public ApplicationType getType () { return ApplicationType.Desktop; } - @Override public int getVersion () { + @Override + public int getVersion () { return 0; } - @Override public long getJavaHeap () { + @Override + public long getJavaHeap () { return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } - @Override public long getNativeHeap () { + @Override + public long getNativeHeap () { return getJavaHeap(); } - @Override public void onKey (int action, int key, int keyCode) { + @Override + public void onKey (int action, int key, int keyCode) { input.registerKeyEvent(action, key, keyCode); } - @Override public void onMouse (int action, int x, int y, int button) { + @Override + public void onMouse (int action, int x, int y, int button) { input.registerMouseEvent(action, x, y, button); } - @Override public void quit () { + @Override + public void quit () { listener.pause(); listener.dispose(); } - @Override public void render () { + @Override + public void render () { graphics.updateTime(); if (!created) { - listener.create(); + listener.create(); created = true; } synchronized (runnables) { - for(int i = 0; i < runnables.size(); i++) { + for (int i = 0; i < runnables.size(); i++) { runnables.get(i).run(); } runnables.clear(); @@ -130,15 +143,18 @@ public void run () { input.justTouched = false; } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { graphics.width = width; graphics.height = height; if (!created) listener.resize(width, height); } Map preferences = new HashMap(); - @Override public Preferences getPreferences (String name) { - if(preferences.containsKey(name)) { + + @Override + public Preferences getPreferences (String name) { + if (preferences.containsKey(name)) { return preferences.get(name); } else { Preferences prefs = new AnglePreferences(name); @@ -147,52 +163,57 @@ public void run () { } } - @Override public void postRunnable (Runnable runnable) { - synchronized(runnables) { + @Override + public void postRunnable (Runnable runnable) { + synchronized (runnables) { runnables.add(runnable); - } + } } - - @Override - public void log(String tag, String message) { - if(logLevel >= LOG_INFO) { - System.out.println(tag + ":" + message); + + @Override + public void log (String tag, String message) { + if (logLevel >= LOG_INFO) { + System.out.println(tag + ":" + message); } - } + } - @Override public void log (String tag, String message, Exception exception) { - if(logLevel >= LOG_INFO) { + @Override + public void log (String tag, String message, Exception exception) { + if (logLevel >= LOG_INFO) { System.out.println(tag + ":" + message); exception.printStackTrace(System.out); } } - - @Override public void error (String tag, String message) { - if(logLevel >= LOG_ERROR) { - System.err.println(tag + ":" + message); + + @Override + public void error (String tag, String message) { + if (logLevel >= LOG_ERROR) { + System.err.println(tag + ":" + message); } } - - @Override public void error (String tag, String message, Exception exception) { - if(logLevel >= LOG_ERROR) { + @Override + public void error (String tag, String message, Exception exception) { + if (logLevel >= LOG_ERROR) { System.err.println(tag + ":" + message); exception.printStackTrace(System.err); } } - - @Override public void setLogLevel (int logLevel) { + @Override + public void setLogLevel (int logLevel) { this.logLevel = logLevel; } - @Override public void exit () { + @Override + public void exit () { postRunnable(new Runnable() { - @Override public void run () { + @Override + public void run () { AngleApplication.this.listener.pause(); AngleApplication.this.listener.dispose(); System.exit(-1); - } + } }); } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudio.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudio.java index 9fa517f114a..f8b5a6146a4 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudio.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudio.java @@ -44,12 +44,9 @@ import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * An implementation of the {@link Audio} interface for the desktop. +/** An implementation of the {@link Audio} interface for the desktop. * - * @author mzechner - * - */ + * @author mzechner */ final class AngleAudio implements Audio, Runnable { /** the audio line for sound effects **/ private SourceDataLine line; @@ -62,12 +59,9 @@ final class AngleAudio implements Audio, Runnable { private volatile boolean run = false; - /** - * Helper class for playing back sound effects concurrently. - * - * @author mzechner + /** Helper class for playing back sound effects concurrently. * - */ + * @author mzechner */ class AngleSoundBuffer { private final float[] samples; private final AudioFormat format; @@ -80,10 +74,8 @@ public AngleSoundBuffer (AngleSound sound, float volume) throws Exception { this.volume = volume; } - /** - * Writes the next numFrames frames to the line for playback - * @return whether playback is done or not. - */ + /** 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); diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioDevice.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioDevice.java index d0192747c32..beac2faea43 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioDevice.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioDevice.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import javax.sound.sampled.AudioFormat; @@ -22,12 +23,9 @@ import com.badlogic.gdx.audio.AudioDevice; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Implementation of the {@link AudioDevice} interface for the desktop using Java Sound. - * - * @author mzechner +/** Implementation of the {@link AudioDevice} interface for the desktop using Java Sound. * - */ + * @author mzechner */ final class AngleAudioDevice implements AudioDevice { /** the audio line **/ private SourceDataLine line; @@ -91,7 +89,8 @@ public void writeSamples (float[] samples, int offset, int numSamples) { writtenBytes += line.write(bytes, writtenBytes, numSamples * 2 - writtenBytes); } - @Override public int getLatency () { + @Override + public int getLatency () { return 0; } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioRecorder.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioRecorder.java index 9f5270de441..c056ebc0857 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioRecorder.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleAudioRecorder.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import javax.sound.sampled.AudioFormat; @@ -23,12 +24,9 @@ import com.badlogic.gdx.audio.AudioRecorder; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * {@link AudioRecorder} implementation for the desktop using the java sound API. - * - * @author badlogicgames@gmail.com +/** {@link AudioRecorder} implementation for the desktop using the java sound API. * - */ + * @author badlogicgames@gmail.com */ final class AngleAudioRecorder implements AudioRecorder { /** the line we read the audio from **/ private TargetDataLine line; diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFileHandle.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFileHandle.java index d36176cd29d..630099719ac 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFileHandle.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFileHandle.java @@ -34,10 +34,8 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; -/** - * @author mzechner - * @author Nathan Sweet - */ +/** @author mzechner + * @author Nathan Sweet */ final class AngleFileHandle extends FileHandle { AngleFileHandle (String fileName, FileType type) { super(fileName, type); diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFiles.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFiles.java index ae37f6a2aa4..1fbb35a82e5 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFiles.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleFiles.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import com.badlogic.gdx.Files; @@ -21,31 +22,38 @@ public class AngleFiles implements Files { private final String externalPath = System.getProperty("user.home") + "/"; - @Override public FileHandle getFileHandle (String fileName, FileType type) { + @Override + public FileHandle getFileHandle (String fileName, FileType type) { return new AngleFileHandle(fileName, type); } - @Override public FileHandle classpath (String path) { + @Override + public FileHandle classpath (String path) { return new AngleFileHandle(path, FileType.Classpath); } - @Override public FileHandle internal (String path) { + @Override + public FileHandle internal (String path) { return new AngleFileHandle(path, FileType.Internal); } - @Override public FileHandle external (String path) { + @Override + public FileHandle external (String path) { return new AngleFileHandle(path, FileType.External); } - @Override public FileHandle absolute (String path) { + @Override + public FileHandle absolute (String path) { return new AngleFileHandle(path, FileType.Absolute); } - @Override public String getExternalStoragePath () { + @Override + public String getExternalStoragePath () { return externalPath; } - @Override public boolean isExternalStorageAvailable () { + @Override + public boolean isExternalStorageAvailable () { return true; } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLES0.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLES0.java index 50464a0c536..6ffb7ceb01a 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLES0.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLES0.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.nio.Buffer; diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLU.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLU.java index 51ca6016a74..ecd7936f0cf 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLU.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGLU.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.nio.FloatBuffer; @@ -22,58 +23,69 @@ import com.badlogic.gdx.graphics.GLU; import com.badlogic.gdx.utils.BufferUtils; -public class AngleGLU implements GLU{ - +public class AngleGLU implements GLU { + FloatBuffer modelb; FloatBuffer projectb; IntBuffer viewb; FloatBuffer winb; - - public AngleGLU() { + + public AngleGLU () { modelb = BufferUtils.newFloatBuffer(16); projectb = BufferUtils.newFloatBuffer(16); viewb = BufferUtils.newIntBuffer(4); winb = BufferUtils.newFloatBuffer(3); } - @Override public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, - float upX, float upY, float upZ) { + @Override + public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, + float upY, float upZ) { throw new UnsupportedOperationException(); } - @Override public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { + @Override + public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top) { throw new UnsupportedOperationException(); } - @Override public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { + @Override + public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar) { throw new UnsupportedOperationException(); } - @Override public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] win, int winOffset) { - modelb.clear(); modelb.put(model, modelOffset, 16); - projectb.clear(); projectb.put(project, projectOffset, 16); - viewb.clear(); viewb.put(view, viewOffset, 4); + modelb.clear(); + modelb.put(model, modelOffset, 16); + projectb.clear(); + projectb.put(project, projectOffset, 16); + viewb.clear(); + viewb.put(view, viewOffset, 4); winb.clear(); - + boolean result = org.lwjgl.util.glu.GLU.gluProject(objX, objY, objZ, modelb, projectb, viewb, winb); win[winOffset] = winb.get(0); - win[winOffset+1] = winb.get(1); - win[winOffset+2] = winb.get(2); + win[winOffset + 1] = winb.get(1); + win[winOffset + 2] = winb.get(2); return result; } - @Override public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, + @Override + public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] obj, int objOffset) { - modelb.clear(); modelb.put(model, modelOffset, 16); - projectb.clear(); projectb.put(project, projectOffset, 16); - viewb.clear(); viewb.put(view, viewOffset, 4); + modelb.clear(); + modelb.put(model, modelOffset, 16); + projectb.clear(); + projectb.put(project, projectOffset, 16); + viewb.clear(); + viewb.put(view, viewOffset, 4); winb.clear(); - + boolean result = org.lwjgl.util.glu.GLU.gluUnProject(winX, winY, winZ, modelb, projectb, viewb, winb); obj[objOffset] = winb.get(0); - obj[objOffset+1] = winb.get(1); - obj[objOffset+2] = winb.get(2); + obj[objOffset + 1] = winb.get(1); + obj[objOffset + 2] = winb.get(2); return result; } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGraphics.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGraphics.java index c64120bf96e..5f3189268a5 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGraphics.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleGraphics.java @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.awt.Toolkit; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Graphics; -import com.badlogic.gdx.Graphics.DisplayMode; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.graphics.GL20; @@ -44,67 +44,83 @@ public class AngleGraphics implements Graphics { glu = new AngleGLU(); } - @Override public boolean isGL11Available () { + @Override + public boolean isGL11Available () { return false; } - @Override public boolean isGL20Available () { + @Override + public boolean isGL20Available () { return true; } - @Override public GLCommon getGLCommon () { + @Override + public GLCommon getGLCommon () { return gl; } - @Override public GL10 getGL10 () { + @Override + public GL10 getGL10 () { return null; } - @Override public GL11 getGL11 () { + @Override + public GL11 getGL11 () { return null; } - @Override public GL20 getGL20 () { + @Override + public GL20 getGL20 () { return gl; } - - @Override public GLU getGLU() { + + @Override + public GLU getGLU () { return glu; } - @Override public int getWidth () { + @Override + public int getWidth () { return width; } - @Override public int getHeight () { + @Override + public int getHeight () { return height; } - @Override public float getDeltaTime () { + @Override + public float getDeltaTime () { return deltaTime; } - @Override public int getFramesPerSecond () { + @Override + public int getFramesPerSecond () { return fps; } - @Override public GraphicsType getType () { + @Override + public GraphicsType getType () { return GraphicsType.Angle; } - @Override public float getPpiX () { + @Override + public float getPpiX () { return Toolkit.getDefaultToolkit().getScreenResolution(); } - @Override public float getPpiY () { + @Override + public float getPpiY () { return Toolkit.getDefaultToolkit().getScreenResolution(); } - @Override public float getPpcX () { + @Override + public float getPpcX () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f); } - @Override public float getPpcY () { + @Override + public float getPpcY () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 2.54f); } @@ -121,50 +137,60 @@ void updateTime () { frames++; } - @Override public boolean supportsDisplayModeChange () { + @Override + public boolean supportsDisplayModeChange () { return false; } - @Override public boolean setDisplayMode (DisplayMode displayMode) { + @Override + public boolean setDisplayMode (DisplayMode displayMode) { return false; } - - @Override public DisplayMode[] getDisplayModes () { + + @Override + public DisplayMode[] getDisplayModes () { return new DisplayMode[0]; } - @Override public void setTitle (String title) { - + @Override + public void setTitle (String title) { + } - @Override public void setIcon (Pixmap pixmap) { - + @Override + public void setIcon (Pixmap pixmap) { + } - @Override public DisplayMode getDesktopDisplayMode () { + @Override + public DisplayMode getDesktopDisplayMode () { return null; } - @Override public boolean setDisplayMode (int width, int height, boolean fullscreen) { + @Override + public boolean setDisplayMode (int width, int height, boolean fullscreen) { return false; } - @Override public void setVSync (boolean vsync) { + @Override + public void setVSync (boolean vsync) { // TODO Auto-generated method stub - + } - @Override public BufferFormat getBufferFormat () { + @Override + public BufferFormat getBufferFormat () { return null; } - - @Override public boolean supportsExtension (String extension) { - if(extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); + + @Override + public boolean supportsExtension (String extension) { + if (extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); return extensions.contains(extension); } @Override - public float getDensity() { + public float getDensity () { return (Toolkit.getDefaultToolkit().getScreenResolution() / 160f); } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleInput.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleInput.java index 5eb29ce7946..d870ef62a81 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleInput.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleInput.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.util.ArrayList; @@ -98,7 +99,7 @@ public void run () { }); } - public int getX () { + public int getX () { return mouseY; } @@ -111,7 +112,7 @@ public boolean isAccelerometerAvailable () { } public boolean isKeyPressed (int key) { - if(key == Keys.ANY_KEY) + if (key == Keys.ANY_KEY) return pressedKeys.size() > 0; else return pressedKeys.contains(key); @@ -146,18 +147,20 @@ public boolean supportsMultitouch () { return false; } - @Override public void setOnscreenKeyboardVisible (boolean visible) { + @Override + public void setOnscreenKeyboardVisible (boolean visible) { } - @Override public void setCatchBackKey (boolean catchBack) { + @Override + public void setCatchBackKey (boolean catchBack) { } void processEvents () { synchronized (this) { justTouched = false; - + if (processor != null) { InputProcessor processor = this.processor; int len = keyEvents.size(); @@ -203,8 +206,9 @@ void processEvents () { int len = touchEvents.size(); for (int i = 0; i < len; i++) { TouchEvent event = touchEvents.get(i); - if(event.type == TouchEvent.TOUCH_DOWN); - justTouched = true; + if (event.type == TouchEvent.TOUCH_DOWN) + ; + justTouched = true; usedTouchEvents.free(event); } @@ -223,11 +227,13 @@ boolean isButtonPressed () { return mousePressed; } - @Override public void setInputProcessor (InputProcessor processor) { + @Override + public void setInputProcessor (InputProcessor processor) { this.processor = processor; } - - @Override public InputProcessor getInputProcessor() { + + @Override + public InputProcessor getInputProcessor () { return this.processor; } @@ -248,7 +254,7 @@ void registerKeyEvent (int action, int key, int uniCode) { break; case ESLoop.ES_KEY_TYPED: event.type = KeyEvent.KEY_TYPED; - break; + break; } keyEvents.add(event); @@ -267,15 +273,15 @@ void registerMouseEvent (int action, int x, int y, int button) { event.type = TouchEvent.TOUCH_DOWN; mousePressed = true; justTouched = true; - if((button & ESLoop.ES_MOUSE_LBUTTON) != 0) { + if ((button & ESLoop.ES_MOUSE_LBUTTON) != 0) { pressedButtons.add(Buttons.LEFT); event.button = Buttons.LEFT; } - if((button & ESLoop.ES_MOUSE_RBUTTON) != 0) { + if ((button & ESLoop.ES_MOUSE_RBUTTON) != 0) { pressedButtons.add(Buttons.RIGHT); event.button = Buttons.RIGHT; } - if((button & ESLoop.ES_MOUSE_MBUTTON) != 0) { + if ((button & ESLoop.ES_MOUSE_MBUTTON) != 0) { pressedButtons.add(Buttons.MIDDLE); event.button = Buttons.MIDDLE; } @@ -283,195 +289,286 @@ void registerMouseEvent (int action, int x, int y, int button) { case ESLoop.ES_MOUSE_UP: event.type = TouchEvent.TOUCH_UP; mousePressed = false; - if((button & ESLoop.ES_MOUSE_LBUTTON) != 0) { + if ((button & ESLoop.ES_MOUSE_LBUTTON) != 0) { pressedButtons.remove(Buttons.LEFT); - event.button = Buttons.LEFT; + event.button = Buttons.LEFT; } - if((button & ESLoop.ES_MOUSE_RBUTTON) != 0) { + if ((button & ESLoop.ES_MOUSE_RBUTTON) != 0) { pressedButtons.remove(Buttons.RIGHT); event.button = Buttons.RIGHT; } - if((button & ESLoop.ES_MOUSE_MBUTTON) != 0) { + if ((button & ESLoop.ES_MOUSE_MBUTTON) != 0) { pressedButtons.remove(Buttons.MIDDLE); event.button = Buttons.MIDDLE; } break; case ESLoop.ES_MOUSE_MOVE: - if(!mousePressed) + if (!mousePressed) event.type = TouchEvent.TOUCH_MOVED; else event.type = TouchEvent.TOUCH_DRAGGED; - break; + break; case ESLoop.ES_MOUSE_WHEEL: event.type = TouchEvent.TOUCH_SCROLL; event.scrollAmount = -(int)Math.signum(x); break; } - + touchEvents.add(event); } } int toGdxKeyCode (int keyCode) { - switch(keyCode) { - case 0x08: return Keys.BACK; - case 0x09: return Keys.TAB; - case 0x0d: return Keys.ENTER; - case 0x10: return Keys.SHIFT_LEFT; - case 0x11: return Keys.CONTROL_LEFT; - case 0x12: return Keys.ALT_LEFT; -// case 0x13: return Keys.KEYCODE_PAUSE; -// case 0x14: return Keys.KEYCODE_CAPS; - case 0x18: return Keys.ESCAPE; - case 0x20: return Keys.SPACE; - case 0x23: return Keys.END; - case 0x24: return Keys.HOME; - case 0x25: return Keys.DPAD_LEFT; - case 0x26: return Keys.DPAD_UP; - case 0x27: return Keys.DPAD_RIGHT; - case 0x28: return Keys.DPAD_DOWN; - case 0x2d: return Keys.INSERT; - case 0x2e: return Keys.DEL; - case 0x30: return Keys.NUM_0; - case 0x31: return Keys.NUM_1; - case 0x32: return Keys.NUM_2; - case 0x33: return Keys.NUM_3; - case 0x34: return Keys.NUM_4; - case 0x35: return Keys.NUM_5; - case 0x36: return Keys.NUM_6; - case 0x37: return Keys.NUM_7; - case 0x38: return Keys.NUM_8; - case 0x39: return Keys.NUM_9; - case 0x41: return Keys.A; - case 0x42: return Keys.B; - case 0x43: return Keys.C; - case 0x44: return Keys.D; - case 0x45: return Keys.E; - case 0x46: return Keys.F; - case 0x47: return Keys.G; - case 0x48: return Keys.H; - case 0x49: return Keys.I; - case 0x4a: return Keys.J; - case 0x4b: return Keys.K; - case 0x4c: return Keys.L; - case 0x4d: return Keys.M; - case 0x4e: return Keys.N; - case 0x4f: return Keys.O; - case 0x50: return Keys.P; - case 0x51: return Keys.Q; - case 0x52: return Keys.R; - case 0x53: return Keys.S; - case 0x54: return Keys.T; - case 0x55: return Keys.U; - case 0x56: return Keys.V; - case 0x57: return Keys.W; - case 0x58: return Keys.X; - case 0x59: return Keys.Y; - case 0x5a: return Keys.Z; - case 0x60: return Keys.NUM_0; - case 0x61: return Keys.NUM_1; - case 0x62: return Keys.NUM_2; - case 0x63: return Keys.NUM_3; - case 0x64: return Keys.NUM_4; - case 0x65: return Keys.NUM_5; - case 0x66: return Keys.NUM_6; - case 0x67: return Keys.NUM_7; - case 0x68: return Keys.NUM_8; - case 0x69: return Keys.NUM_9; - case 0x6a: return Keys.STAR; - case 0x6b: return Keys.PLUS; - case 0x6d: return Keys.MINUS; - case 0x6e: return Keys.PERIOD; - case 0x6f: return Keys.SLASH; - case 0xa0: return Keys.SHIFT_LEFT; - case 0xa1: return Keys.SHIFT_RIGHT; - case 0xa2: return Keys.CONTROL_LEFT; - case 0xa3: return Keys.CONTROL_RIGHT; - case 0xae: return Keys.VOLUME_DOWN; - case 0xaf: return Keys.VOLUME_UP; - default: - return Keys.UNKNOWN; - } - } - - @Override public void vibrate (int milliseconds) { - - } - - @Override public boolean justTouched () { + switch (keyCode) { + case 0x08: + return Keys.BACK; + case 0x09: + return Keys.TAB; + case 0x0d: + return Keys.ENTER; + case 0x10: + return Keys.SHIFT_LEFT; + case 0x11: + return Keys.CONTROL_LEFT; + case 0x12: + return Keys.ALT_LEFT; +// case 0x13: return Keys.KEYCODE_PAUSE; +// case 0x14: return Keys.KEYCODE_CAPS; + case 0x18: + return Keys.ESCAPE; + case 0x20: + return Keys.SPACE; + case 0x23: + return Keys.END; + case 0x24: + return Keys.HOME; + case 0x25: + return Keys.DPAD_LEFT; + case 0x26: + return Keys.DPAD_UP; + case 0x27: + return Keys.DPAD_RIGHT; + case 0x28: + return Keys.DPAD_DOWN; + case 0x2d: + return Keys.INSERT; + case 0x2e: + return Keys.DEL; + case 0x30: + return Keys.NUM_0; + case 0x31: + return Keys.NUM_1; + case 0x32: + return Keys.NUM_2; + case 0x33: + return Keys.NUM_3; + case 0x34: + return Keys.NUM_4; + case 0x35: + return Keys.NUM_5; + case 0x36: + return Keys.NUM_6; + case 0x37: + return Keys.NUM_7; + case 0x38: + return Keys.NUM_8; + case 0x39: + return Keys.NUM_9; + case 0x41: + return Keys.A; + case 0x42: + return Keys.B; + case 0x43: + return Keys.C; + case 0x44: + return Keys.D; + case 0x45: + return Keys.E; + case 0x46: + return Keys.F; + case 0x47: + return Keys.G; + case 0x48: + return Keys.H; + case 0x49: + return Keys.I; + case 0x4a: + return Keys.J; + case 0x4b: + return Keys.K; + case 0x4c: + return Keys.L; + case 0x4d: + return Keys.M; + case 0x4e: + return Keys.N; + case 0x4f: + return Keys.O; + case 0x50: + return Keys.P; + case 0x51: + return Keys.Q; + case 0x52: + return Keys.R; + case 0x53: + return Keys.S; + case 0x54: + return Keys.T; + case 0x55: + return Keys.U; + case 0x56: + return Keys.V; + case 0x57: + return Keys.W; + case 0x58: + return Keys.X; + case 0x59: + return Keys.Y; + case 0x5a: + return Keys.Z; + case 0x60: + return Keys.NUM_0; + case 0x61: + return Keys.NUM_1; + case 0x62: + return Keys.NUM_2; + case 0x63: + return Keys.NUM_3; + case 0x64: + return Keys.NUM_4; + case 0x65: + return Keys.NUM_5; + case 0x66: + return Keys.NUM_6; + case 0x67: + return Keys.NUM_7; + case 0x68: + return Keys.NUM_8; + case 0x69: + return Keys.NUM_9; + case 0x6a: + return Keys.STAR; + case 0x6b: + return Keys.PLUS; + case 0x6d: + return Keys.MINUS; + case 0x6e: + return Keys.PERIOD; + case 0x6f: + return Keys.SLASH; + case 0xa0: + return Keys.SHIFT_LEFT; + case 0xa1: + return Keys.SHIFT_RIGHT; + case 0xa2: + return Keys.CONTROL_LEFT; + case 0xa3: + return Keys.CONTROL_RIGHT; + case 0xae: + return Keys.VOLUME_DOWN; + case 0xaf: + return Keys.VOLUME_UP; + default: + return Keys.UNKNOWN; + } + } + + @Override + public void vibrate (int milliseconds) { + + } + + @Override + public boolean justTouched () { return justTouched; - } - - @Override public boolean isButtonPressed (int button) { + } + + @Override + public boolean isButtonPressed (int button) { return pressedButtons.contains(button); } - @Override public void vibrate (long[] pattern, int repeat) { + @Override + public void vibrate (long[] pattern, int repeat) { } - @Override public void cancelVibrate () { + @Override + public void cancelVibrate () { } - @Override public float getAzimuth () { + @Override + public float getAzimuth () { return 0; } - @Override public float getPitch () { + @Override + public float getPitch () { return 0; } - @Override public float getRoll () { + @Override + public float getRoll () { return 0; } - - @Override public boolean isPeripheralAvailable (Peripheral peripheral) { - if(peripheral == Peripheral.HardwareKeyboard) return true; + + @Override + public boolean isPeripheralAvailable (Peripheral peripheral) { + if (peripheral == Peripheral.HardwareKeyboard) return true; return false; } - @Override public int getRotation () { + @Override + public int getRotation () { return 0; } - @Override public Orientation getNativeOrientation () { + @Override + public Orientation getNativeOrientation () { return Orientation.Landscape; } - @Override public void setCursorCatched (boolean catched) { + @Override + public void setCursorCatched (boolean catched) { } - @Override public boolean isCursorCatched () { + @Override + public boolean isCursorCatched () { return false; } - @Override public int getDeltaX () { + @Override + public int getDeltaX () { // TODO Auto-generated method stub return 0; } - @Override public int getDeltaX (int pointer) { + @Override + public int getDeltaX (int pointer) { // TODO Auto-generated method stub return 0; } - @Override public int getDeltaY () { + @Override + public int getDeltaY () { // TODO Auto-generated method stub return 0; } - @Override public int getDeltaY (int pointer) { + @Override + public int getDeltaY (int pointer) { // TODO Auto-generated method stub return 0; } - @Override public void setCursorPosition (int x, int y) { + @Override + public void setCursorPosition (int x, int y) { // TODO Auto-generated method stub - + } @Override - public void setCatchMenuKey(boolean catchMenu) { + public void setCatchMenuKey (boolean catchMenu) { // TODO Auto-generated method stub - - } + + } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleMusic.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleMusic.java index 44e4efeb521..e7f01b5e1fb 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleMusic.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleMusic.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.io.BufferedInputStream; @@ -71,7 +72,8 @@ private void openAudioInputStream () throws UnsupportedAudioFileException, IOExc ain = AudioSystem.getAudioInputStream(decodedFormat, ain); } - @Override public void dispose () { + @Override + public void dispose () { disposed = true; try { thread.join(); @@ -82,31 +84,38 @@ private void openAudioInputStream () throws UnsupportedAudioFileException, IOExc } } - @Override public boolean isLooping () { + @Override + public boolean isLooping () { return looping.get(); } - @Override public boolean isPlaying () { + @Override + public boolean isPlaying () { return state.get() == Playing; } - @Override public void pause () { + @Override + public void pause () { state.compareAndSet(Playing, Paused); } - @Override public void play () { + @Override + public void play () { state.set(Playing); } - @Override public void stop () { + @Override + public void stop () { state.set(Stopped); } - @Override public void setLooping (boolean isLooping) { + @Override + public void setLooping (boolean isLooping) { looping.set(isLooping); } - @Override public void setVolume (float volume) { + @Override + public void setVolume (float volume) { try { volume = Math.min(1, volume); volume = Math.max(0, volume); @@ -117,7 +126,8 @@ private void openAudioInputStream () throws UnsupportedAudioFileException, IOExc } } - @Override public void run () { + @Override + public void run () { int readBytes = 0; long readSamples = 0; diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AnglePreferences.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AnglePreferences.java index d03b1226926..5b39b54dea8 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AnglePreferences.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AnglePreferences.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.io.BufferedInputStream; @@ -21,8 +22,8 @@ import java.io.OutputStream; import java.util.HashMap; import java.util.Map; -import java.util.Properties; import java.util.Map.Entry; +import java.util.Properties; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; @@ -31,134 +32,152 @@ public class AnglePreferences implements Preferences { private final String name; private final Properties properties = new Properties(); - AnglePreferences(String name) { + AnglePreferences (String name) { this.name = name; InputStream in = null; try { in = new BufferedInputStream(Gdx.files.external(name).read()); properties.loadFromXML(in); - } catch(Throwable t) { + } catch (Throwable t) { } finally { - if(in != null) try { in.close(); } catch(Exception e) { } + if (in != null) try { + in.close(); + } catch (Exception e) { + } } - + Runtime.getRuntime().addShutdownHook(new Thread() { - @Override public void run() { + @Override + public void run () { flush(); } }); - } - - @Override public void putBoolean (String key, boolean val) { + } + + @Override + public void putBoolean (String key, boolean val) { properties.put(key, Boolean.toString(val)); } - @Override public void putInteger (String key, int val) { + @Override + public void putInteger (String key, int val) { properties.put(key, Integer.toString(val)); } - @Override public void putLong (String key, long val) { + @Override + public void putLong (String key, long val) { properties.put(key, Long.toString(val)); } - @Override public void putFloat (String key, float val) { + @Override + public void putFloat (String key, float val) { properties.put(key, Float.toString(val)); } - @Override public void putString (String key, String val) { + @Override + public void putString (String key, String val) { properties.put(key, val); } - @Override public void put (Map vals) { - for(Entry val: vals.entrySet()) { - if(val.getValue() instanceof Boolean) - putBoolean(val.getKey(), (Boolean)val.getValue()); - if(val.getValue() instanceof Integer) - putInteger(val.getKey(), (Integer)val.getValue()); - if(val.getValue() instanceof Long) - putLong(val.getKey(), (Long)val.getValue()); - if(val.getValue() instanceof String) - putString(val.getKey(), (String)val.getValue()); - if(val.getValue() instanceof Float) - putFloat(val.getKey(), (Float)val.getValue()); + @Override + public void put (Map vals) { + for (Entry val : vals.entrySet()) { + if (val.getValue() instanceof Boolean) putBoolean(val.getKey(), (Boolean)val.getValue()); + if (val.getValue() instanceof Integer) putInteger(val.getKey(), (Integer)val.getValue()); + if (val.getValue() instanceof Long) putLong(val.getKey(), (Long)val.getValue()); + if (val.getValue() instanceof String) putString(val.getKey(), (String)val.getValue()); + if (val.getValue() instanceof Float) putFloat(val.getKey(), (Float)val.getValue()); } } - @Override public boolean getBoolean (String key) { + @Override + public boolean getBoolean (String key) { return getBoolean(key, false); } - @Override public int getInteger (String key) { + @Override + public int getInteger (String key) { return getInteger(key, 0); } - @Override public long getLong (String key) { + @Override + public long getLong (String key) { return getLong(key, 0); } - @Override public float getFloat (String key) { + @Override + public float getFloat (String key) { return getFloat(key, 0); } - @Override public String getString (String key) { + @Override + public String getString (String key) { return getString(key, ""); } - @Override public boolean getBoolean (String key, boolean defValue) { + @Override + public boolean getBoolean (String key, boolean defValue) { return Boolean.parseBoolean(properties.getProperty(key, Boolean.toString(defValue))); } - @Override public int getInteger (String key, int defValue) { + @Override + public int getInteger (String key, int defValue) { return Integer.parseInt(properties.getProperty(key, Integer.toString(defValue))); } - @Override public long getLong (String key, long defValue) { + @Override + public long getLong (String key, long defValue) { return Long.parseLong(properties.getProperty(key, Long.toString(defValue))); } - @Override public float getFloat (String key, float defValue) { + @Override + public float getFloat (String key, float defValue) { return Float.parseFloat(properties.getProperty(key, Float.toString(defValue))); } - @Override public String getString (String key, String defValue) { + @Override + public String getString (String key, String defValue) { return properties.getProperty(key, defValue); } - @Override public Map get () { + @Override + public Map get () { Map map = new HashMap(); - for(Entry val: properties.entrySet()) { - if(val.getValue() instanceof Boolean) - map.put((String)val.getKey(), (Boolean)Boolean.parseBoolean((String)val.getValue())); - if(val.getValue() instanceof Integer) - map.put((String)val.getKey(), (Integer)Integer.parseInt((String)val.getValue())); - if(val.getValue() instanceof Long) - map.put((String)val.getKey(), (Long)Long.parseLong((String)val.getValue())); - if(val.getValue() instanceof String) - map.put((String)val.getKey(), (String)val.getValue()); - if(val.getValue() instanceof Float) - map.put((String)val.getKey(), (Float)Float.parseFloat((String)val.getValue())); + for (Entry val : properties.entrySet()) { + if (val.getValue() instanceof Boolean) + map.put((String)val.getKey(), (Boolean)Boolean.parseBoolean((String)val.getValue())); + if (val.getValue() instanceof Integer) map.put((String)val.getKey(), (Integer)Integer.parseInt((String)val.getValue())); + if (val.getValue() instanceof Long) map.put((String)val.getKey(), (Long)Long.parseLong((String)val.getValue())); + if (val.getValue() instanceof String) map.put((String)val.getKey(), (String)val.getValue()); + if (val.getValue() instanceof Float) map.put((String)val.getKey(), (Float)Float.parseFloat((String)val.getValue())); } - + return map; } - @Override public boolean contains (String key) { + @Override + public boolean contains (String key) { return properties.containsKey(key); } - @Override public void clear () { + @Override + public void clear () { properties.clear(); } - - @Override public void flush() { + + @Override + public void flush () { OutputStream out = null; try { out = new BufferedOutputStream(Gdx.files.external(AnglePreferences.this.name).write(false)); properties.storeToXML(out, null); - } catch(Throwable t) { + } catch (Throwable t) { } finally { - if(out != null) try { out.close(); } catch(Exception e) { } + if (out != null) try { + out.close(); + } catch (Exception e) { + } } } } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleSound.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleSound.java index df2761d4a2e..dfedfaffc49 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleSound.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/AngleSound.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.angle; import java.io.BufferedInputStream; @@ -31,11 +32,8 @@ import com.badlogic.gdx.audio.Sound; -/** - * Implements the {@link Sound} interface for the desktop using {@link Clip}s internally. - * @author mzechner - * - */ +/** Implements the {@link Sound} interface for the desktop using {@link Clip}s internally. + * @author mzechner */ final class AngleSound implements Sound { /** the audio format **/ private final AudioFormat format; @@ -148,16 +146,12 @@ public void stop () { throw new UnsupportedOperationException("Upgrade Angle to OpenAL."); } - /** - * @return the {@link AudioFormat} of the audio data - */ + /** @return the {@link AudioFormat} of the audio data */ public AudioFormat getAudioFormat () { return format; } - /** - * @return the audio samples in form of a byte array - */ + /** @return the audio samples in form of a byte array */ public float[] getAudioData () { return samples; } diff --git a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/PNGDecoder.java b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/PNGDecoder.java index 4ec9b962539..2e4f8b64cda 100644 --- a/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/PNGDecoder.java +++ b/backends/gdx-backends-angle/src/com/badlogic/gdx/backends/angle/PNGDecoder.java @@ -32,12 +32,10 @@ import java.util.zip.DataFormatException; import java.util.zip.Inflater; -/** - * Decodes A PNG directly a ByteBuffer. +/** Decodes A PNG directly a ByteBuffer. * * @author Matthias Mann - * @author Nathan Sweet (minor edits to avoid allocation) - */ + * @author Nathan Sweet (minor edits to avoid allocation) */ final class PNGDecoder { public enum Format { ALPHA(1, true), LUMINANCE(1, false), LUMINANCE_ALPHA(2, true), RGB(3, false), RGBA(4, true), BGRA(4, true), ABGR(4, true); @@ -144,13 +142,11 @@ public boolean isRGB () { return colorType == COLOR_TRUEALPHA || colorType == COLOR_TRUECOLOR || colorType == COLOR_INDEXED; } - /** - * Computes the implemented format conversion for the desired format. + /** Computes the implemented format conversion for the desired format. * * @param fmt the desired format * @return format which best matches the desired format - * @throws UnsupportedOperationException if this PNG file can't be decoded - */ + * @throws UnsupportedOperationException if this PNG file can't be decoded */ public Format decideTextureFormat (Format fmt) { switch (colorType) { case COLOR_TRUECOLOR: diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GdxGwtTest.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GdxGwtTest.java index c5a995abbf9..84aaf19ffbd 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GdxGwtTest.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GdxGwtTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.gwt; import com.badlogic.gdx.ApplicationListener; @@ -6,40 +7,40 @@ public class GdxGwtTest extends GwtApplication implements ApplicationListener { @Override - public GwtApplicationConfiguration getConfig() { + public GwtApplicationConfiguration getConfig () { return new GwtApplicationConfiguration(500, 500); } @Override - public ApplicationListener getApplicationListener() { + public ApplicationListener getApplicationListener () { return this; } @Override - public void create() { + public void create () { } @Override - public void resume() { + public void resume () { } @Override - public void render() { + public void render () { Gdx.gl.glClearColor(1, (float)Math.random(), 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); - + Gdx.app.log("GdxGwtTest", "fps:" + Gdx.graphics.getFramesPerSecond() + ", " + Gdx.graphics.getDeltaTime()); } @Override - public void resize(int width, int height) { + public void resize (int width, int height) { } @Override - public void pause() { + public void pause () { } @Override - public void dispose() { + public void dispose () { } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplication.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplication.java index 191d450775c..75052a058d0 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplication.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplication.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.gwt; import gwt.g2d.client.util.FpsTimer; @@ -29,43 +30,43 @@ public abstract class GwtApplication implements EntryPoint, Application { private TextArea log = null; private int logLevel = LOG_ERROR; private List runnables = new ArrayList(); - + @Override - public void onModuleLoad() { + public void onModuleLoad () { this.listener = getApplicationListener(); this.config = getConfig(); - this.root = config.rootPanel != null? config.rootPanel: RootPanel.get(); + this.root = config.rootPanel != null ? config.rootPanel : RootPanel.get(); graphics = new GwtGraphics(root, config); - + Gdx.app = this; Gdx.graphics = graphics; Gdx.gl20 = graphics.getGL20(); Gdx.gl = graphics.getGLCommon(); - + setupLoop(); } - - private void setupLoop() { + + private void setupLoop () { // tell listener about app creation listener.create(); listener.resize(graphics.getWidth(), graphics.getHeight()); - + // add resize handler graphics.surface.addHandler(new ResizeHandler() { @Override - public void onResize(ResizeEvent event) { + public void onResize (ResizeEvent event) { GwtApplication.this.listener.resize(event.getWidth(), event.getHeight()); } }, ResizeEvent.getType()); - + // setup rendering timer FpsTimer timer = new FpsTimer(config.fps) { @Override - public void update() { + public void update () { graphics.setFps(this.getFps()); - - for(int i = 0; i < runnables.size(); i++) { + + for (int i = 0; i < runnables.size(); i++) { runnables.get(i).run(); } runnables.clear(); @@ -75,44 +76,45 @@ public void update() { timer.start(); } - public abstract GwtApplicationConfiguration getConfig(); - public abstract ApplicationListener getApplicationListener(); + public abstract GwtApplicationConfiguration getConfig (); + + public abstract ApplicationListener getApplicationListener (); @Override - public Graphics getGraphics() { + public Graphics getGraphics () { return graphics; } @Override - public Audio getAudio() { + public Audio getAudio () { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public Input getInput() { + public Input getInput () { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public Files getFiles() { + public Files getFiles () { // FIXME throw new GdxRuntimeException("not implemented"); } - private void checkLogLabel() { - if(log == null) { + private void checkLogLabel () { + if (log == null) { log = new TextArea(); log.setSize(graphics.getWidth() + "px", "150px"); log.setReadOnly(true); root.add(log); } } - + @Override - public void log(String tag, String message) { - if(logLevel >= LOG_INFO) { + public void log (String tag, String message) { + if (logLevel >= LOG_INFO) { checkLogLabel(); log.setText(log.getText() + "\n" + tag + ": " + message); log.setCursorPos(log.getText().length() - 1); @@ -120,17 +122,17 @@ public void log(String tag, String message) { } @Override - public void log(String tag, String message, Exception exception) { - if(logLevel >= LOG_INFO) { + public void log (String tag, String message, Exception exception) { + if (logLevel >= LOG_INFO) { checkLogLabel(); log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + exception.getMessage()); log.setCursorPos(log.getText().length() - 1); - } + } } @Override - public void error(String tag, String message) { - if(logLevel >= LOG_ERROR) { + public void error (String tag, String message) { + if (logLevel >= LOG_ERROR) { checkLogLabel(); log.setText(log.getText() + "\n" + tag + ": " + message); log.setCursorPos(log.getText().length() - 1); @@ -138,51 +140,51 @@ public void error(String tag, String message) { } @Override - public void error(String tag, String message, Exception exception) { - if(logLevel >= LOG_ERROR) { + public void error (String tag, String message, Exception exception) { + if (logLevel >= LOG_ERROR) { checkLogLabel(); log.setText(log.getText() + "\n" + tag + ": " + message + "\n" + exception.getMessage()); log.setCursorPos(log.getText().length() - 1); - } + } } @Override - public void setLogLevel(int logLevel) { + public void setLogLevel (int logLevel) { this.logLevel = logLevel; } @Override - public ApplicationType getType() { + public ApplicationType getType () { return ApplicationType.WebGL; } @Override - public int getVersion() { + public int getVersion () { return 0; } @Override - public long getJavaHeap() { + public long getJavaHeap () { return 0; } @Override - public long getNativeHeap() { + public long getNativeHeap () { return 0; } @Override - public Preferences getPreferences(String name) { + public Preferences getPreferences (String name) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void postRunnable(Runnable runnable) { + public void postRunnable (Runnable runnable) { runnables.add(runnable); } @Override - public void exit() { + public void exit () { } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplicationConfiguration.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplicationConfiguration.java index ed1915b6062..17334adf5a8 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplicationConfiguration.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtApplicationConfiguration.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.gwt; import com.google.gwt.user.client.ui.Panel; @@ -11,8 +12,8 @@ public class GwtApplicationConfiguration { public int fps = 60; public Panel rootPanel; public TextArea log; - - public GwtApplicationConfiguration(int width, int height) { + + public GwtApplicationConfiguration (int width, int height) { this.width = width; this.height = height; } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java index d44ddf72be7..27c20c6d9f6 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.gwt; import gwt.g3d.client.Surface3D; @@ -36,869 +37,849 @@ public class GwtGL20 implements GL20 { final Surface3D surface; final GL2 gl; - - protected GwtGL20(Surface3D surface) { + + protected GwtGL20 (Surface3D surface) { this.surface = surface; this.gl = surface.getGL(); } @Override - public void glActiveTexture(int texture) { + public void glActiveTexture (int texture) { gl.activeTexture(TextureUnit.parseTextureUnit(texture)); } @Override - public void glBindTexture(int target, int texture) { + public void glBindTexture (int target, int texture) { // FIXME throw new GdxRuntimeException("not implemented"); -// gl.bindTexture(TextureTarget.parseTextureTarget(target), ); +// gl.bindTexture(TextureTarget.parseTextureTarget(target), ); } @Override - public void glBlendFunc(int sfactor, int dfactor) { + public void glBlendFunc (int sfactor, int dfactor) { gl.blendFunc(BlendingFactorSrc.parseBlendingFactorSrc(sfactor), BlendingFactorDest.parseBlendingFactorDest(dfactor)); } @Override - public void glClear(int mask) { - if((mask & GL20.GL_COLOR_BUFFER_BIT) != 0 && (mask & GL20.GL_DEPTH_BUFFER_BIT) != 0 && (mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { + public void glClear (int mask) { + if ((mask & GL20.GL_COLOR_BUFFER_BIT) != 0 && (mask & GL20.GL_DEPTH_BUFFER_BIT) != 0 + && (mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { gl.clear(ClearBufferMask.COLOR_BUFFER_BIT, ClearBufferMask.DEPTH_BUFFER_BIT, ClearBufferMask.STENCIL_BUFFER_BIT); } - - if((mask & GL20.GL_COLOR_BUFFER_BIT) != 0 && (mask & GL20.GL_DEPTH_BUFFER_BIT) != 0) { + + if ((mask & GL20.GL_COLOR_BUFFER_BIT) != 0 && (mask & GL20.GL_DEPTH_BUFFER_BIT) != 0) { gl.clear(ClearBufferMask.COLOR_BUFFER_BIT, ClearBufferMask.DEPTH_BUFFER_BIT); } - - if((mask & GL20.GL_DEPTH_BUFFER_BIT) != 0 && (mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { + + if ((mask & GL20.GL_DEPTH_BUFFER_BIT) != 0 && (mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { gl.clear(ClearBufferMask.DEPTH_BUFFER_BIT, ClearBufferMask.STENCIL_BUFFER_BIT); } - - if((mask & GL20.GL_COLOR_BUFFER_BIT) != 0 && (mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { + + if ((mask & GL20.GL_COLOR_BUFFER_BIT) != 0 && (mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { gl.clear(ClearBufferMask.COLOR_BUFFER_BIT, ClearBufferMask.STENCIL_BUFFER_BIT); } - - if((mask & GL20.GL_COLOR_BUFFER_BIT) != 0) { + + if ((mask & GL20.GL_COLOR_BUFFER_BIT) != 0) { gl.clear(ClearBufferMask.COLOR_BUFFER_BIT); } - - if((mask & GL20.GL_DEPTH_BUFFER_BIT) != 0) { + + if ((mask & GL20.GL_DEPTH_BUFFER_BIT) != 0) { gl.clear(ClearBufferMask.DEPTH_BUFFER_BIT); } - - if((mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { + + if ((mask & GL20.GL_STENCIL_BUFFER_BIT) != 0) { gl.clear(ClearBufferMask.STENCIL_BUFFER_BIT); } } @Override - public void glClearColor(float red, float green, float blue, float alpha) { + public void glClearColor (float red, float green, float blue, float alpha) { gl.clearColor(red, green, blue, alpha); } @Override - public void glClearDepthf(float depth) { + public void glClearDepthf (float depth) { gl.clearDepth(depth); } @Override - public void glClearStencil(int s) { + public void glClearStencil (int s) { gl.clearStencil(s); } @Override - public void glColorMask(boolean red, boolean green, boolean blue, - boolean alpha) { + public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) { gl.colorMask(red, green, blue, alpha); } @Override - public void glCompressedTexImage2D(int target, int level, - int internalformat, int width, int height, int border, - int imageSize, Buffer data) { + public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border, + int imageSize, Buffer data) { throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend"); } @Override - public void glCompressedTexSubImage2D(int target, int level, int xoffset, - int yoffset, int width, int height, int format, int imageSize, - Buffer data) { - throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend"); + public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, + int imageSize, Buffer data) { + throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend"); } @Override - public void glCopyTexImage2D(int target, int level, int internalformat, - int x, int y, int width, int height, int border) { - gl.copyTexImage2D(TextureTarget.parseTextureTarget(target), level, PixelInternalFormat.parsePixelInternalFormat(internalformat), x, y, width, height, border); + public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border) { + gl.copyTexImage2D(TextureTarget.parseTextureTarget(target), level, + PixelInternalFormat.parsePixelInternalFormat(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) { + public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { gl.copyTexSubImage2D(TextureTarget.parseTextureTarget(target), level, xoffset, yoffset, x, y, width, height); } @Override - public void glCullFace(int mode) { + public void glCullFace (int mode) { gl.cullFace(CullFaceMode.parseCullFaceMode(mode)); } @Override - public void glDeleteTextures(int n, IntBuffer textures) { + public void glDeleteTextures (int n, IntBuffer textures) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glDepthFunc(int func) { + public void glDepthFunc (int func) { gl.depthFunc(DepthFunction.parseDepthFunction(func)); } @Override - public void glDepthMask(boolean flag) { + public void glDepthMask (boolean flag) { gl.depthMask(flag); } @Override - public void glDepthRangef(float zNear, float zFar) { + public void glDepthRangef (float zNear, float zFar) { gl.depthRange(zNear, zFar); } @Override - public void glDisable(int cap) { + public void glDisable (int cap) { gl.disable(EnableCap.parseEnableCap(cap)); } @Override - public void glDrawArrays(int mode, int first, int count) { + public void glDrawArrays (int mode, int first, int count) { gl.drawArrays(BeginMode.parseBeginMode(mode), first, count); } @Override - public void glDrawElements(int mode, int count, int type, Buffer indices) { + public void glDrawElements (int mode, int count, int type, Buffer indices) { // FIXME throw new GdxRuntimeException("not implemented"); -// gl.drawElements(BeginMode.parseBeginMode(mode), count, type, offset) +// gl.drawElements(BeginMode.parseBeginMode(mode), count, type, offset) } @Override - public void glEnable(int cap) { + public void glEnable (int cap) { gl.enable(EnableCap.parseEnableCap(cap)); } @Override - public void glFinish() { + public void glFinish () { gl.finish(); } @Override - public void glFlush() { + public void glFlush () { gl.flush(); } @Override - public void glFrontFace(int mode) { + public void glFrontFace (int mode) { gl.frontFace(FrontFaceDirection.parseFrontFaceDirection(mode)); } @Override - public void glGenTextures(int n, IntBuffer textures) { + public void glGenTextures (int n, IntBuffer textures) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public int glGetError() { + public int glGetError () { return gl.getError().getValue(); } @Override - public void glGetIntegerv(int pname, IntBuffer params) { + public void glGetIntegerv (int pname, IntBuffer params) { throw new GdxRuntimeException("glGetInteger not supported by GWT WebGL backend"); } @Override - public String glGetString(int name) { + public String glGetString (int name) { return gl.getString(StringName.parseStringName(name)); } @Override - public void glHint(int target, int mode) { + public void glHint (int target, int mode) { gl.hint(HintTarget.parseHintTarget(target), HintMode.parseHintMode(mode)); } @Override - public void glLineWidth(float width) { + public void glLineWidth (float width) { gl.lineWidth(width); } @Override - public void glPixelStorei(int pname, int param) { + public void glPixelStorei (int pname, int param) { gl.pixelStorei(PixelStoreParameter.parsePixelStoreParameter(pname), param); } @Override - public void glPolygonOffset(float factor, float units) { + public void glPolygonOffset (float factor, float units) { gl.polygonOffset(factor, units); } @Override - 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) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glScissor(int x, int y, int width, int height) { + public void glScissor (int x, int y, int width, int height) { gl.scissor(x, y, width, height); } @Override - public void glStencilFunc(int func, int ref, int mask) { + public void glStencilFunc (int func, int ref, int mask) { gl.stencilFunc(StencilFunction.parseStencilFunction(func), ref, mask); } @Override - public void glStencilMask(int mask) { + public void glStencilMask (int mask) { gl.stencilMask(mask); } @Override - public void glStencilOp(int fail, int zfail, int zpass) { + public void glStencilOp (int fail, int zfail, int zpass) { gl.stencilOp(StencilOp.parseStencilOp(fail), StencilOp.parseStencilOp(zfail), StencilOp.parseStencilOp(zpass)); } @Override - 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) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glTexParameterf(int target, int pname, float param) { + public void glTexParameterf (int target, int pname, float param) { gl.texParameterf(TextureTarget.parseTextureTarget(target), TextureParameterName.parseTextureParameterName(pname), param); } @Override - 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) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glViewport(int x, int y, int width, int height) { + public void glViewport (int x, int y, int width, int height) { gl.viewport(x, y, width, height); } @Override - public void glAttachShader(int program, int shader) { - // FIXME + public void glAttachShader (int program, int shader) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glBindAttribLocation(int program, int index, String name) { - // FIXME + public void glBindAttribLocation (int program, int index, String name) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glBindBuffer(int target, int buffer) { + public void glBindBuffer (int target, int buffer) { // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glBindFramebuffer(int target, int framebuffer) { - // FIXME + public void glBindFramebuffer (int target, int framebuffer) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glBindRenderbuffer(int target, int renderbuffer) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glBindRenderbuffer (int target, int renderbuffer) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glBlendColor(float red, float green, float blue, float alpha) { + public void glBlendColor (float red, float green, float blue, float alpha) { gl.blendColor(red, green, blue, alpha); } @Override - public void glBlendEquation(int mode) { + public void glBlendEquation (int mode) { gl.blendEquation(BlendEquationMode.parseBlendEquationMode(mode)); } @Override - public void glBlendEquationSeparate(int modeRGB, int modeAlpha) { - gl.blendEquationSeparate(BlendEquationMode.parseBlendEquationMode(modeRGB), BlendEquationMode.parseBlendEquationMode(modeAlpha)); + public void glBlendEquationSeparate (int modeRGB, int modeAlpha) { + gl.blendEquationSeparate(BlendEquationMode.parseBlendEquationMode(modeRGB), + BlendEquationMode.parseBlendEquationMode(modeAlpha)); } @Override - public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, - int dstAlpha) { - gl.blendFuncSeparate(BlendingFactorSrc.parseBlendingFactorSrc(srcRGB), - BlendingFactorDest.parseBlendingFactorDest(dstRGB), - BlendingFactorSrc.parseBlendingFactorSrc(srcAlpha), - BlendingFactorDest.parseBlendingFactorDest(dstAlpha)); + public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { + gl.blendFuncSeparate(BlendingFactorSrc.parseBlendingFactorSrc(srcRGB), BlendingFactorDest.parseBlendingFactorDest(dstRGB), + BlendingFactorSrc.parseBlendingFactorSrc(srcAlpha), BlendingFactorDest.parseBlendingFactorDest(dstAlpha)); } @Override - public void glBufferData(int target, int size, Buffer data, int usage) { - // FIXME + public void glBufferData (int target, int size, Buffer data, int usage) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glBufferSubData(int target, int offset, int size, Buffer data) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glBufferSubData (int target, int offset, int size, Buffer data) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public int glCheckFramebufferStatus(int target) { + public int glCheckFramebufferStatus (int target) { return gl.checkFramebufferStatus(FramebufferTarget.parseFramebufferTarget(target)).getValue(); } @Override - public void glCompileShader(int shader) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glCompileShader (int shader) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public int glCreateProgram() { - // FIXME + public int glCreateProgram () { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public int glCreateShader(int type) { - // FIXME + public int glCreateShader (int type) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glDeleteBuffers(int n, IntBuffer buffers) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glDeleteBuffers (int n, IntBuffer buffers) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glDeleteFramebuffers(int n, IntBuffer framebuffers) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glDeleteFramebuffers (int n, IntBuffer framebuffers) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glDeleteProgram(int program) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glDeleteProgram (int program) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glDeleteRenderbuffers(int n, IntBuffer renderbuffers) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glDeleteShader(int shader) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glDeleteShader (int shader) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glDetachShader(int program, int shader) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glDetachShader (int program, int shader) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glDisableVertexAttribArray(int index) { + public void glDisableVertexAttribArray (int index) { gl.disableVertexAttribArray(index); } @Override - public void glDrawElements(int mode, int count, int type, int indices) { + public void glDrawElements (int mode, int count, int type, int indices) { gl.drawElements(BeginMode.parseBeginMode(mode), count, DrawElementsType.parseDataType(type), indices); } @Override - public void glEnableVertexAttribArray(int index) { + public void glEnableVertexAttribArray (int index) { gl.enableVertexAttribArray(index); } @Override - public void glFramebufferRenderbuffer(int target, int attachment, - int renderbuffertarget, int renderbuffer) { - // FIXME + public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glFramebufferTexture2D(int target, int attachment, - int textarget, int texture, int level) { - // FIXME + public void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGenBuffers(int n, IntBuffer buffers) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glGenBuffers (int n, IntBuffer buffers) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glGenerateMipmap(int target) { + public void glGenerateMipmap (int target) { gl.generateMipmap(TextureTarget.parseTextureTarget(target)); } @Override - public void glGenFramebuffers(int n, IntBuffer framebuffers) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glGenFramebuffers (int n, IntBuffer framebuffers) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glGenRenderbuffers(int n, IntBuffer renderbuffers) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glGenRenderbuffers (int n, IntBuffer renderbuffers) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public String glGetActiveAttrib(int program, int index, IntBuffer size, - Buffer type) { - // FIXME + public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public String glGetActiveUniform(int program, int index, IntBuffer size, - Buffer type) { - // FIXME + public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetAttachedShaders(int program, int maxcount, Buffer count, - IntBuffer shaders) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public int glGetAttribLocation(int program, String name) { - // FIXME + public int glGetAttribLocation (int program, String name) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetBooleanv(int pname, Buffer params) { + public void glGetBooleanv (int pname, Buffer params) { throw new GdxRuntimeException("glGetBoolean not supported by GWT WebGL backend"); } @Override - public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { - // FIXME + public void glGetBufferParameteriv (int target, int pname, IntBuffer params) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetFloatv(int pname, FloatBuffer params) { + public void glGetFloatv (int pname, FloatBuffer params) { throw new GdxRuntimeException("glGetFloat not supported by GWT WebGL backend"); } @Override - public void glGetFramebufferAttachmentParameteriv(int target, - int attachment, int pname, IntBuffer params) { - // FIXME + public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetProgramiv(int program, int pname, IntBuffer params) { + public void glGetProgramiv (int program, int pname, IntBuffer params) { throw new GdxRuntimeException("glGetProgram not supported by GWT WebGL backend"); } @Override - public String glGetProgramInfoLog(int program) { - // FIXME + public String glGetProgramInfoLog (int program) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetRenderbufferParameteriv(int target, int pname, - IntBuffer params) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glGetShaderiv(int shader, int pname, IntBuffer params) { + public void glGetShaderiv (int shader, int pname, IntBuffer params) { throw new GdxRuntimeException("glGetShader not supported by GWT WebGL backend"); } @Override - public String glGetShaderInfoLog(int shader) { - // FIXME + public String glGetShaderInfoLog (int shader) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetShaderPrecisionFormat(int shadertype, int precisiontype, - IntBuffer range, IntBuffer precision) { + public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) { throw new GdxRuntimeException("glGetShaderPrecisionFormat not supported by GWT WebGL backend"); } @Override - public void glGetShaderSource(int shader, int bufsize, Buffer length, - String source) { + public void glGetShaderSource (int shader, int bufsize, Buffer length, String source) { throw new GdxRuntimeException("glGetShaderSource not supported by GWT WebGL backend"); } @Override - public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { + public void glGetTexParameterfv (int target, int pname, FloatBuffer params) { throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend"); } @Override - public void glGetTexParameteriv(int target, int pname, IntBuffer params) { + public void glGetTexParameteriv (int target, int pname, IntBuffer params) { throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend"); } @Override - public void glGetUniformfv(int program, int location, FloatBuffer params) { - // FIXME + public void glGetUniformfv (int program, int location, FloatBuffer params) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetUniformiv(int program, int location, IntBuffer params) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glGetUniformiv (int program, int location, IntBuffer params) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public int glGetUniformLocation(int program, String name) { - // FIXME + public int glGetUniformLocation (int program, String name) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetVertexAttribfv(int index, int pname, FloatBuffer params) { - // FIXME + public void glGetVertexAttribfv (int index, int pname, FloatBuffer params) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetVertexAttribiv(int index, int pname, IntBuffer params) { - // FIXME + public void glGetVertexAttribiv (int index, int pname, IntBuffer params) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glGetVertexAttribPointerv(int index, int pname, Buffer pointer) { + public void glGetVertexAttribPointerv (int index, int pname, Buffer pointer) { throw new GdxRuntimeException("glGetVertexAttribPointer not supported by GWT WebGL backend"); } @Override - public boolean glIsBuffer(int buffer) { - // FIXME + public boolean glIsBuffer (int buffer) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public boolean glIsEnabled(int cap) { + public boolean glIsEnabled (int cap) { return gl.isEnabled(EnableCap.parseEnableCap(cap)); } @Override - public boolean glIsFramebuffer(int framebuffer) { - // FIXME + public boolean glIsFramebuffer (int framebuffer) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public boolean glIsProgram(int program) { - // FIXME + public boolean glIsProgram (int program) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public boolean glIsRenderbuffer(int renderbuffer) { - // FIXME + public boolean glIsRenderbuffer (int renderbuffer) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public boolean glIsShader(int shader) { - // FIXME + public boolean glIsShader (int shader) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public boolean glIsTexture(int texture) { - // FIXME + public boolean glIsTexture (int texture) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glLinkProgram(int program) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glLinkProgram (int program) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glReleaseShaderCompiler() { + public void glReleaseShaderCompiler () { throw new GdxRuntimeException("glReleaseShaderCompiler not supported by GWT WebGL backend"); } @Override - public void glRenderbufferStorage(int target, int internalformat, - int width, int height) { - gl.renderbufferStorage(RenderbufferTarget.parseRenderbufferTarget(target), RenderbufferInternalFormat.parseRenderbufferInternalFormat(internalformat), width, height); + public void glRenderbufferStorage (int target, int internalformat, int width, int height) { + gl.renderbufferStorage(RenderbufferTarget.parseRenderbufferTarget(target), + RenderbufferInternalFormat.parseRenderbufferInternalFormat(internalformat), width, height); } @Override - public void glSampleCoverage(float value, boolean invert) { + public void glSampleCoverage (float value, boolean invert) { gl.sampleCoverage(value, invert); } @Override - 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) { throw new GdxRuntimeException("glShaderBinary not supported by GWT WebGL backend"); } @Override - public void glShaderSource(int shader, String string) { - // FIXME + public void glShaderSource (int shader, String string) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glStencilFuncSeparate(int face, int func, int ref, int mask) { + public void glStencilFuncSeparate (int face, int func, int ref, int mask) { gl.stencilFuncSeparate(CullFaceMode.parseCullFaceMode(face), StencilFunction.parseStencilFunction(func), ref, mask); } @Override - public void glStencilMaskSeparate(int face, int mask) { + public void glStencilMaskSeparate (int face, int mask) { gl.stencilMaskSeparate(CullFaceMode.parseCullFaceMode(face), mask); } @Override - public void glStencilOpSeparate(int face, int fail, int zfail, int zpass) { - gl.stencilOpSeparate(CullFaceMode.parseCullFaceMode(face), StencilOp.parseStencilOp(fail), StencilOp.parseStencilOp(zfail), StencilOp.parseStencilOp(zpass)); + public void glStencilOpSeparate (int face, int fail, int zfail, int zpass) { + gl.stencilOpSeparate(CullFaceMode.parseCullFaceMode(face), StencilOp.parseStencilOp(fail), StencilOp.parseStencilOp(zfail), + StencilOp.parseStencilOp(zpass)); } @Override - public void glTexParameterfv(int target, int pname, FloatBuffer params) { - gl.texParameterf(TextureTarget.parseTextureTarget(target), TextureParameterName.parseTextureParameterName(pname), params.get()); + public void glTexParameterfv (int target, int pname, FloatBuffer params) { + gl.texParameterf(TextureTarget.parseTextureTarget(target), TextureParameterName.parseTextureParameterName(pname), + params.get()); } @Override - public void glTexParameteri(int target, int pname, int param) { + public void glTexParameteri (int target, int pname, int param) { gl.texParameterf(TextureTarget.parseTextureTarget(target), TextureParameterName.parseTextureParameterName(pname), param); } @Override - public void glTexParameteriv(int target, int pname, IntBuffer params) { - gl.texParameterf(TextureTarget.parseTextureTarget(target), TextureParameterName.parseTextureParameterName(pname), params.get()); + public void glTexParameteriv (int target, int pname, IntBuffer params) { + gl.texParameterf(TextureTarget.parseTextureTarget(target), TextureParameterName.parseTextureParameterName(pname), + params.get()); } @Override - public void glUniform1f(int location, float x) { - // FIXME + public void glUniform1f (int location, float x) { + // FIXME throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform1fv(int location, int count, FloatBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform1fv (int location, int count, FloatBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform1i(int location, int x) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform1i (int location, int x) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform1iv(int location, int count, IntBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform1iv (int location, int count, IntBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform2f(int location, float x, float y) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform2f (int location, float x, float y) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform2fv(int location, int count, FloatBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform2fv (int location, int count, FloatBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform2i(int location, int x, int y) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform2i (int location, int x, int y) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform2iv(int location, int count, IntBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform2iv (int location, int count, IntBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform3f(int location, float x, float y, float z) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform3f (int location, float x, float y, float z) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform3fv(int location, int count, FloatBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform3fv (int location, int count, FloatBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform3i(int location, int x, int y, int z) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform3i (int location, int x, int y, int z) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform3iv(int location, int count, IntBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform3iv (int location, int count, IntBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform4f(int location, float x, float y, float z, float w) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform4f (int location, float x, float y, float z, float w) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform4fv(int location, int count, FloatBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform4fv (int location, int count, FloatBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform4i(int location, int x, int y, int z, int w) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform4i (int location, int x, int y, int z, int w) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniform4iv(int location, int count, IntBuffer v) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniform4iv (int location, int count, IntBuffer v) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniformMatrix2fv(int location, int count, boolean transpose, - FloatBuffer value) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniformMatrix3fv(int location, int count, boolean transpose, - FloatBuffer value) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUniformMatrix4fv(int location, int count, boolean transpose, - FloatBuffer value) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glUseProgram(int program) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glUseProgram (int program) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glValidateProgram(int program) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glValidateProgram (int program) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib1f(int indx, float x) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib1f (int indx, float x) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib1fv(int indx, FloatBuffer values) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib1fv (int indx, FloatBuffer values) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib2f(int indx, float x, float y) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib2f (int indx, float x, float y) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib2fv(int indx, FloatBuffer values) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib2fv (int indx, FloatBuffer values) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib3f(int indx, float x, float y, float z) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib3f (int indx, float x, float y, float z) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib3fv(int indx, FloatBuffer values) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib3fv (int indx, FloatBuffer values) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib4f(int indx, float x, float y, float z, float w) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib4f (int indx, float x, float y, float z, float w) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttrib4fv(int indx, FloatBuffer values) { - // FIXME - throw new GdxRuntimeException("not implemented"); + public void glVertexAttrib4fv (int indx, FloatBuffer values) { + // FIXME + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttribPointer(int indx, int size, int type, - boolean normalized, int stride, Buffer ptr) { - throw new GdxRuntimeException("not implemented"); + public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr) { + throw new GdxRuntimeException("not implemented"); } @Override - public void glVertexAttribPointer(int indx, int size, int type, - boolean normalized, int stride, int ptr) { - // FIXME + public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr) { + // FIXME throw new GdxRuntimeException("not implemented"); } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGraphics.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGraphics.java index 678dd71ad71..c44c0aa39a3 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGraphics.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGraphics.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.gwt; import gwt.g3d.client.Surface3D; @@ -22,163 +23,163 @@ public class GwtGraphics implements Graphics { float fps = 0; long lastTimeStamp = System.currentTimeMillis(); float deltaTime = 0; - - public GwtGraphics(Panel root, GwtApplicationConfiguration config) { + + public GwtGraphics (Panel root, GwtApplicationConfiguration config) { // create surface per configuration WebGLContextAttributes contextAttribs = new WebGLContextAttributes(); contextAttribs.setStencilEnable(config.stencil); contextAttribs.setAntialiasEnable(config.antialiasing); surface = new Surface3D(config.width, config.height, contextAttribs); root.add(surface); - + // check whether WebGL is supported GL2 gl = surface.getGL(); if (gl == null) { throw new GdxRuntimeException("WebGL not supported"); } - + this.gl = new GwtGL20(surface); - + // set initial viewport to cover entire surface and - gl.viewport(0, 0, surface.getWidth(), surface.getHeight()); + gl.viewport(0, 0, surface.getWidth(), surface.getHeight()); } - - public Surface3D getSurface() { + + public Surface3D getSurface () { return surface; } - + @Override - public boolean isGL11Available() { + public boolean isGL11Available () { return false; } @Override - public boolean isGL20Available() { + public boolean isGL20Available () { return true; } @Override - public GLCommon getGLCommon() { + public GLCommon getGLCommon () { return gl; } @Override - public GL10 getGL10() { + public GL10 getGL10 () { return null; } @Override - public GL11 getGL11() { + public GL11 getGL11 () { return null; } @Override - public GL20 getGL20() { + public GL20 getGL20 () { return gl; } @Override - public GLU getGLU() { + public GLU getGLU () { return null; } @Override - public int getWidth() { + public int getWidth () { return surface.getWidth(); } @Override - public int getHeight() { + public int getHeight () { return surface.getHeight(); } @Override - public float getDeltaTime() { + public float getDeltaTime () { return deltaTime; } @Override - public int getFramesPerSecond() { + public int getFramesPerSecond () { return (int)fps; } @Override - public GraphicsType getType() { + public GraphicsType getType () { return GraphicsType.WebGL; } @Override - public float getPpiX() { + public float getPpiX () { return 0; } @Override - public float getPpiY() { + public float getPpiY () { return 0; } @Override - public float getPpcX() { + public float getPpcX () { return 0; } @Override - public float getPpcY() { + public float getPpcY () { return 0; } @Override - public boolean supportsDisplayModeChange() { + public boolean supportsDisplayModeChange () { return false; } @Override - public DisplayMode[] getDisplayModes() { + public DisplayMode[] getDisplayModes () { return null; } @Override - public DisplayMode getDesktopDisplayMode() { + public DisplayMode getDesktopDisplayMode () { return null; } @Override - public boolean setDisplayMode(DisplayMode displayMode) { + public boolean setDisplayMode (DisplayMode displayMode) { return false; } @Override - public boolean setDisplayMode(int width, int height, boolean fullscreen) { + public boolean setDisplayMode (int width, int height, boolean fullscreen) { return false; } @Override - public void setTitle(String title) { - + public void setTitle (String title) { + } @Override - public void setIcon(Pixmap pixmap) { - + public void setIcon (Pixmap pixmap) { + } @Override - public void setVSync(boolean vsync) { - + public void setVSync (boolean vsync) { + } @Override - public BufferFormat getBufferFormat() { + public BufferFormat getBufferFormat () { return null; } @Override - public boolean supportsExtension(String extension) { - if(extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); + public boolean supportsExtension (String extension) { + if (extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS); return extensions.contains(extension); } - public void setFps(float fps) { + public void setFps (float fps) { long currTimeStamp = System.currentTimeMillis(); deltaTime = (currTimeStamp - lastTimeStamp) / 1000.0f; lastTimeStamp = currTimeStamp; @@ -186,7 +187,7 @@ public void setFps(float fps) { } @Override - public float getDensity() { + public float getDensity () { throw new GdxRuntimeException("No supported"); } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/PlainTest.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/PlainTest.java index 709900ce1a2..e1e4e9ff6d2 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/PlainTest.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/PlainTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.backends.gwt; import gwt.g2d.client.util.FpsTimer; @@ -6,14 +7,11 @@ import gwt.g3d.client.gl2.WebGLContextAttributes; import gwt.g3d.client.gl2.enums.ClearBufferMask; -import com.google.gwt.core.client.EntryPoint; -import com.google.gwt.user.client.ui.RootPanel; - public class PlainTest implements EntryPoint { private Surface3D surface; @Override - public void onModuleLoad() { + public void onModuleLoad () { // create surface per configuration WebGLContextAttributes contextAttribs = new WebGLContextAttributes(); surface = new Surface3D(500, 500, contextAttribs); @@ -30,11 +28,11 @@ public void onModuleLoad() { setupLoop(); } - private void setupLoop() { + private void setupLoop () { // setup rendering timer FpsTimer timer = new FpsTimer(60) { @Override - public void update() { + public void update () { GL2 gl = surface.getGL(); gl.clearColor((float)Math.random(), 0, 0, 1); gl.clear(ClearBufferMask.COLOR_BUFFER_BIT); diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/files/FileHandle.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/files/FileHandle.java index 928a8769acb..4e9c31e3729 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/files/FileHandle.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/files/FileHandle.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.files; public class FileHandle { diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Pixmap.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Pixmap.java index c8d2aca490d..14323af3b3f 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Pixmap.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Pixmap.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.utils.Disposable; @@ -5,6 +6,6 @@ public class Pixmap implements Disposable { @Override - public void dispose() { + public void dispose () { } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Texture.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Texture.java index 5196c465ddf..4a177928d2e 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Texture.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/Texture.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.utils.Disposable; @@ -5,6 +6,6 @@ public class Texture implements Disposable { @Override - public void dispose() { + public void dispose () { } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/utils/NumberUtils.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/utils/NumberUtils.java index 2c58fc8acaf..5682f430409 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/utils/NumberUtils.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/utils/NumberUtils.java @@ -1,27 +1,28 @@ + package com.badlogic.gdx.utils; import com.google.gwt.corp.compatibility.CompatibilityImpl; public class NumberUtils { static CompatibilityImpl impl = new CompatibilityImpl(); - - public static int floatToIntBits(float value) { + + public static int floatToIntBits (float value) { return impl.floatToIntBits(value); } - - public static int floatToRawIntBits(float value) { + + public static int floatToRawIntBits (float value) { return impl.floatToIntBits(value); } - - public static float intBitsToFloat(int value) { + + public static float intBitsToFloat (int value) { return impl.intBitsToFloat(value); } - - public static long doubleToLongBits(double value) { + + public static long doubleToLongBits (double value) { return 0; // FIXME } - - public static double longBitsToDouble(long value) { + + public static double longBitsToDouble (long value) { return 0; // FIXME } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Compatibility.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Compatibility.java index 656a6ba1f29..7a2312d38e8 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Compatibility.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Compatibility.java @@ -18,90 +18,96 @@ of the License, or (at your option) any later version. */ /* Modifications - Copyright 2003-2004 Bytonic Software - Copyright 2010 Google Inc. -*/ + Copyright 2003-2004 Bytonic Software + Copyright 2010 Google Inc. + */ + package com.google.gwt.corp.compatibility; import java.io.UnsupportedEncodingException; public class Compatibility { public interface Impl { - int floatToIntBits(float f); - float intBitsToFloat(int i); - String createString(byte[] b, int ofs, int length); - String getOriginatingServerAddress(); - void printStackTrace(Throwable e); - String createString(byte[] b, String encoding); - void sleep(int i); + int floatToIntBits (float f); + + float intBitsToFloat (int i); + + String createString (byte[] b, int ofs, int length); + + String getOriginatingServerAddress (); + + void printStackTrace (Throwable e); + + String createString (byte[] b, String encoding); + + void sleep (int i); } - + public static Impl impl; - - public static int floatToIntBits(float f) { + + public static int floatToIntBits (float f) { return impl.floatToIntBits(f); } - - public static float intBitsToFloat(int i) { + + public static float intBitsToFloat (int i) { return impl.intBitsToFloat(i); } - public static String newString(byte[] b) { + public static String newString (byte[] b) { return impl.createString(b, 0, b.length); } - - public static String newString(byte[] b, int s, int l) { + + public static String newString (byte[] b, int s, int l) { return impl.createString(b, s, l); } - - public static String newString(byte[] b, String encoding) throws UnsupportedEncodingException { + + public static String newString (byte[] b, String encoding) throws UnsupportedEncodingException { return impl.createString(b, encoding); } - - public static String getOriginatingServerAddress() { + + public static String getOriginatingServerAddress () { return impl.getOriginatingServerAddress(); } - public static void printStackTrace(Throwable e) { + public static void printStackTrace (Throwable e) { impl.printStackTrace(e); } - public static void sleep(int i) { - impl.sleep(i); + public static void sleep (int i) { + impl.sleep(i); } - public static String bytesToString(byte[] data, int len) { + public static String bytesToString (byte[] data, int len) { char[] chars = new char[len]; for (int i = 0; i < len; i++) { - chars[i] = (char) data[i]; + chars[i] = (char)data[i]; } return new String(chars); } - - public static int stringToBytes(String s, byte[] data) { + + public static int stringToBytes (String s, byte[] data) { int len = s.length(); for (int i = 0; i < len; i++) { - data[i] = (byte) s.charAt(i); + data[i] = (byte)s.charAt(i); } return len; } - - public static String bytesToHex(byte[] data, int len) { - char[] hex = new char[len * 2]; - for (int i = 0; i < len; i++) { - int di = data[i]; - hex[i << 1] = Character.forDigit((di >> 4) & 15, 16); - hex[(i << 1) + 1] = Character.forDigit(di & 15, 16); - } - return new String(hex); - } - - public static int hexToBytes(String hex, byte[] data) { - int len = hex.length(); - for (int i = 0; i < len; i +=2) { - data[i >> 1] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) | - Character.digit(hex.charAt(i + 1), 16)); - } - return len / 2; - } + + public static String bytesToHex (byte[] data, int len) { + char[] hex = new char[len * 2]; + for (int i = 0; i < len; i++) { + int di = data[i]; + hex[i << 1] = Character.forDigit((di >> 4) & 15, 16); + hex[(i << 1) + 1] = Character.forDigit(di & 15, 16); + } + return new String(hex); + } + + public static int hexToBytes (String hex, byte[] data) { + int len = hex.length(); + for (int i = 0; i < len; i += 2) { + data[i >> 1] = (byte)((Character.digit(hex.charAt(i), 16) << 4) | Character.digit(hex.charAt(i + 1), 16)); + } + return len / 2; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/CompatibilityImpl.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/CompatibilityImpl.java index e96640499bc..a99a0a30fa3 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/CompatibilityImpl.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/CompatibilityImpl.java @@ -15,67 +15,66 @@ of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package com.google.gwt.corp.compatibility; + */ +package com.google.gwt.corp.compatibility; public class CompatibilityImpl implements Compatibility.Impl { - public CompatibilityImpl() { + public CompatibilityImpl () { ConsolePrintStream cps; cps = new ConsolePrintStream(); System.setOut(cps); System.setErr(cps); - + System.out.println("Test for System.out.println()"); new Throwable("Exception test").printStackTrace(); System.out.println("Did the exception test appear above?"); - + } - - public int floatToIntBits(float f) { + + public int floatToIntBits (float f) { return Numbers.floatToIntBits(f); } - public float intBitsToFloat(int i) { + public float intBitsToFloat (int i) { return Numbers.intBitsToFloat(i); } - public String createString(byte[] b, int ofs, int length) { + public String createString (byte[] b, int ofs, int length) { StringBuffer sb = new StringBuffer(length); for (int i = 0; i < length; i++) { - sb.append((char) b[ofs + i]); + sb.append((char)b[ofs + i]); } return sb.toString(); } - - public String getOriginatingServerAddress() { -// String moduleUrl = GWT.getModuleBaseURL(); -// return getDomain(moduleUrl);// + ":" + getServerPort(); + public String getOriginatingServerAddress () { +// String moduleUrl = GWT.getModuleBaseURL(); +// return getDomain(moduleUrl);// + ":" + getServerPort(); return getServerAddress(); } - private static native String getServerAddress() /*-{ - if ($wnd.__serverAddress) { - return $wnd.__serverAddress; - } - return "127.0.0.1"; - }-*/; + private static native String getServerAddress () /*-{ + if ($wnd.__serverAddress) { + return $wnd.__serverAddress; + } + return "127.0.0.1"; + }-*/; - public void printStackTrace(Throwable e) { + public void printStackTrace (Throwable e) { System.out.println("" + e); - for (StackTraceElement ste : e.getStackTrace()) { - System.out.println(" at " + ste); - } + for (StackTraceElement ste : e.getStackTrace()) { + System.out.println(" at " + ste); + } } - public String createString(byte[] b, String encoding) { + public String createString (byte[] b, String encoding) { return createString(b, 0, b.length); } - public void sleep(int i) { + public void sleep (int i) { // TODO Auto-generated method stub - + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/ConsolePrintStream.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/ConsolePrintStream.java index eff8ba28762..8055a4d65d8 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/ConsolePrintStream.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/ConsolePrintStream.java @@ -13,60 +13,59 @@ * License for the specific language governing permissions and limitations under * the License. */ + package com.google.gwt.corp.compatibility; import java.io.OutputStream; import java.io.PrintStream; -/** - * Print stream for GWT that prints to the browser console. +/** Print stream for GWT that prints to the browser console. * - * @author Stefan Haustein - */ + * @author Stefan Haustein */ public class ConsolePrintStream extends PrintStream { - + StringBuilder buf = new StringBuilder(); - - public ConsolePrintStream() { - super((OutputStream) null); + + public ConsolePrintStream () { + super((OutputStream)null); } - - public void print(String s) { - - while(true) { + + public void print (String s) { + + while (true) { int cut = s.indexOf('\n'); - if(cut == -1) { + if (cut == -1) { break; } println(s.substring(0, cut)); s = s.substring(cut + 1); } - + buf.append(s); } - - public native void consoleLog(String msg) /*-{ - if (window.console) { - window.console.log(msg); - } else { - document.title = "LOG:" + msg; - } - }-*/; - public void print(char c) { + public native void consoleLog (String msg) /*-{ + if (window.console) { + window.console.log(msg); + } else { + document.title = "LOG:" + msg; + } + }-*/; + + public void print (char c) { if (c == '\n') { println(""); } else { buf.append(c); } } - - public void println() { + + public void println () { println(""); } - + @Override - public void println(String s) { + public void println (String s) { buf.append(s); consoleLog(buf.toString()); buf.setLength(0); diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Endianness.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Endianness.java index ed8d49ef770..d4a15894290 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Endianness.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Endianness.java @@ -18,5 +18,5 @@ package com.google.gwt.corp.compatibility; public enum Endianness { - BIG_ENDIAN, LITTLE_ENDIAN + BIG_ENDIAN, LITTLE_ENDIAN } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Numbers.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Numbers.java index ea63e7107c4..b9a6e89df91 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Numbers.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/Numbers.java @@ -13,6 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ + package com.google.gwt.corp.compatibility; import gwt.g3d.client.gl2.array.Float32Array; @@ -20,89 +21,87 @@ import gwt.g3d.client.gl2.array.Int8Array; public class Numbers { - - static final double LN2 = Math.log(2); - - public static final int floatToIntBits(float f) { - wfa.set(0, f); - return wia.get(0); - -// if (Float.isNaN(f)) { -// return 0x7f800001; -// } -// int signBit; -// if (f == 0) { -// return (1/f == Float.NEGATIVE_INFINITY) ? 0x80000000 : 0; -// } else if (f < 0) { -// f = -f; -// signBit = 0x80000000; -// } else { -// signBit = 0; -// } -// if (f == Float.POSITIVE_INFINITY) { -// return signBit | 0x7f800000; -// } -// -// int exponent = (int) (Math.log(f) / LN2); -// if (exponent < -126) { -// exponent = -126; -// } -// int significand = (int) (0.5 + f * Math.exp(-(exponent - 23) * LN2)); -// -// // Handle exponent rounding issues & denorm -// if ((significand & 0x01000000) != 0) { -// significand >>= 1; -// exponent++; -// } else if ((significand & 0x00800000) == 0) { -// if (exponent == -126) { -// return signBit | significand; -// } else { -// significand <<= 1; -// exponent--; -// } -// } -// -// return signBit | ((exponent + 127) << 23) | (significand & 0x007fffff); - } - - static Int8Array wba = Int8Array.create(4); - static Int32Array wia = Int32Array.create(wba.getBuffer(), 0, 1); - static Float32Array wfa = Float32Array.create(wba.getBuffer(), 0, 1); - - public static final float intBitsToFloat(int i) { -// wba.set(0, (byte) (i >> 24)); -// wba.set(1, (byte) (i >> 16)); -// wba.set(2, (byte) (i >> 8)); -// wba.set(3, (byte) (i)); - wia.set(0, i); - return wfa.get(0); -// -// -// int exponent = (i >>> 23) & 255; -// int significand = i & 0x007fffff; -// float result; -// if (exponent == 0) { -// result = (float) (Math.exp((-126 - 23) * LN2) * significand); -// } else if (exponent == 255) { -// result = significand == 0 ? Float.POSITIVE_INFINITY : Float.NaN; -// } else { -// result = (float) (Math.exp((exponent - 127 - 23) * LN2) * (0x00800000 | significand)); -// } -// -// return (i & 0x80000000) == 0 ? result : -result; - } - - public static final long doubleToLongBits(Double d) { - throw new RuntimeException("NYI"); - } - - public static final double longBitsToDouble(long l) { - throw new RuntimeException("NYI"); - } + static final double LN2 = Math.log(2); + + public static final int floatToIntBits (float f) { + wfa.set(0, f); + return wia.get(0); + +// if (Float.isNaN(f)) { +// return 0x7f800001; +// } +// int signBit; +// if (f == 0) { +// return (1/f == Float.NEGATIVE_INFINITY) ? 0x80000000 : 0; +// } else if (f < 0) { +// f = -f; +// signBit = 0x80000000; +// } else { +// signBit = 0; +// } +// if (f == Float.POSITIVE_INFINITY) { +// return signBit | 0x7f800000; +// } +// +// int exponent = (int) (Math.log(f) / LN2); +// if (exponent < -126) { +// exponent = -126; +// } +// int significand = (int) (0.5 + f * Math.exp(-(exponent - 23) * LN2)); +// +// // Handle exponent rounding issues & denorm +// if ((significand & 0x01000000) != 0) { +// significand >>= 1; +// exponent++; +// } else if ((significand & 0x00800000) == 0) { +// if (exponent == -126) { +// return signBit | significand; +// } else { +// significand <<= 1; +// exponent--; +// } +// } +// +// return signBit | ((exponent + 127) << 23) | (significand & 0x007fffff); + } + + static Int8Array wba = Int8Array.create(4); + static Int32Array wia = Int32Array.create(wba.getBuffer(), 0, 1); + static Float32Array wfa = Float32Array.create(wba.getBuffer(), 0, 1); + + public static final float intBitsToFloat (int i) { +// wba.set(0, (byte) (i >> 24)); +// wba.set(1, (byte) (i >> 16)); +// wba.set(2, (byte) (i >> 8)); +// wba.set(3, (byte) (i)); + wia.set(0, i); + return wfa.get(0); +// +// +// int exponent = (i >>> 23) & 255; +// int significand = i & 0x007fffff; +// float result; +// if (exponent == 0) { +// result = (float) (Math.exp((-126 - 23) * LN2) * significand); +// } else if (exponent == 255) { +// result = significand == 0 ? Float.POSITIVE_INFINITY : Float.NaN; +// } else { +// result = (float) (Math.exp((exponent - 127 - 23) * LN2) * (0x00800000 | significand)); +// } +// +// return (i & 0x80000000) == 0 ? result : -result; + } + + public static final long doubleToLongBits (Double d) { + throw new RuntimeException("NYI"); + } + public static final double longBitsToDouble (long l) { + throw new RuntimeException("NYI"); + } - public static long doubleToRawLongBits(double value) { - throw new RuntimeException("NYI: Numbers.doubleToRawLongBits"); - } + public static long doubleToRawLongBits (double value) { + throw new RuntimeException("NYI: Numbers.doubleToRawLongBits"); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/StringToByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/StringToByteBuffer.java index 81ba3d50754..7ecaec653d2 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/StringToByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/google/gwt/corp/compatibility/StringToByteBuffer.java @@ -18,9 +18,10 @@ of the License, or (at your option) any later version. */ /* Modifications - Copyright 2003-2004 Bytonic Software - Copyright 2010 Google Inc. -*/ + Copyright 2003-2004 Bytonic Software + Copyright 2010 Google Inc. + */ + package com.google.gwt.corp.compatibility; import java.nio.ByteBuffer; @@ -28,5 +29,5 @@ of the License, or (at your option) any later version. /** Ugly hack to get gwt internal stuff into nio, see StringByteBuffer in nio */ public interface StringToByteBuffer { - ByteBuffer stringToByteBuffer(String s); + ByteBuffer stringToByteBuffer (String s); } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BaseByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BaseByteBuffer.java index 3b120f73021..9c78c2a6d8c 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BaseByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BaseByteBuffer.java @@ -16,61 +16,56 @@ package java.nio; - -/** - * Serves as the root of other byte buffer impl classes, implements common - * methods that can be shared by child classes. - * - */ +/** Serves as the root of other byte buffer impl classes, implements common methods that can be shared by child classes. */ abstract class BaseByteBuffer extends ByteBuffer { - protected BaseByteBuffer(int capacity) { - super(capacity); - } + protected BaseByteBuffer (int capacity) { + super(capacity); + } + + @Override + public CharBuffer asCharBuffer () { + return CharToByteBufferAdapter.wrap(this); + } + + @Override + public DoubleBuffer asDoubleBuffer () { + return DoubleToByteBufferAdapter.wrap(this); + } + + @Override + public FloatBuffer asFloatBuffer () { + return FloatToByteBufferAdapter.wrap(this); + } + + @Override + public IntBuffer asIntBuffer () { + return IntToByteBufferAdapter.wrap(this); + } + + @Override + public LongBuffer asLongBuffer () { + return LongToByteBufferAdapter.wrap(this); + } + + @Override + public ShortBuffer asShortBuffer () { + return ShortToByteBufferAdapter.wrap(this); + } - @Override - public CharBuffer asCharBuffer() { - return CharToByteBufferAdapter.wrap(this); - } - - @Override - public DoubleBuffer asDoubleBuffer() { - return DoubleToByteBufferAdapter.wrap(this); - } - - @Override - public FloatBuffer asFloatBuffer() { - return FloatToByteBufferAdapter.wrap(this); - } - - @Override - public IntBuffer asIntBuffer() { - return IntToByteBufferAdapter.wrap(this); - } - - @Override - public LongBuffer asLongBuffer() { - return LongToByteBufferAdapter.wrap(this); - } - - @Override - public ShortBuffer asShortBuffer() { - return ShortToByteBufferAdapter.wrap(this); - } - - public final char getChar() { - return (char) getShort(); - } + public final char getChar () { + return (char)getShort(); + } - public final char getChar(int index) { - return (char) getShort(index); - } + public final char getChar (int index) { + return (char)getShort(index); + } - public final ByteBuffer putChar(char value) { - return putShort((short) value); - } + public final ByteBuffer putChar (char value) { + return putShort((short)value); + } - public final ByteBuffer putChar(int index, char value) { - return putShort(index, (short) value); - } + public final ByteBuffer putChar (int index, char value) { + return putShort(index, (short)value); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/Buffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/Buffer.java index 96b59e8387a..9e36157fa50 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/Buffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/Buffer.java @@ -16,285 +16,217 @@ package java.nio; - -/** - * A buffer is a list of elements of a specific primitive type. +/** A buffer is a list of elements of a specific primitive type. *

    * A buffer can be described by the following properties: *

      - *
    • Capacity: the number of elements a buffer can hold. Capacity may not be - * negative and never changes.
    • - *
    • Position: a cursor of this buffer. Elements are read or written at the - * position if you do not specify an index explicitly. Position may not be - * negative and not greater than the limit.
    • - *
    • Limit: controls the scope of accessible elements. You can only read or - * write elements from index zero to limit - 1. Accessing - * elements out of the scope will cause an exception. Limit may not be negative - * and not greater than capacity.
    • - *
    • Mark: used to remember the current position, so that you can reset the - * position later. Mark may not be negative and no greater than position.
    • - *
    • A buffer can be read-only or read-write. Trying to modify the elements - * of a read-only buffer will cause a ReadOnlyBufferException, - * while changing the position, limit and mark of a read-only buffer is OK.
    • - *
    • A buffer can be direct or indirect. A direct buffer will try its best to - * take advantage of native memory APIs and it may not stay in the Java heap, - * thus it is not affected by garbage collection.
    • + *
    • Capacity: the number of elements a buffer can hold. Capacity may not be negative and never changes.
    • + *
    • Position: a cursor of this buffer. Elements are read or written at the position if you do not specify an index explicitly. + * Position may not be negative and not greater than the limit.
    • + *
    • Limit: controls the scope of accessible elements. You can only read or write elements from index zero to + * limit - 1. Accessing elements out of the scope will cause an exception. Limit may not be negative and not greater + * than capacity.
    • + *
    • Mark: used to remember the current position, so that you can reset the position later. Mark may not be negative and no + * greater than position.
    • + *
    • A buffer can be read-only or read-write. Trying to modify the elements of a read-only buffer will cause a + * ReadOnlyBufferException, while changing the position, limit and mark of a read-only buffer is OK.
    • + *
    • A buffer can be direct or indirect. A direct buffer will try its best to take advantage of native memory APIs and it may + * not stay in the Java heap, thus it is not affected by garbage collection.
    • *
    *

    *

    - * Buffers are not thread-safe. If concurrent access to a buffer instance is - * required, then the callers are responsible to take care of the - * synchronization issues. + * Buffers are not thread-safe. If concurrent access to a buffer instance is required, then the callers are responsible to take + * care of the synchronization issues. *

    * - * @since Android 1.0 - */ + * @since Android 1.0 */ public abstract class Buffer { - /** - * UNSET_MARK means the mark has not been set. - */ - final static int UNSET_MARK = -1; - - /** - * The capacity of this buffer, which never change. - */ - final int capacity; - - /** - * limit - 1 is the last element that can be read or written. - * Limit must be no less than zero and no greater than capacity. - */ - int limit; - - /** - * Mark is where position will be set when reset() is called. - * Mark is not set by default. Mark is always no less than zero and no - * greater than position. - */ - int mark = UNSET_MARK; - - /** - * The current position of this buffer. Position is always no less than zero - * and no greater than limit. - */ - int position = 0; - - /** - * Construct a buffer with the specified capacity. - * - * @param capacity - * the capacity of this buffer. - */ - Buffer(int capacity) { - super(); - if (capacity < 0) { - throw new IllegalArgumentException(); - } - this.capacity = this.limit = capacity; - } - - /** - * Returns the capacity of this buffer. - * - * @return the number of elements that are contained in this buffer. - * @since Android 1.0 - */ - public final int capacity() { - return capacity; - } - - /** - * Clears this buffer. - *

    - * While the content of this buffer is not changed, the following internal - * changes take place: the current position is reset back to the start of - * the buffer, the value of the buffer limit is made equal to the capacity - * and mark is cleared. - *

    - * - * @return this buffer. - * @since Android 1.0 - */ - public final Buffer clear() { - position = 0; - mark = UNSET_MARK; - limit = capacity; - return this; - } - - /** - * Flips this buffer. - *

    - * The limit is set to the current position, then the position is set to - * zero, and the mark is cleared. - *

    - *

    - * The content of this buffer is not changed. - *

    - * - * @return this buffer. - * @since Android 1.0 - */ - public final Buffer flip() { - limit = position; - position = 0; - mark = UNSET_MARK; - return this; - } - - /** - * Indicates if there are elements remaining in this buffer, that is if - * {@code position < limit}. - * - * @return {@code true} if there are elements remaining in this buffer, - * {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasRemaining() { - return position < limit; - } - - /** - * Indicates whether this buffer is read-only. - * - * @return {@code true} if this buffer is read-only, {@code false} - * otherwise. - * @since Android 1.0 - */ - public abstract boolean isReadOnly(); - - /** - * Returns the limit of this buffer. - * - * @return the limit of this buffer. - * @since Android 1.0 - */ - public final int limit() { - return limit; - } - - /** - * Sets the limit of this buffer. - *

    - * If the current position in the buffer is in excess of - * newLimit then, on returning from this call, it will have - * been adjusted to be equivalent to newLimit. If the mark - * is set and is greater than the new limit, then it is cleared. - *

    - * - * @param newLimit - * the new limit, must not be negative and not greater than - * capacity. - * @return this buffer. - * @exception IllegalArgumentException - * if newLimit is invalid. - * @since Android 1.0 - */ - public final Buffer limit(int newLimit) { - if (newLimit < 0 || newLimit > capacity) { - throw new IllegalArgumentException(); - } - - limit = newLimit; - if (position > newLimit) { - position = newLimit; - } - if ((mark != UNSET_MARK) && (mark > newLimit)) { - mark = UNSET_MARK; - } - return this; - } - - /** - * Marks the current position, so that the position may return to this point - * later by calling reset(). - * - * @return this buffer. - * @since Android 1.0 - */ - public final Buffer mark() { - mark = position; - return this; - } - - /** - * Returns the position of this buffer. - * - * @return the value of this buffer's current position. - * @since Android 1.0 - */ - public final int position() { - return position; - } - - /** - * Sets the position of this buffer. - *

    - * If the mark is set and it is greater than the new position, then it is - * cleared. - *

    - * - * @param newPosition - * the new position, must be not negative and not greater than - * limit. - * @return this buffer. - * @exception IllegalArgumentException - * if newPosition is invalid. - * @since Android 1.0 - */ - public final Buffer position(int newPosition) { - if (newPosition < 0 || newPosition > limit) { - throw new IllegalArgumentException(); - } - - position = newPosition; - if ((mark != UNSET_MARK) && (mark > position)) { - mark = UNSET_MARK; - } - return this; - } - - /** - * Returns the number of remaining elements in this buffer, that is - * {@code limit - position}. - * - * @return the number of remaining elements in this buffer. - * @since Android 1.0 - */ - public final int remaining() { - return limit - position; - } - - /** - * Resets the position of this buffer to the mark. - * - * @return this buffer. - * @exception InvalidMarkException - * if the mark is not set. - * @since Android 1.0 - */ - public final Buffer reset() { - if (mark == UNSET_MARK) { - throw new InvalidMarkException(); - } - position = mark; - return this; - } - - /** - * Rewinds this buffer. - *

    - * The position is set to zero, and the mark is cleared. The content of this - * buffer is not changed. - *

    - * - * @return this buffer. - * @since Android 1.0 - */ - public final Buffer rewind() { - position = 0; - mark = UNSET_MARK; - return this; - } + /** UNSET_MARK means the mark has not been set. */ + final static int UNSET_MARK = -1; + + /** The capacity of this buffer, which never change. */ + final int capacity; + + /** limit - 1 is the last element that can be read or written. Limit must be no less than zero and no greater than + * capacity. */ + int limit; + + /** Mark is where position will be set when reset() is called. Mark is not set by default. Mark is always no less + * than zero and no greater than position. */ + int mark = UNSET_MARK; + + /** The current position of this buffer. Position is always no less than zero and no greater than limit. */ + int position = 0; + + /** Construct a buffer with the specified capacity. + * + * @param capacity the capacity of this buffer. */ + Buffer (int capacity) { + super(); + if (capacity < 0) { + throw new IllegalArgumentException(); + } + this.capacity = this.limit = capacity; + } + + /** Returns the capacity of this buffer. + * + * @return the number of elements that are contained in this buffer. + * @since Android 1.0 */ + public final int capacity () { + return capacity; + } + + /** Clears this buffer. + *

    + * While the content of this buffer is not changed, the following internal changes take place: the current position is reset + * back to the start of the buffer, the value of the buffer limit is made equal to the capacity and mark is cleared. + *

    + * + * @return this buffer. + * @since Android 1.0 */ + public final Buffer clear () { + position = 0; + mark = UNSET_MARK; + limit = capacity; + return this; + } + + /** Flips this buffer. + *

    + * The limit is set to the current position, then the position is set to zero, and the mark is cleared. + *

    + *

    + * The content of this buffer is not changed. + *

    + * + * @return this buffer. + * @since Android 1.0 */ + public final Buffer flip () { + limit = position; + position = 0; + mark = UNSET_MARK; + return this; + } + + /** Indicates if there are elements remaining in this buffer, that is if {@code position < limit}. + * + * @return {@code true} if there are elements remaining in this buffer, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasRemaining () { + return position < limit; + } + + /** Indicates whether this buffer is read-only. + * + * @return {@code true} if this buffer is read-only, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isReadOnly (); + + /** Returns the limit of this buffer. + * + * @return the limit of this buffer. + * @since Android 1.0 */ + public final int limit () { + return limit; + } + + /** Sets the limit of this buffer. + *

    + * If the current position in the buffer is in excess of newLimit then, on returning from this call, it will have + * been adjusted to be equivalent to newLimit. If the mark is set and is greater than the new limit, then it is + * cleared. + *

    + * + * @param newLimit the new limit, must not be negative and not greater than capacity. + * @return this buffer. + * @exception IllegalArgumentException if newLimit is invalid. + * @since Android 1.0 */ + public final Buffer limit (int newLimit) { + if (newLimit < 0 || newLimit > capacity) { + throw new IllegalArgumentException(); + } + + limit = newLimit; + if (position > newLimit) { + position = newLimit; + } + if ((mark != UNSET_MARK) && (mark > newLimit)) { + mark = UNSET_MARK; + } + return this; + } + + /** Marks the current position, so that the position may return to this point later by calling reset(). + * + * @return this buffer. + * @since Android 1.0 */ + public final Buffer mark () { + mark = position; + return this; + } + + /** Returns the position of this buffer. + * + * @return the value of this buffer's current position. + * @since Android 1.0 */ + public final int position () { + return position; + } + + /** Sets the position of this buffer. + *

    + * If the mark is set and it is greater than the new position, then it is cleared. + *

    + * + * @param newPosition the new position, must be not negative and not greater than limit. + * @return this buffer. + * @exception IllegalArgumentException if newPosition is invalid. + * @since Android 1.0 */ + public final Buffer position (int newPosition) { + if (newPosition < 0 || newPosition > limit) { + throw new IllegalArgumentException(); + } + + position = newPosition; + if ((mark != UNSET_MARK) && (mark > position)) { + mark = UNSET_MARK; + } + return this; + } + + /** Returns the number of remaining elements in this buffer, that is {@code limit - position}. + * + * @return the number of remaining elements in this buffer. + * @since Android 1.0 */ + public final int remaining () { + return limit - position; + } + + /** Resets the position of this buffer to the mark. + * + * @return this buffer. + * @exception InvalidMarkException if the mark is not set. + * @since Android 1.0 */ + public final Buffer reset () { + if (mark == UNSET_MARK) { + throw new InvalidMarkException(); + } + position = mark; + return this; + } + + /** Rewinds this buffer. + *

    + * The position is set to zero, and the mark is cleared. The content of this buffer is not changed. + *

    + * + * @return this buffer. + * @since Android 1.0 */ + public final Buffer rewind () { + position = 0; + mark = UNSET_MARK; + return this; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferFactory.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferFactory.java index 6db6c1ee80a..8f58ee96961 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferFactory.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferFactory.java @@ -17,192 +17,139 @@ package java.nio; - -/** - * Provide factory service of buffer classes. +/** Provide factory service of buffer classes. *

    - * Since all buffer impl classes are package private (except DirectByteBuffer), - * this factory is the only entrance to access buffer functions from outside of - * the impl package. - *

    - * - */ + * Since all buffer impl classes are package private (except DirectByteBuffer), this factory is the only entrance to access buffer + * functions from outside of the impl package. + *

    */ final class BufferFactory { - /** - * Returns a new byte buffer based on the specified byte array. - * - * @param array - * The byte array - * @return A new byte buffer based on the specified byte array. - */ - public static ByteBuffer newByteBuffer(byte array[]) { - return new ReadWriteHeapByteBuffer(array); - } - - /** - * Returns a new array based byte buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new array based byte buffer with the specified capacity. - */ - public static ByteBuffer newByteBuffer(int capacity) { - return new ReadWriteHeapByteBuffer(capacity); - } - - /** - * Returns a new char buffer based on the specified char array. - * - * @param array - * The char array - * @return A new char buffer based on the specified char array. - */ - public static CharBuffer newCharBuffer(char array[]) { - return new ReadWriteCharArrayBuffer(array); - } - - /** - * Returns a new readonly char buffer based on the specified char sequence. - * - * @param chseq - * The char sequence - * @return A new readonly char buffer based on the specified char sequence. - */ - public static CharBuffer newCharBuffer(CharSequence chseq) { - return new CharSequenceAdapter(chseq); - } - - /** - * Returns a new array based char buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new array based char buffer with the specified capacity. - */ - public static CharBuffer newCharBuffer(int capacity) { - return new ReadWriteCharArrayBuffer(capacity); - } - - /** - * Returns a new direct byte buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new direct byte buffer with the specified capacity. - */ - public static ByteBuffer newDirectByteBuffer(int capacity) { - return new DirectReadWriteByteBuffer(capacity); - } - - /** - * Returns a new double buffer based on the specified double array. - * - * @param array - * The double array - * @return A new double buffer based on the specified double array. - */ - public static DoubleBuffer newDoubleBuffer(double array[]) { - return new ReadWriteDoubleArrayBuffer(array); - } - - /** - * Returns a new array based double buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new array based double buffer with the specified capacity. - */ - public static DoubleBuffer newDoubleBuffer(int capacity) { - return new ReadWriteDoubleArrayBuffer(capacity); - } - - /** - * Returns a new float buffer based on the specified float array. - * - * @param array - * The float array - * @return A new float buffer based on the specified float array. - */ - public static FloatBuffer newFloatBuffer(float array[]) { - return new ReadWriteFloatArrayBuffer(array); - } - - /** - * Returns a new array based float buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new array based float buffer with the specified capacity. - */ - public static FloatBuffer newFloatBuffer(int capacity) { - return new ReadWriteFloatArrayBuffer(capacity); - } - - /** - * Returns a new array based int buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new array based int buffer with the specified capacity. - */ - public static IntBuffer newIntBuffer(int capacity) { - return new ReadWriteIntArrayBuffer(capacity); - } - - /** - * Returns a new int buffer based on the specified int array. - * - * @param array - * The int array - * @return A new int buffer based on the specified int array. - */ - public static IntBuffer newIntBuffer(int array[]) { - return new ReadWriteIntArrayBuffer(array); - } - - /** - * Returns a new array based long buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new array based long buffer with the specified capacity. - */ - public static LongBuffer newLongBuffer(int capacity) { - return new ReadWriteLongArrayBuffer(capacity); - } - - /** - * Returns a new long buffer based on the specified long array. - * - * @param array - * The long array - * @return A new long buffer based on the specified long array. - */ - public static LongBuffer newLongBuffer(long array[]) { - return new ReadWriteLongArrayBuffer(array); - } - - /** - * Returns a new array based short buffer with the specified capacity. - * - * @param capacity - * The capacity of the new buffer - * @return A new array based short buffer with the specified capacity. - */ - public static ShortBuffer newShortBuffer(int capacity) { - return new ReadWriteShortArrayBuffer(capacity); - } - - /** - * Returns a new short buffer based on the specified short array. - * - * @param array - * The short array - * @return A new short buffer based on the specified short array. - */ - public static ShortBuffer newShortBuffer(short array[]) { - return new ReadWriteShortArrayBuffer(array); - } + /** Returns a new byte buffer based on the specified byte array. + * + * @param array The byte array + * @return A new byte buffer based on the specified byte array. */ + public static ByteBuffer newByteBuffer (byte array[]) { + return new ReadWriteHeapByteBuffer(array); + } + + /** Returns a new array based byte buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new array based byte buffer with the specified capacity. */ + public static ByteBuffer newByteBuffer (int capacity) { + return new ReadWriteHeapByteBuffer(capacity); + } + + /** Returns a new char buffer based on the specified char array. + * + * @param array The char array + * @return A new char buffer based on the specified char array. */ + public static CharBuffer newCharBuffer (char array[]) { + return new ReadWriteCharArrayBuffer(array); + } + + /** Returns a new readonly char buffer based on the specified char sequence. + * + * @param chseq The char sequence + * @return A new readonly char buffer based on the specified char sequence. */ + public static CharBuffer newCharBuffer (CharSequence chseq) { + return new CharSequenceAdapter(chseq); + } + + /** Returns a new array based char buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new array based char buffer with the specified capacity. */ + public static CharBuffer newCharBuffer (int capacity) { + return new ReadWriteCharArrayBuffer(capacity); + } + + /** Returns a new direct byte buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new direct byte buffer with the specified capacity. */ + public static ByteBuffer newDirectByteBuffer (int capacity) { + return new DirectReadWriteByteBuffer(capacity); + } + + /** Returns a new double buffer based on the specified double array. + * + * @param array The double array + * @return A new double buffer based on the specified double array. */ + public static DoubleBuffer newDoubleBuffer (double array[]) { + return new ReadWriteDoubleArrayBuffer(array); + } + + /** Returns a new array based double buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new array based double buffer with the specified capacity. */ + public static DoubleBuffer newDoubleBuffer (int capacity) { + return new ReadWriteDoubleArrayBuffer(capacity); + } + + /** Returns a new float buffer based on the specified float array. + * + * @param array The float array + * @return A new float buffer based on the specified float array. */ + public static FloatBuffer newFloatBuffer (float array[]) { + return new ReadWriteFloatArrayBuffer(array); + } + + /** Returns a new array based float buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new array based float buffer with the specified capacity. */ + public static FloatBuffer newFloatBuffer (int capacity) { + return new ReadWriteFloatArrayBuffer(capacity); + } + + /** Returns a new array based int buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new array based int buffer with the specified capacity. */ + public static IntBuffer newIntBuffer (int capacity) { + return new ReadWriteIntArrayBuffer(capacity); + } + + /** Returns a new int buffer based on the specified int array. + * + * @param array The int array + * @return A new int buffer based on the specified int array. */ + public static IntBuffer newIntBuffer (int array[]) { + return new ReadWriteIntArrayBuffer(array); + } + + /** Returns a new array based long buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new array based long buffer with the specified capacity. */ + public static LongBuffer newLongBuffer (int capacity) { + return new ReadWriteLongArrayBuffer(capacity); + } + + /** Returns a new long buffer based on the specified long array. + * + * @param array The long array + * @return A new long buffer based on the specified long array. */ + public static LongBuffer newLongBuffer (long array[]) { + return new ReadWriteLongArrayBuffer(array); + } + + /** Returns a new array based short buffer with the specified capacity. + * + * @param capacity The capacity of the new buffer + * @return A new array based short buffer with the specified capacity. */ + public static ShortBuffer newShortBuffer (int capacity) { + return new ReadWriteShortArrayBuffer(capacity); + } + + /** Returns a new short buffer based on the specified short array. + * + * @param array The short array + * @return A new short buffer based on the specified short array. */ + public static ShortBuffer newShortBuffer (short array[]) { + return new ReadWriteShortArrayBuffer(array); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferOverflowException.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferOverflowException.java index a9ec60d6bc7..923808ec71c 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferOverflowException.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferOverflowException.java @@ -16,23 +16,18 @@ package java.nio; - -/** - * A BufferOverflowException is thrown when elements are written - * to a buffer but there is not enough remaining space in the buffer. +/** A BufferOverflowException is thrown when elements are written to a buffer but there is not enough remaining space + * in the buffer. * - * @since Android 1.0 - */ + * @since Android 1.0 */ public class BufferOverflowException extends RuntimeException { - private static final long serialVersionUID = -5484897634319144535L; + private static final long serialVersionUID = -5484897634319144535L; - /** - * Constructs a BufferOverflowException. - * - * @since Android 1.0 - */ - public BufferOverflowException() { - super(); - } + /** Constructs a BufferOverflowException. + * + * @since Android 1.0 */ + public BufferOverflowException () { + super(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferUnderflowException.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferUnderflowException.java index f15a8db0c72..1d3251ee340 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferUnderflowException.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/BufferUnderflowException.java @@ -16,23 +16,18 @@ package java.nio; - -/** - * A BufferUnderflowException is thrown when elements are read - * from a buffer but there are not enough remaining elements in the buffer. +/** A BufferUnderflowException is thrown when elements are read from a buffer but there are not enough remaining + * elements in the buffer. * - * @since Android 1.0 - */ + * @since Android 1.0 */ public class BufferUnderflowException extends RuntimeException { - private static final long serialVersionUID = -1713313658691622206L; + private static final long serialVersionUID = -1713313658691622206L; - /** - * Constructs a BufferUnderflowException. - * - * @since Android 1.0 - */ - public BufferUnderflowException() { - super(); - } + /** Constructs a BufferUnderflowException. + * + * @since Android 1.0 */ + public BufferUnderflowException () { + super(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBuffer.java index 81277ea0fd2..76a218d63ea 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBuffer.java @@ -20,1157 +20,818 @@ import com.google.gwt.corp.compatibility.Endianness; import com.google.gwt.corp.compatibility.StringToByteBuffer; - - -/** - * A buffer for bytes. +/** A buffer for bytes. *

    * A byte buffer can be created in either one of the following ways: *

    *
      - *
    • {@link #allocate(int) Allocate} a new byte array and create a buffer - * based on it;
    • - *
    • {@link #allocateDirect(int) Allocate} a memory block and create a direct - * buffer based on it;
    • - *
    • {@link #wrap(byte[]) Wrap} an existing byte array to create a new - * buffer.
    • + *
    • {@link #allocate(int) Allocate} a new byte array and create a buffer based on it;
    • + *
    • {@link #allocateDirect(int) Allocate} a memory block and create a direct buffer based on it;
    • + *
    • {@link #wrap(byte[]) Wrap} an existing byte array to create a new buffer.
    • *
    - * @since Android 1.0 - */ + * @since Android 1.0 */ public abstract class ByteBuffer extends Buffer implements Comparable, StringToByteBuffer { - - /** - * Creates a byte buffer based on a newly allocated byte array. - * - * @param capacity - * the capacity of the new buffer - * @return the created byte buffer. - * @throws IllegalArgumentException - * if {@code capacity < 0}. - * @since Android 1.0 - */ - public static ByteBuffer allocate(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newByteBuffer(capacity); - } - - /** - * Creates a direct byte buffer based on a newly allocated memory block. - * - * @param capacity - * the capacity of the new buffer - * @return the created byte buffer. - * @throws IllegalArgumentException - * if {@code capacity < 0}. - * @since Android 1.0 - */ - public static ByteBuffer allocateDirect(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newDirectByteBuffer(capacity); - } - - /** - * Creates a new byte buffer by wrapping the given byte array. - *

    - * Calling this method has the same effect as - * {@code wrap(array, 0, array.length)}. - *

    - * - * @param array - * the byte array which the new buffer will be based on - * @return the created byte buffer. - * @since Android 1.0 - */ - public static ByteBuffer wrap(byte[] array) { - return BufferFactory.newByteBuffer(array); - } - - /** - * Creates a new byte buffer by wrapping the given byte array. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code start + len}, capacity will be the length of the array. - *

    - * - * @param array - * the byte array which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code array.length}. - * @param len - * the length, must not be negative and not greater than - * {@code array.length - start}. - * @return the created byte buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code len} is invalid. - * @since Android 1.0 - */ - public static ByteBuffer wrap(byte[] array, int start, int len) { - int length = array.length; - if ((start < 0) || (len < 0) || ((long) start + (long) len > length)) { - throw new IndexOutOfBoundsException(); - } - - ByteBuffer buf = BufferFactory.newByteBuffer(array); - buf.position = start; - buf.limit = start + len; - - return buf; - } - - /** - * The byte order of this buffer, default is {@code BIG_ENDIAN}. - */ - Endianness order = Endianness.BIG_ENDIAN; - - /** - * Constructs a {@code ByteBuffer} with given capacity. - * - * @param capacity - * the capacity of the buffer. - */ - ByteBuffer(int capacity) { - super(capacity); - } - - /** - * Returns the byte array which this buffer is based on, if there is one. - * - * @return the byte array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on a read-only array. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final byte[] array() { - return protectedArray(); - } - - /** - * Returns the offset of the byte array which this buffer is based on, if - * there is one. - *

    - * The offset is the index of the array which corresponds to the zero - * position of the buffer. - *

    - * - * @return the offset of the byte array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on a read-only array. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int arrayOffset() { - return protectedArrayOffset(); - } - - - /** - * Returns a char buffer which is based on the remaining content of this - * byte buffer. - *

    - * The new buffer's position is zero, its limit and capacity is the number - * of remaining bytes divided by two, and its mark is not set. The new - * buffer's read-only property and byte order are the same as this buffer's. - * The new buffer is direct if this byte buffer is direct. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a char buffer which is based on the content of this byte buffer. - * @since Android 1.0 - */ - public abstract CharBuffer asCharBuffer(); - - /** - * Returns a double buffer which is based on the remaining content of this - * byte buffer. - *

    - * The new buffer's position is zero, its limit and capacity is the number - * of remaining bytes divided by eight, and its mark is not set. The new - * buffer's read-only property and byte order are the same as this buffer's. - * The new buffer is direct if this byte buffer is direct. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a double buffer which is based on the content of this byte - * buffer. - * @since Android 1.0 - */ - public abstract DoubleBuffer asDoubleBuffer(); - - /** - * Returns a float buffer which is based on the remaining content of this - * byte buffer. - *

    - * The new buffer's position is zero, its limit and capacity is the number - * of remaining bytes divided by four, and its mark is not set. The new - * buffer's read-only property and byte order are the same as this buffer's. - * The new buffer is direct if this byte buffer is direct. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a float buffer which is based on the content of this byte buffer. - * @since Android 1.0 - */ - public abstract FloatBuffer asFloatBuffer(); - - /** - * Returns a int buffer which is based on the remaining content of this byte - * buffer. - *

    - * The new buffer's position is zero, its limit and capacity is the number - * of remaining bytes divided by four, and its mark is not set. The new - * buffer's read-only property and byte order are the same as this buffer's. - * The new buffer is direct if this byte buffer is direct. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a int buffer which is based on the content of this byte buffer. - * @since Android 1.0 - */ - public abstract IntBuffer asIntBuffer(); - - /** - * Returns a long buffer which is based on the remaining content of this - * byte buffer. - *

    - * The new buffer's position is zero, its limit and capacity is the number - * of remaining bytes divided by eight, and its mark is not set. The new - * buffer's read-only property and byte order are the same as this buffer's. - * The new buffer is direct if this byte buffer is direct. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a long buffer which is based on the content of this byte buffer. - * @since Android 1.0 - */ - public abstract LongBuffer asLongBuffer(); - - /** - * Returns a read-only buffer that shares its content with this buffer. - *

    - * The returned buffer is guaranteed to be a new instance, even if this - * buffer is read-only itself. The new buffer's position, limit, capacity - * and mark are the same as this buffer. - *

    - *

    - * The new buffer shares its content with this buffer, which means this - * buffer's change of content will be visible to the new buffer. The two - * buffer's position, limit and mark are independent. - *

    - * - * @return a read-only version of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer asReadOnlyBuffer(); - - /** - * Returns a short buffer which is based on the remaining content of this - * byte buffer. - *

    - * The new buffer's position is zero, its limit and capacity is the number - * of remaining bytes divided by two, and its mark is not set. The new - * buffer's read-only property and byte order are the same as this buffer's. - * The new buffer is direct if this byte buffer is direct. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a short buffer which is based on the content of this byte buffer. - * @since Android 1.0 - */ - public abstract ShortBuffer asShortBuffer(); - - /** - * Compacts this byte buffer. - *

    - * The remaining bytes will be moved to the head of the - * buffer, starting from position zero. Then the position is set to - * {@code remaining()}; the limit is set to capacity; the mark is - * cleared. - *

    - * - * @return this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer compact(); - - /** - * Compares the remaining bytes of this buffer to another byte buffer's - * remaining bytes. - * - * @param otherBuffer - * another byte buffer. - * @return a negative value if this is less than {@code other}; 0 if this - * equals to {@code other}; a positive value if this is greater - * than {@code other}. - * @exception ClassCastException - * if {@code other} is not a byte buffer. - * @since Android 1.0 - */ - public int compareTo(ByteBuffer otherBuffer) { - int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() - : otherBuffer.remaining(); - int thisPos = position; - int otherPos = otherBuffer.position; - byte thisByte, otherByte; - while (compareRemaining > 0) { - thisByte = get(thisPos); - otherByte = otherBuffer.get(otherPos); - if (thisByte != otherByte) { - return thisByte < otherByte ? -1 : 1; - } - thisPos++; - otherPos++; - compareRemaining--; - } - return remaining() - otherBuffer.remaining(); - } - - /** - * Returns a duplicated buffer that shares its content with this buffer. - *

    - * The duplicated buffer's position, limit, capacity and mark are the same - * as this buffer's. The duplicated buffer's read-only property and byte - * order are the same as this buffer's too. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a duplicated buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer duplicate(); - - /** - * Checks whether this byte buffer is equal to another object. - *

    - * If {@code other} is not a byte buffer then {@code false} is returned. Two - * byte buffers are equal if and only if their remaining bytes are exactly - * the same. Position, limit, capacity and mark are not considered. - *

    - * - * @param other - * the object to compare with this byte buffer. - * @return {@code true} if this byte buffer is equal to {@code other}, - * {@code false} otherwise. - * @since Android 1.0 - */ - public boolean equals(Object other) { - if (!(other instanceof ByteBuffer)) { - return false; - } - ByteBuffer otherBuffer = (ByteBuffer) other; - - if (remaining() != otherBuffer.remaining()) { - return false; - } - - int myPosition = position; - int otherPosition = otherBuffer.position; - boolean equalSoFar = true; - while (equalSoFar && (myPosition < limit)) { - equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); - } - - return equalSoFar; - } - - /** - * Returns the byte at the current position and increases the position by 1. - * - * @return the byte at the current position. - * @exception BufferUnderflowException - * if the position is equal or greater than limit. - * @since Android 1.0 - */ - public abstract byte get(); - - /** - * Reads bytes from the current position into the specified byte array and - * increases the position by the number of bytes read. - *

    - * Calling this method has the same effect as - * {@code get(dest, 0, dest.length)}. - *

    - * - * @param dest - * the destination byte array. - * @return this buffer. - * @exception BufferUnderflowException - * if {@code dest.length} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public ByteBuffer get(byte[] dest) { - return get(dest, 0, dest.length); - } - - /** - * Reads bytes from the current position into the specified byte array, - * starting at the specified offset, and increases the position by the - * number of bytes read. - * - * @param dest - * the target byte array. - * @param off - * the offset of the byte array, must not be negative and - * not greater than {@code dest.length}. - * @param len - * the number of bytes to read, must not be negative and not - * greater than {@code dest.length - off} - * @return this buffer. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception BufferUnderflowException - * if {@code len} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public ByteBuffer get(byte[] dest, int off, int len) { - int length = dest.length; - if ((off < 0 ) || (len < 0) || ((long)off + (long)len > length)) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferUnderflowException(); - } - for (int i = off; i < off + len; i++) { - dest[i] = get(); - } - return this; - } - - /** - * Returns the byte at the specified index and does not change the position. - * - * @param index - * the index, must not be negative and less than limit. - * @return the byte at the specified index. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @since Android 1.0 - */ - public abstract byte get(int index); - - /** - * Returns the char at the current position and increases the position by 2. - *

    - * The 2 bytes starting at the current position are composed into a char - * according to the current byte order and returned. - *

    - * - * @return the char at the current position. - * @exception BufferUnderflowException - * if the position is greater than {@code limit - 2}. - * @since Android 1.0 - */ - public abstract char getChar(); - - /** - * Returns the char at the specified index. - *

    - * The 2 bytes starting from the specified index are composed into a char - * according to the current byte order and returned. The position is not - * changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 2}. - * @return the char at the specified index. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @since Android 1.0 - */ - public abstract char getChar(int index); - - /** - * Returns the double at the current position and increases the position by - * 8. - *

    - * The 8 bytes starting from the current position are composed into a double - * according to the current byte order and returned. - *

    - * - * @return the double at the current position. - * @exception BufferUnderflowException - * if the position is greater than {@code limit - 8}. - * @since Android 1.0 - */ - public abstract double getDouble(); - - /** - * Returns the double at the specified index. - *

    - * The 8 bytes starting at the specified index are composed into a double - * according to the current byte order and returned. The position is not - * changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 8}. - * @return the double at the specified index. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @since Android 1.0 - */ - public abstract double getDouble(int index); - - /** - * Returns the float at the current position and increases the position by - * 4. - *

    - * The 4 bytes starting at the current position are composed into a float - * according to the current byte order and returned. - *

    - * - * @return the float at the current position. - * @exception BufferUnderflowException - * if the position is greater than {@code limit - 4}. - * @since Android 1.0 - */ - public abstract float getFloat(); - - /** - * Returns the float at the specified index. - *

    - * The 4 bytes starting at the specified index are composed into a float - * according to the current byte order and returned. The position is not - * changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 4}. - * @return the float at the specified index. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @since Android 1.0 - */ - public abstract float getFloat(int index); - - /** - * Returns the int at the current position and increases the position by 4. - *

    - * The 4 bytes starting at the current position are composed into a int - * according to the current byte order and returned. - *

    - * - * @return the int at the current position. - * @exception BufferUnderflowException - * if the position is greater than {@code limit - 4}. - * @since Android 1.0 - */ - public abstract int getInt(); - - /** - * Returns the int at the specified index. - *

    - * The 4 bytes starting at the specified index are composed into a int - * according to the current byte order and returned. The position is not - * changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 4}. - * @return the int at the specified index. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @since Android 1.0 - */ - public abstract int getInt(int index); - - /** - * Returns the long at the current position and increases the position by 8. - *

    - * The 8 bytes starting at the current position are composed into a long - * according to the current byte order and returned. - *

    - * - * @return the long at the current position. - * @exception BufferUnderflowException - * if the position is greater than {@code limit - 8}. - * @since Android 1.0 - */ - public abstract long getLong(); - - /** - * Returns the long at the specified index. - *

    - * The 8 bytes starting at the specified index are composed into a long - * according to the current byte order and returned. The position is not - * changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 8}. - * @return the long at the specified index. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @since Android 1.0 - */ - public abstract long getLong(int index); - - /** - * Returns the short at the current position and increases the position by 2. - *

    - * The 2 bytes starting at the current position are composed into a short - * according to the current byte order and returned. - *

    - * - * @return the short at the current position. - * @exception BufferUnderflowException - * if the position is greater than {@code limit - 2}. - * @since Android 1.0 - */ - public abstract short getShort(); - - /** - * Returns the short at the specified index. - *

    - * The 2 bytes starting at the specified index are composed into a short - * according to the current byte order and returned. The position is not - * changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 2}. - * @return the short at the specified index. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @since Android 1.0 - */ - public abstract short getShort(int index); - - /** - * Indicates whether this buffer is based on a byte array and provides - * read/write access. - * - * @return {@code true} if this buffer is based on a byte array and provides - * read/write access, {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasArray() { - return protectedHasArray(); - } - - /** - * Calculates this buffer's hash code from the remaining chars. The - * position, limit, capacity and mark don't affect the hash code. - * - * @return the hash code calculated from the remaining bytes. - * @since Android 1.0 - */ - public int hashCode() { - int myPosition = position; - int hash = 0; - while (myPosition < limit) { - hash = hash + get(myPosition++); - } - return hash; - } - - /** - * Indicates whether this buffer is direct. - * - * @return {@code true} if this buffer is direct, {@code false} otherwise. - * @since Android 1.0 - */ - public abstract boolean isDirect(); - - /** - * Returns the byte order used by this buffer when converting bytes from/to - * other primitive types. - *

    - * The default byte order of byte buffer is always - * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN} - *

    - * - * @return the byte order used by this buffer when converting bytes from/to - * other primitive types. - * @since Android 1.0 - */ - public final ByteOrder order() { - return order == Endianness.BIG_ENDIAN ? ByteOrder.BIG_ENDIAN - : ByteOrder.LITTLE_ENDIAN; - } - - /** - * Sets the byte order of this buffer. - * - * @param byteOrder - * the byte order to set. If {@code null} then the order - * will be {@link ByteOrder#LITTLE_ENDIAN LITTLE_ENDIAN}. - * @return this buffer. - * @see ByteOrder - * @since Android 1.0 - */ - public final ByteBuffer order(ByteOrder byteOrder) { - return orderImpl(byteOrder); - } - - ByteBuffer orderImpl(ByteOrder byteOrder) { - order = byteOrder == ByteOrder.BIG_ENDIAN ? Endianness.BIG_ENDIAN - : Endianness.LITTLE_ENDIAN; - return this; - } - - /** - * Child class implements this method to realize {@code array()}. - * - * @see #array() - * @since Android 1.0 - */ - abstract byte[] protectedArray(); - - /** - * Child class implements this method to realize {@code arrayOffset()}. - * - * @see #arrayOffset() - * @since Android 1.0 - */ - abstract int protectedArrayOffset(); - - /** - * Child class implements this method to realize {@code hasArray()}. - * - * @see #hasArray() - * @since Android 1.0 - */ - abstract boolean protectedHasArray(); - - /** - * Writes the given byte to the current position and increases the position - * by 1. - * - * @param b - * the byte to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer put(byte b); - - /** - * Writes bytes in the given byte array to the current position and - * increases the position by the number of bytes written. - *

    - * Calling this method has the same effect as - * {@code put(src, 0, src.length)}. - *

    - * - * @param src - * the source byte array. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code src.length}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final ByteBuffer put(byte[] src) { - return put(src, 0, src.length); - } - - /** - * Writes bytes in the given byte array, starting from the specified offset, - * to the current position and increases the position by the number of bytes - * written. - * - * @param src - * the source byte array. - * @param off - * the offset of byte array, must not be negative and not greater - * than {@code src.length}. - * @param len - * the number of bytes to write, must not be negative and not - * greater than {@code src.length - off}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code len}. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public ByteBuffer put(byte[] src, int off, int len) { - int length = src.length; - if ((off < 0 ) || (len < 0) || ((long)off + (long)len > length)) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - for (int i = off; i < off + len; i++) { - put(src[i]); - } - return this; - } - - /** - * Writes all the remaining bytes of the {@code src} byte buffer to this - * buffer's current position, and increases both buffers' position by the - * number of bytes copied. - * - * @param src - * the source byte buffer. - * @return this buffer. - * @exception BufferOverflowException - * if {@code src.remaining()} is greater than this buffer's - * {@code remaining()}. - * @exception IllegalArgumentException - * if {@code src} is this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public ByteBuffer put(ByteBuffer src) { - if (src == this) { - throw new IllegalArgumentException(); - } - if (src.remaining() > remaining()) { - throw new BufferOverflowException(); - } - byte[] contents = new byte[src.remaining()]; - src.get(contents); - put(contents); - return this; - } - - /** - * Write a byte to the specified index of this buffer without changing the - * position. - * - * @param index - * the index, must not be negative and less than the limit. - * @param b - * the byte to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer put(int index, byte b); - - /** - * Writes the given char to the current position and increases the position - * by 2. - *

    - * The char is converted to bytes using the current byte order. - *

    - * - * @param value - * the char to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is greater than {@code limit - 2}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putChar(char value); - - /** - * Writes the given char to the specified index of this buffer. - *

    - * The char is converted to bytes using the current byte order. The position - * is not changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 2}. - * @param value - * the char to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putChar(int index, char value); - - /** - * Writes the given double to the current position and increases the position - * by 8. - *

    - * The double is converted to bytes using the current byte order. - *

    - * - * @param value - * the double to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is greater than {@code limit - 8}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putDouble(double value); - - /** - * Writes the given double to the specified index of this buffer. - *

    - * The double is converted to bytes using the current byte order. The - * position is not changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 8}. - * @param value - * the double to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putDouble(int index, double value); - - /** - * Writes the given float to the current position and increases the position - * by 4. - *

    - * The float is converted to bytes using the current byte order. - *

    - * - * @param value - * the float to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is greater than {@code limit - 4}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putFloat(float value); - - /** - * Writes the given float to the specified index of this buffer. - *

    - * The float is converted to bytes using the current byte order. The - * position is not changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 4}. - * @param value - * the float to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putFloat(int index, float value); - - /** - * Writes the given int to the current position and increases the position by - * 4. - *

    - * The int is converted to bytes using the current byte order. - *

    - * - * @param value - * the int to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is greater than {@code limit - 4}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putInt(int value); - - /** - * Writes the given int to the specified index of this buffer. - *

    - * The int is converted to bytes using the current byte order. The position - * is not changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 4}. - * @param value - * the int to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putInt(int index, int value); - - /** - * Writes the given long to the current position and increases the position - * by 8. - *

    - * The long is converted to bytes using the current byte order. - *

    - * - * @param value - * the long to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is greater than {@code limit - 8}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putLong(long value); - - /** - * Writes the given long to the specified index of this buffer. - *

    - * The long is converted to bytes using the current byte order. The position - * is not changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 8}. - * @param value - * the long to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putLong(int index, long value); - - /** - * Writes the given short to the current position and increases the position - * by 2. - *

    - * The short is converted to bytes using the current byte order. - *

    - * - * @param value - * the short to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is greater than {@code limit - 2}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putShort(short value); - - /** - * Writes the given short to the specified index of this buffer. - *

    - * The short is converted to bytes using the current byte order. The - * position is not changed. - *

    - * - * @param index - * the index, must not be negative and equal or less than - * {@code limit - 2}. - * @param value - * the short to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if {@code index} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer putShort(int index, short value); - - /** - * Returns a sliced buffer that shares its content with this buffer. - *

    - * The sliced buffer's capacity will be this buffer's - * {@code remaining()}, and it's zero position will correspond to - * this buffer's current position. The new buffer's position will be 0, - * limit will be its capacity, and its mark is cleared. The new buffer's - * read-only property and byte order are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a sliced buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract ByteBuffer slice(); - - /** - * Returns a string representing the state of this byte buffer. - * - * @return a string representing the state of this byte buffer. - * @since Android 1.0 - */ - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append(getClass().getName()); - buf.append(", status: capacity="); //$NON-NLS-1$ - buf.append(capacity()); - buf.append(" position="); //$NON-NLS-1$ - buf.append(position()); - buf.append(" limit="); //$NON-NLS-1$ - buf.append(limit()); - return buf.toString(); - } - - public ByteBuffer stringToByteBuffer(String s) { - return new StringByteBuffer(s); - } + /** Creates a byte buffer based on a newly allocated byte array. + * + * @param capacity the capacity of the new buffer + * @return the created byte buffer. + * @throws IllegalArgumentException if {@code capacity < 0}. + * @since Android 1.0 */ + public static ByteBuffer allocate (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newByteBuffer(capacity); + } + + /** Creates a direct byte buffer based on a newly allocated memory block. + * + * @param capacity the capacity of the new buffer + * @return the created byte buffer. + * @throws IllegalArgumentException if {@code capacity < 0}. + * @since Android 1.0 */ + public static ByteBuffer allocateDirect (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newDirectByteBuffer(capacity); + } + + /** Creates a new byte buffer by wrapping the given byte array. + *

    + * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. + *

    + * + * @param array the byte array which the new buffer will be based on + * @return the created byte buffer. + * @since Android 1.0 */ + public static ByteBuffer wrap (byte[] array) { + return BufferFactory.newByteBuffer(array); + } + + /** Creates a new byte buffer by wrapping the given byte array. + *

    + * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the + * array. + *

    + * + * @param array the byte array which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code array.length}. + * @param len the length, must not be negative and not greater than {@code array.length - start}. + * @return the created byte buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. + * @since Android 1.0 */ + public static ByteBuffer wrap (byte[] array, int start, int len) { + int length = array.length; + if ((start < 0) || (len < 0) || ((long)start + (long)len > length)) { + throw new IndexOutOfBoundsException(); + } + + ByteBuffer buf = BufferFactory.newByteBuffer(array); + buf.position = start; + buf.limit = start + len; + + return buf; + } + + /** The byte order of this buffer, default is {@code BIG_ENDIAN}. */ + Endianness order = Endianness.BIG_ENDIAN; + + /** Constructs a {@code ByteBuffer} with given capacity. + * + * @param capacity the capacity of the buffer. */ + ByteBuffer (int capacity) { + super(capacity); + } + + /** Returns the byte array which this buffer is based on, if there is one. + * + * @return the byte array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on a read-only array. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final byte[] array () { + return protectedArray(); + } + + /** Returns the offset of the byte array which this buffer is based on, if there is one. + *

    + * The offset is the index of the array which corresponds to the zero position of the buffer. + *

    + * + * @return the offset of the byte array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on a read-only array. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int arrayOffset () { + return protectedArrayOffset(); + } + + /** Returns a char buffer which is based on the remaining content of this byte buffer. + *

    + * The new buffer's position is zero, its limit and capacity is the number of remaining bytes divided by two, and its mark is + * not set. The new buffer's read-only property and byte order are the same as this buffer's. The new buffer is direct if this + * byte buffer is direct. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a char buffer which is based on the content of this byte buffer. + * @since Android 1.0 */ + public abstract CharBuffer asCharBuffer (); + + /** Returns a double buffer which is based on the remaining content of this byte buffer. + *

    + * The new buffer's position is zero, its limit and capacity is the number of remaining bytes divided by eight, and its mark is + * not set. The new buffer's read-only property and byte order are the same as this buffer's. The new buffer is direct if this + * byte buffer is direct. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a double buffer which is based on the content of this byte buffer. + * @since Android 1.0 */ + public abstract DoubleBuffer asDoubleBuffer (); + + /** Returns a float buffer which is based on the remaining content of this byte buffer. + *

    + * The new buffer's position is zero, its limit and capacity is the number of remaining bytes divided by four, and its mark is + * not set. The new buffer's read-only property and byte order are the same as this buffer's. The new buffer is direct if this + * byte buffer is direct. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a float buffer which is based on the content of this byte buffer. + * @since Android 1.0 */ + public abstract FloatBuffer asFloatBuffer (); + + /** Returns a int buffer which is based on the remaining content of this byte buffer. + *

    + * The new buffer's position is zero, its limit and capacity is the number of remaining bytes divided by four, and its mark is + * not set. The new buffer's read-only property and byte order are the same as this buffer's. The new buffer is direct if this + * byte buffer is direct. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a int buffer which is based on the content of this byte buffer. + * @since Android 1.0 */ + public abstract IntBuffer asIntBuffer (); + + /** Returns a long buffer which is based on the remaining content of this byte buffer. + *

    + * The new buffer's position is zero, its limit and capacity is the number of remaining bytes divided by eight, and its mark is + * not set. The new buffer's read-only property and byte order are the same as this buffer's. The new buffer is direct if this + * byte buffer is direct. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a long buffer which is based on the content of this byte buffer. + * @since Android 1.0 */ + public abstract LongBuffer asLongBuffer (); + + /** Returns a read-only buffer that shares its content with this buffer. + *

    + * The returned buffer is guaranteed to be a new instance, even if this buffer is read-only itself. The new buffer's position, + * limit, capacity and mark are the same as this buffer. + *

    + *

    + * The new buffer shares its content with this buffer, which means this buffer's change of content will be visible to the new + * buffer. The two buffer's position, limit and mark are independent. + *

    + * + * @return a read-only version of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer asReadOnlyBuffer (); + + /** Returns a short buffer which is based on the remaining content of this byte buffer. + *

    + * The new buffer's position is zero, its limit and capacity is the number of remaining bytes divided by two, and its mark is + * not set. The new buffer's read-only property and byte order are the same as this buffer's. The new buffer is direct if this + * byte buffer is direct. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a short buffer which is based on the content of this byte buffer. + * @since Android 1.0 */ + public abstract ShortBuffer asShortBuffer (); + + /** Compacts this byte buffer. + *

    + * The remaining bytes will be moved to the head of the buffer, starting from position zero. Then the position is set to + * {@code remaining()}; the limit is set to capacity; the mark is cleared. + *

    + * + * @return this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer compact (); + + /** Compares the remaining bytes of this buffer to another byte buffer's remaining bytes. + * + * @param otherBuffer another byte buffer. + * @return a negative value if this is less than {@code other}; 0 if this equals to {@code other}; a positive value if this is + * greater than {@code other}. + * @exception ClassCastException if {@code other} is not a byte buffer. + * @since Android 1.0 */ + public int compareTo (ByteBuffer otherBuffer) { + int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); + int thisPos = position; + int otherPos = otherBuffer.position; + byte thisByte, otherByte; + while (compareRemaining > 0) { + thisByte = get(thisPos); + otherByte = otherBuffer.get(otherPos); + if (thisByte != otherByte) { + return thisByte < otherByte ? -1 : 1; + } + thisPos++; + otherPos++; + compareRemaining--; + } + return remaining() - otherBuffer.remaining(); + } + + /** Returns a duplicated buffer that shares its content with this buffer. + *

    + * The duplicated buffer's position, limit, capacity and mark are the same as this buffer's. The duplicated buffer's read-only + * property and byte order are the same as this buffer's too. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a duplicated buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer duplicate (); + + /** Checks whether this byte buffer is equal to another object. + *

    + * If {@code other} is not a byte buffer then {@code false} is returned. Two byte buffers are equal if and only if their + * remaining bytes are exactly the same. Position, limit, capacity and mark are not considered. + *

    + * + * @param other the object to compare with this byte buffer. + * @return {@code true} if this byte buffer is equal to {@code other}, {@code false} otherwise. + * @since Android 1.0 */ + public boolean equals (Object other) { + if (!(other instanceof ByteBuffer)) { + return false; + } + ByteBuffer otherBuffer = (ByteBuffer)other; + + if (remaining() != otherBuffer.remaining()) { + return false; + } + + int myPosition = position; + int otherPosition = otherBuffer.position; + boolean equalSoFar = true; + while (equalSoFar && (myPosition < limit)) { + equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); + } + + return equalSoFar; + } + + /** Returns the byte at the current position and increases the position by 1. + * + * @return the byte at the current position. + * @exception BufferUnderflowException if the position is equal or greater than limit. + * @since Android 1.0 */ + public abstract byte get (); + + /** Reads bytes from the current position into the specified byte array and increases the position by the number of bytes read. + *

    + * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. + *

    + * + * @param dest the destination byte array. + * @return this buffer. + * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. + * @since Android 1.0 */ + public ByteBuffer get (byte[] dest) { + return get(dest, 0, dest.length); + } + + /** Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the + * position by the number of bytes read. + * + * @param dest the target byte array. + * @param off the offset of the byte array, must not be negative and not greater than {@code dest.length}. + * @param len the number of bytes to read, must not be negative and not greater than {@code dest.length - off} + * @return this buffer. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. + * @since Android 1.0 */ + public ByteBuffer get (byte[] dest, int off, int len) { + int length = dest.length; + if ((off < 0) || (len < 0) || ((long)off + (long)len > length)) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferUnderflowException(); + } + for (int i = off; i < off + len; i++) { + dest[i] = get(); + } + return this; + } + + /** Returns the byte at the specified index and does not change the position. + * + * @param index the index, must not be negative and less than limit. + * @return the byte at the specified index. + * @exception IndexOutOfBoundsException if index is invalid. + * @since Android 1.0 */ + public abstract byte get (int index); + + /** Returns the char at the current position and increases the position by 2. + *

    + * The 2 bytes starting at the current position are composed into a char according to the current byte order and returned. + *

    + * + * @return the char at the current position. + * @exception BufferUnderflowException if the position is greater than {@code limit - 2}. + * @since Android 1.0 */ + public abstract char getChar (); + + /** Returns the char at the specified index. + *

    + * The 2 bytes starting from the specified index are composed into a char according to the current byte order and returned. The + * position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 2}. + * @return the char at the specified index. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @since Android 1.0 */ + public abstract char getChar (int index); + + /** Returns the double at the current position and increases the position by 8. + *

    + * The 8 bytes starting from the current position are composed into a double according to the current byte order and returned. + *

    + * + * @return the double at the current position. + * @exception BufferUnderflowException if the position is greater than {@code limit - 8}. + * @since Android 1.0 */ + public abstract double getDouble (); + + /** Returns the double at the specified index. + *

    + * The 8 bytes starting at the specified index are composed into a double according to the current byte order and returned. The + * position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 8}. + * @return the double at the specified index. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @since Android 1.0 */ + public abstract double getDouble (int index); + + /** Returns the float at the current position and increases the position by 4. + *

    + * The 4 bytes starting at the current position are composed into a float according to the current byte order and returned. + *

    + * + * @return the float at the current position. + * @exception BufferUnderflowException if the position is greater than {@code limit - 4}. + * @since Android 1.0 */ + public abstract float getFloat (); + + /** Returns the float at the specified index. + *

    + * The 4 bytes starting at the specified index are composed into a float according to the current byte order and returned. The + * position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 4}. + * @return the float at the specified index. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @since Android 1.0 */ + public abstract float getFloat (int index); + + /** Returns the int at the current position and increases the position by 4. + *

    + * The 4 bytes starting at the current position are composed into a int according to the current byte order and returned. + *

    + * + * @return the int at the current position. + * @exception BufferUnderflowException if the position is greater than {@code limit - 4}. + * @since Android 1.0 */ + public abstract int getInt (); + + /** Returns the int at the specified index. + *

    + * The 4 bytes starting at the specified index are composed into a int according to the current byte order and returned. The + * position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 4}. + * @return the int at the specified index. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @since Android 1.0 */ + public abstract int getInt (int index); + + /** Returns the long at the current position and increases the position by 8. + *

    + * The 8 bytes starting at the current position are composed into a long according to the current byte order and returned. + *

    + * + * @return the long at the current position. + * @exception BufferUnderflowException if the position is greater than {@code limit - 8}. + * @since Android 1.0 */ + public abstract long getLong (); + + /** Returns the long at the specified index. + *

    + * The 8 bytes starting at the specified index are composed into a long according to the current byte order and returned. The + * position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 8}. + * @return the long at the specified index. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @since Android 1.0 */ + public abstract long getLong (int index); + + /** Returns the short at the current position and increases the position by 2. + *

    + * The 2 bytes starting at the current position are composed into a short according to the current byte order and returned. + *

    + * + * @return the short at the current position. + * @exception BufferUnderflowException if the position is greater than {@code limit - 2}. + * @since Android 1.0 */ + public abstract short getShort (); + + /** Returns the short at the specified index. + *

    + * The 2 bytes starting at the specified index are composed into a short according to the current byte order and returned. The + * position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 2}. + * @return the short at the specified index. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @since Android 1.0 */ + public abstract short getShort (int index); + + /** Indicates whether this buffer is based on a byte array and provides read/write access. + * + * @return {@code true} if this buffer is based on a byte array and provides read/write access, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasArray () { + return protectedHasArray(); + } + + /** Calculates this buffer's hash code from the remaining chars. The position, limit, capacity and mark don't affect the hash + * code. + * + * @return the hash code calculated from the remaining bytes. + * @since Android 1.0 */ + public int hashCode () { + int myPosition = position; + int hash = 0; + while (myPosition < limit) { + hash = hash + get(myPosition++); + } + return hash; + } + + /** Indicates whether this buffer is direct. + * + * @return {@code true} if this buffer is direct, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isDirect (); + + /** Returns the byte order used by this buffer when converting bytes from/to other primitive types. + *

    + * The default byte order of byte buffer is always {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN} + *

    + * + * @return the byte order used by this buffer when converting bytes from/to other primitive types. + * @since Android 1.0 */ + public final ByteOrder order () { + return order == Endianness.BIG_ENDIAN ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; + } + + /** Sets the byte order of this buffer. + * + * @param byteOrder the byte order to set. If {@code null} then the order will be {@link ByteOrder#LITTLE_ENDIAN LITTLE_ENDIAN} + * . + * @return this buffer. + * @see ByteOrder + * @since Android 1.0 */ + public final ByteBuffer order (ByteOrder byteOrder) { + return orderImpl(byteOrder); + } + + ByteBuffer orderImpl (ByteOrder byteOrder) { + order = byteOrder == ByteOrder.BIG_ENDIAN ? Endianness.BIG_ENDIAN : Endianness.LITTLE_ENDIAN; + return this; + } + + /** Child class implements this method to realize {@code array()}. + * + * @see #array() + * @since Android 1.0 */ + abstract byte[] protectedArray (); + + /** Child class implements this method to realize {@code arrayOffset()}. + * + * @see #arrayOffset() + * @since Android 1.0 */ + abstract int protectedArrayOffset (); + + /** Child class implements this method to realize {@code hasArray()}. + * + * @see #hasArray() + * @since Android 1.0 */ + abstract boolean protectedHasArray (); + + /** Writes the given byte to the current position and increases the position by 1. + * + * @param b the byte to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer put (byte b); + + /** Writes bytes in the given byte array to the current position and increases the position by the number of bytes written. + *

    + * Calling this method has the same effect as {@code put(src, 0, src.length)}. + *

    + * + * @param src the source byte array. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final ByteBuffer put (byte[] src) { + return put(src, 0, src.length); + } + + /** Writes bytes in the given byte array, starting from the specified offset, to the current position and increases the position + * by the number of bytes written. + * + * @param src the source byte array. + * @param off the offset of byte array, must not be negative and not greater than {@code src.length}. + * @param len the number of bytes to write, must not be negative and not greater than {@code src.length - off}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public ByteBuffer put (byte[] src, int off, int len) { + int length = src.length; + if ((off < 0) || (len < 0) || ((long)off + (long)len > length)) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + for (int i = off; i < off + len; i++) { + put(src[i]); + } + return this; + } + + /** Writes all the remaining bytes of the {@code src} byte buffer to this buffer's current position, and increases both buffers' + * position by the number of bytes copied. + * + * @param src the source byte buffer. + * @return this buffer. + * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. + * @exception IllegalArgumentException if {@code src} is this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public ByteBuffer put (ByteBuffer src) { + if (src == this) { + throw new IllegalArgumentException(); + } + if (src.remaining() > remaining()) { + throw new BufferOverflowException(); + } + byte[] contents = new byte[src.remaining()]; + src.get(contents); + put(contents); + return this; + } + + /** Write a byte to the specified index of this buffer without changing the position. + * + * @param index the index, must not be negative and less than the limit. + * @param b the byte to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer put (int index, byte b); + + /** Writes the given char to the current position and increases the position by 2. + *

    + * The char is converted to bytes using the current byte order. + *

    + * + * @param value the char to write. + * @return this buffer. + * @exception BufferOverflowException if position is greater than {@code limit - 2}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putChar (char value); + + /** Writes the given char to the specified index of this buffer. + *

    + * The char is converted to bytes using the current byte order. The position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 2}. + * @param value the char to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putChar (int index, char value); + + /** Writes the given double to the current position and increases the position by 8. + *

    + * The double is converted to bytes using the current byte order. + *

    + * + * @param value the double to write. + * @return this buffer. + * @exception BufferOverflowException if position is greater than {@code limit - 8}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putDouble (double value); + + /** Writes the given double to the specified index of this buffer. + *

    + * The double is converted to bytes using the current byte order. The position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 8}. + * @param value the double to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putDouble (int index, double value); + + /** Writes the given float to the current position and increases the position by 4. + *

    + * The float is converted to bytes using the current byte order. + *

    + * + * @param value the float to write. + * @return this buffer. + * @exception BufferOverflowException if position is greater than {@code limit - 4}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putFloat (float value); + + /** Writes the given float to the specified index of this buffer. + *

    + * The float is converted to bytes using the current byte order. The position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 4}. + * @param value the float to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putFloat (int index, float value); + + /** Writes the given int to the current position and increases the position by 4. + *

    + * The int is converted to bytes using the current byte order. + *

    + * + * @param value the int to write. + * @return this buffer. + * @exception BufferOverflowException if position is greater than {@code limit - 4}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putInt (int value); + + /** Writes the given int to the specified index of this buffer. + *

    + * The int is converted to bytes using the current byte order. The position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 4}. + * @param value the int to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putInt (int index, int value); + + /** Writes the given long to the current position and increases the position by 8. + *

    + * The long is converted to bytes using the current byte order. + *

    + * + * @param value the long to write. + * @return this buffer. + * @exception BufferOverflowException if position is greater than {@code limit - 8}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putLong (long value); + + /** Writes the given long to the specified index of this buffer. + *

    + * The long is converted to bytes using the current byte order. The position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 8}. + * @param value the long to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putLong (int index, long value); + + /** Writes the given short to the current position and increases the position by 2. + *

    + * The short is converted to bytes using the current byte order. + *

    + * + * @param value the short to write. + * @return this buffer. + * @exception BufferOverflowException if position is greater than {@code limit - 2}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putShort (short value); + + /** Writes the given short to the specified index of this buffer. + *

    + * The short is converted to bytes using the current byte order. The position is not changed. + *

    + * + * @param index the index, must not be negative and equal or less than {@code limit - 2}. + * @param value the short to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if {@code index} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer putShort (int index, short value); + + /** Returns a sliced buffer that shares its content with this buffer. + *

    + * The sliced buffer's capacity will be this buffer's {@code remaining()}, and it's zero position will correspond to this + * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new + * buffer's read-only property and byte order are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a sliced buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract ByteBuffer slice (); + + /** Returns a string representing the state of this byte buffer. + * + * @return a string representing the state of this byte buffer. + * @since Android 1.0 */ + public String toString () { + StringBuffer buf = new StringBuffer(); + buf.append(getClass().getName()); + buf.append(", status: capacity="); //$NON-NLS-1$ + buf.append(capacity()); + buf.append(" position="); //$NON-NLS-1$ + buf.append(position()); + buf.append(" limit="); //$NON-NLS-1$ + buf.append(limit()); + return buf.toString(); + } + + public ByteBuffer stringToByteBuffer (String s) { + return new StringByteBuffer(s); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBufferWrapper.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBufferWrapper.java index 455a7bcab76..a8654af4e3c 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBufferWrapper.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteBufferWrapper.java @@ -13,10 +13,9 @@ * License for the specific language governing permissions and limitations under * the License. */ -package java.nio; -import java.nio.ByteBuffer; +package java.nio; public interface ByteBufferWrapper { - ByteBuffer getByteBuffer(); + ByteBuffer getByteBuffer (); } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteOrder.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteOrder.java index 70c2d910685..a5b0f470653 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteOrder.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ByteOrder.java @@ -16,67 +16,54 @@ package java.nio; - //import org.apache.harmony.luni.platform.Platform; -/** - * Defines byte order constants. +/** Defines byte order constants. * - * @since Android 1.0 - */ + * @since Android 1.0 */ public final class ByteOrder { - /** - * This constant represents big endian. - * - * @since Android 1.0 - */ - public static final ByteOrder BIG_ENDIAN = new ByteOrder("BIG_ENDIAN"); //$NON-NLS-1$ + /** This constant represents big endian. + * + * @since Android 1.0 */ + public static final ByteOrder BIG_ENDIAN = new ByteOrder("BIG_ENDIAN"); //$NON-NLS-1$ - /** - * This constant represents little endian. - * - * @since Android 1.0 - */ - public static final ByteOrder LITTLE_ENDIAN = new ByteOrder("LITTLE_ENDIAN"); //$NON-NLS-1$ + /** This constant represents little endian. + * + * @since Android 1.0 */ + public static final ByteOrder LITTLE_ENDIAN = new ByteOrder("LITTLE_ENDIAN"); //$NON-NLS-1$ - private static final ByteOrder NATIVE_ORDER; + private static final ByteOrder NATIVE_ORDER; - static { -// if (Platform.getMemorySystem().isLittleEndian()) { - NATIVE_ORDER = LITTLE_ENDIAN; -// } else { -// NATIVE_ORDER = BIG_ENDIAN; -// } - } + static { +// if (Platform.getMemorySystem().isLittleEndian()) { + NATIVE_ORDER = LITTLE_ENDIAN; +// } else { +// NATIVE_ORDER = BIG_ENDIAN; +// } + } - /** - * Returns the current platform byte order. - * - * @return the byte order object, which is either LITTLE_ENDIAN or - * BIG_ENDIAN. - * @since Android 1.0 - */ - public static ByteOrder nativeOrder() { - return NATIVE_ORDER; - } + /** Returns the current platform byte order. + * + * @return the byte order object, which is either LITTLE_ENDIAN or BIG_ENDIAN. + * @since Android 1.0 */ + public static ByteOrder nativeOrder () { + return NATIVE_ORDER; + } - private final String name; + private final String name; - private ByteOrder(String name) { - super(); - this.name = name; - } + private ByteOrder (String name) { + super(); + this.name = name; + } - /** - * Returns a string that describes this object. - * - * @return "BIG_ENDIAN" for {@link #BIG_ENDIAN ByteOrder.BIG_ENDIAN} - * objects, "LITTLE_ENDIAN" for - * {@link #LITTLE_ENDIAN ByteOrder.LITTLE_ENDIAN} objects. - * @since Android 1.0 - */ - public String toString() { - return name; - } + /** Returns a string that describes this object. + * + * @return "BIG_ENDIAN" for {@link #BIG_ENDIAN ByteOrder.BIG_ENDIAN} objects, "LITTLE_ENDIAN" for {@link #LITTLE_ENDIAN + * ByteOrder.LITTLE_ENDIAN} objects. + * @since Android 1.0 */ + public String toString () { + return name; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharArrayBuffer.java index 516aada5176..17a0522b464 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharArrayBuffer.java @@ -17,85 +17,80 @@ package java.nio; -/** - * CharArrayBuffer, ReadWriteCharArrayBuffer and ReadOnlyCharArrayBuffer compose - * the implementation of array based char buffers. +/** CharArrayBuffer, ReadWriteCharArrayBuffer and ReadOnlyCharArrayBuffer compose the implementation of array based char buffers. *

    - * CharArrayBuffer implements all the shared readonly methods and is extended by - * the other two classes. + * CharArrayBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class CharArrayBuffer extends CharBuffer { - protected final char[] backingArray; + protected final char[] backingArray; + + protected final int offset; + + CharArrayBuffer (char[] array) { + this(array.length, array, 0); + } - protected final int offset; + CharArrayBuffer (int capacity) { + this(capacity, new char[capacity], 0); + } - CharArrayBuffer(char[] array) { - this(array.length, array, 0); - } + CharArrayBuffer (int capacity, char[] backingArray, int offset) { + super(capacity); + this.backingArray = backingArray; + this.offset = offset; + } - CharArrayBuffer(int capacity) { - this(capacity, new char[capacity], 0); - } + public final char get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return backingArray[offset + position++]; + } - CharArrayBuffer(int capacity, char[] backingArray, int offset) { - super(capacity); - this.backingArray = backingArray; - this.offset = offset; - } + public final char get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return backingArray[offset + index]; + } - public final char get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return backingArray[offset + position++]; - } + public final CharBuffer get (char[] dest, int off, int len) { + int length = dest.length; + if ((off < 0) || (len < 0) || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + System.arraycopy(backingArray, offset + position, dest, off, len); + position += len; + return this; + } - public final char get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return backingArray[offset + index]; - } + public final boolean isDirect () { + return false; + } - public final CharBuffer get(char[] dest, int off, int len) { - int length = dest.length; - if ((off < 0 ) || (len < 0) || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - System.arraycopy(backingArray, offset+position, dest, off, len); - position += len; - return this; - } - - public final boolean isDirect() { - return false; - } + public final ByteOrder order () { + return ByteOrder.nativeOrder(); + } - public final ByteOrder order() { - return ByteOrder.nativeOrder(); - } + public final CharSequence subSequence (int start, int end) { + if (start < 0 || end < start || end > remaining()) { + throw new IndexOutOfBoundsException(); + } - public final CharSequence subSequence(int start, int end) { - if (start < 0 || end < start || end > remaining()) { - throw new IndexOutOfBoundsException(); - } - - CharBuffer result = duplicate(); - result.limit(position + end); - result.position(position + start); - return result; - } + CharBuffer result = duplicate(); + result.limit(position + end); + result.position(position + start); + return result; + } - public final String toString() { - return String.copyValueOf(backingArray, offset + position, remaining()); - } + public final String toString () { + return String.copyValueOf(backingArray, offset + position, remaining()); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharBuffer.java index 2fc8c2a82b0..e5c4dad4c5e 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharBuffer.java @@ -19,838 +19,605 @@ import java.io.IOException; -/** - * A buffer of chars. +/** A buffer of chars. *

    * A char buffer can be created in either one of the following ways: *

    *
      - *
    • {@link #allocate(int) Allocate} a new char array and create a buffer - * based on it;
    • - *
    • {@link #wrap(char[]) Wrap} an existing char array to create a new - * buffer;
    • - *
    • {@link #wrap(CharSequence) Wrap} an existing char sequence to create a - * new buffer;
    • - *
    • Use {@link java.nio.ByteBuffer#asCharBuffer() ByteBuffer.asCharBuffer} - * to create a char buffer based on a byte buffer.
    • + *
    • {@link #allocate(int) Allocate} a new char array and create a buffer based on it;
    • + *
    • {@link #wrap(char[]) Wrap} an existing char array to create a new buffer;
    • + *
    • {@link #wrap(CharSequence) Wrap} an existing char sequence to create a new buffer;
    • + *
    • Use {@link java.nio.ByteBuffer#asCharBuffer() ByteBuffer.asCharBuffer} to create a char buffer based on a byte buffer.
    • *
    * - * @since Android 1.0 - */ -public abstract class CharBuffer extends Buffer implements Comparable, - CharSequence, Appendable {//, Readable { - - /** - * Creates a char buffer based on a newly allocated char array. - * - * @param capacity - * the capacity of the new buffer. - * @return the created char buffer. - * @throws IllegalArgumentException - * if {@code capacity} is less than zero. - * @since Android 1.0 - */ - public static CharBuffer allocate(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newCharBuffer(capacity); - } - - /** - * Creates a new char buffer by wrapping the given char array. - *

    - * Calling this method has the same effect as - * {@code wrap(array, 0, array.length)}. - *

    - * - * @param array - * the char array which the new buffer will be based on. - * @return the created char buffer. - * @since Android 1.0 - */ - public static CharBuffer wrap(char[] array) { - return wrap(array, 0, array.length); - } - - /** - * Creates a new char buffer by wrapping the given char array. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code start + len}, capacity will be the length of the array. - *

    - * - * @param array - * the char array which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code array.length}. - * @param len - * the length, must not be negative and not greater than - * {@code array.length - start}. - * @return the created char buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code len} is invalid. - * @since Android 1.0 - */ - public static CharBuffer wrap(char[] array, int start, int len) { - int length = array.length; - if ((start < 0) || (len < 0) - || (long) start + (long) len > length) { - throw new IndexOutOfBoundsException(); - } - - CharBuffer buf = BufferFactory.newCharBuffer(array); - buf.position = start; - buf.limit = start + len; - - return buf; - } - - /** - * Creates a new char buffer by wrapping the given char sequence. - *

    - * Calling this method has the same effect as - * {@code wrap(chseq, 0, chseq.length())}. - *

    - * - * @param chseq - * the char sequence which the new buffer will be based on. - * @return the created char buffer. - * @since Android 1.0 - */ - public static CharBuffer wrap(CharSequence chseq) { - return BufferFactory.newCharBuffer(chseq); - } - - /** - * Creates a new char buffer by wrapping the given char sequence. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code end}, capacity will be the length of the char sequence. The new - * buffer is read-only. - *

    - * - * @param chseq - * the char sequence which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code chseq.length()}. - * @param end - * the end index, must be no less than {@code start} and no - * greater than {@code chseq.length()}. - * @return the created char buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code end} is invalid. - * @since Android 1.0 - */ - public static CharBuffer wrap(CharSequence chseq, int start, int end) { - if (chseq == null) { - throw new NullPointerException(); - } - if (start < 0 || end < start || end > chseq.length()) { - throw new IndexOutOfBoundsException(); - } - - CharBuffer result = BufferFactory.newCharBuffer(chseq); - result.position = start; - result.limit = end; - return result; - } - - /** - * Constructs a {@code CharBuffer} with given capacity. - * - * @param capacity - * the capacity of the buffer. - * @since Android 1.0 - */ - CharBuffer(int capacity) { - super(capacity); - } - - /** - * Returns the char array which this buffer is based on, if there is one. - * - * @return the char array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final char[] array() { - return protectedArray(); - } - - /** - * Returns the offset of the char array which this buffer is based on, if - * there is one. - *

    - * The offset is the index of the array corresponds to the zero position of - * the buffer. - *

    - * - * @return the offset of the char array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int arrayOffset() { - return protectedArrayOffset(); - } - - /** - * Returns a read-only buffer that shares its content with this buffer. - *

    - * The returned buffer is guaranteed to be a new instance, even if this - * buffer is read-only itself. The new buffer's position, limit, capacity - * and mark are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means this - * buffer's change of content will be visible to the new buffer. The two - * buffer's position, limit and mark are independent. - *

    - * - * @return a read-only version of this buffer. - * @since Android 1.0 - */ - public abstract CharBuffer asReadOnlyBuffer(); - - /** - * Returns the character located at the specified index in the buffer. The - * index value is referenced from the current buffer position. - * - * @param index - * the index referenced from the current buffer position. It must - * not be less than zero but less than the value obtained from a - * call to {@code remaining()}. - * @return the character located at the specified index (referenced from the - * current position) in the buffer. - * @exception IndexOutOfBoundsException - * if the index is invalid. - * @since Android 1.0 - */ - public final char charAt(int index) { - if (index < 0 || index >= remaining()) { - throw new IndexOutOfBoundsException(); - } - return get(position + index); - } - - /** - * Compacts this char buffer. - *

    - * The remaining chars will be moved to the head of the buffer, - * starting from position zero. Then the position is set to - * {@code remaining()}; the limit is set to capacity; the mark is cleared. - *

    - * - * @return this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract CharBuffer compact(); - - /** - * Compare the remaining chars of this buffer to another char - * buffer's remaining chars. - * - * @param otherBuffer - * another char buffer. - * @return a negative value if this is less than {@code otherBuffer}; 0 if - * this equals to {@code otherBuffer}; a positive value if this is - * greater than {@code otherBuffer}. - * @exception ClassCastException - * if {@code otherBuffer} is not a char buffer. - * @since Android 1.0 - */ - public int compareTo(CharBuffer otherBuffer) { - int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() - : otherBuffer.remaining(); - int thisPos = position; - int otherPos = otherBuffer.position; - char thisByte, otherByte; - while (compareRemaining > 0) { - thisByte = get(thisPos); - otherByte = otherBuffer.get(otherPos); - if (thisByte != otherByte) { - return thisByte < otherByte ? -1 : 1; - } - thisPos++; - otherPos++; - compareRemaining--; - } - return remaining() - otherBuffer.remaining(); - } - - /** - * Returns a duplicated buffer that shares its content with this buffer. - *

    - * The duplicated buffer's initial position, limit, capacity and mark are - * the same as this buffer's. The duplicated buffer's read-only property and - * byte order are the same as this buffer's, too. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a duplicated buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract CharBuffer duplicate(); - - /** - * Checks whether this char buffer is equal to another object. - *

    - * If {@code other} is not a char buffer then {@code false} is returned. Two - * char buffers are equal if and only if their remaining chars are exactly - * the same. Position, limit, capacity and mark are not considered. - *

    - * - * @param other - * the object to compare with this char buffer. - * @return {@code true} if this char buffer is equal to {@code other}, - * {@code false} otherwise. - * @since Android 1.0 - */ - public boolean equals(Object other) { - if (!(other instanceof CharBuffer)) { - return false; - } - CharBuffer otherBuffer = (CharBuffer) other; - - if (remaining() != otherBuffer.remaining()) { - return false; - } - - int myPosition = position; - int otherPosition = otherBuffer.position; - boolean equalSoFar = true; - while (equalSoFar && (myPosition < limit)) { - equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); - } - - return equalSoFar; - } - - /** - * Returns the char at the current position and increases the position by 1. - * - * @return the char at the current position. - * @exception BufferUnderflowException - * if the position is equal or greater than limit. - * @since Android 1.0 - */ - public abstract char get(); - - /** - * Reads chars from the current position into the specified char array and - * increases the position by the number of chars read. - *

    - * Calling this method has the same effect as - * {@code get(dest, 0, dest.length)}. - *

    - * - * @param dest - * the destination char array. - * @return this buffer. - * @exception BufferUnderflowException - * if {@code dest.length} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public CharBuffer get(char[] dest) { - return get(dest, 0, dest.length); - } - - /** - * Reads chars from the current position into the specified char array, - * starting from the specified offset, and increases the position by the - * number of chars read. - * - * @param dest - * the target char array. - * @param off - * the offset of the char array, must not be negative and not - * greater than {@code dest.length}. - * @param len - * The number of chars to read, must be no less than zero and no - * greater than {@code dest.length - off}. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception BufferUnderflowException - * if {@code len} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public CharBuffer get(char[] dest, int off, int len) { - int length = dest.length; - if ((off < 0 ) || (len < 0) || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferUnderflowException(); - } - for (int i = off; i < off + len; i++) { - dest[i] = get(); - } - return this; - } - - /** - * Returns a char at the specified index; the position is not changed. - * - * @param index - * the index, must not be negative and less than limit. - * @return a char at the specified index. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @since Android 1.0 - */ - public abstract char get(int index); - - /** - * Indicates whether this buffer is based on a char array and is read/write. - * - * @return {@code true} if this buffer is based on a byte array and provides - * read/write access, {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasArray() { - return protectedHasArray(); - } - - /** - * Calculates this buffer's hash code from the remaining chars. The - * position, limit, capacity and mark don't affect the hash code. - * - * @return the hash code calculated from the remaining chars. - * @since Android 1.0 - */ - public int hashCode() { - int myPosition = position; - int hash = 0; - while (myPosition < limit) { - hash = hash + get(myPosition++); - } - return hash; - } - - /** - * Indicates whether this buffer is direct. A direct buffer will try its - * best to take advantage of native memory APIs and it may not stay in the - * Java heap, so it is not affected by garbage collection. - *

    - * A char buffer is direct if it is based on a byte buffer and the byte - * buffer is direct. - *

    - * - * @return {@code true} if this buffer is direct, {@code false} otherwise. - * @since Android 1.0 - */ - public abstract boolean isDirect(); - - /** - * Returns the number of remaining chars. - * - * @return the number of remaining chars. - * @since Android 1.0 - */ - public final int length() { - return remaining(); - } - - /** - * Returns the byte order used by this buffer when converting chars from/to - * bytes. - *

    - * If this buffer is not based on a byte buffer, then this always returns - * the platform's native byte order. - *

    - * - * @return the byte order used by this buffer when converting chars from/to - * bytes. - * @since Android 1.0 - */ - public abstract ByteOrder order(); - - /** - * Child class implements this method to realize {@code array()}. - * - * @see #array() - */ - abstract char[] protectedArray(); - - /** - * Child class implements this method to realize {@code arrayOffset()}. - * - * @see #arrayOffset() - */ - abstract int protectedArrayOffset(); - - /** - * Child class implements this method to realize {@code hasArray()}. - * - * @see #hasArray() - */ - abstract boolean protectedHasArray(); - - /** - * Writes the given char to the current position and increases the position - * by 1. - * - * @param c - * the char to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract CharBuffer put(char c); - - /** - * Writes chars from the given char array to the current position and - * increases the position by the number of chars written. - *

    - * Calling this method has the same effect as - * {@code put(src, 0, src.length)}. - *

    - * - * @param src - * the source char array. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code src.length}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final CharBuffer put(char[] src) { - return put(src, 0, src.length); - } - - /** - * Writes chars from the given char array, starting from the specified offset, - * to the current position and increases the position by the number of chars - * written. - * - * @param src - * the source char array. - * @param off - * the offset of char array, must not be negative and not greater - * than {@code src.length}. - * @param len - * the number of chars to write, must be no less than zero and no - * greater than {@code src.length - off}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code len}. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public CharBuffer put(char[] src, int off, int len) { - int length = src.length; - if ((off < 0 ) || (len < 0) || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - for (int i = off; i < off + len; i++) { - put(src[i]); - } - return this; - } - - /** - * Writes all the remaining chars of the {@code src} char buffer to this - * buffer's current position, and increases both buffers' position by the - * number of chars copied. - * - * @param src - * the source char buffer. - * @return this buffer. - * @exception BufferOverflowException - * if {@code src.remaining()} is greater than this buffer's - * {@code remaining()}. - * @exception IllegalArgumentException - * if {@code src} is this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public CharBuffer put(CharBuffer src) { - if (src == this) { - throw new IllegalArgumentException(); - } - if (src.remaining() > remaining()) { - throw new BufferOverflowException(); - } - - char[] contents = new char[src.remaining()]; - src.get(contents); - put(contents); - return this; - } - - /** - * Writes a char to the specified index of this buffer; the position is not - * changed. - * - * @param index - * the index, must be no less than zero and less than the limit. - * @param c - * the char to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract CharBuffer put(int index, char c); - - /** - * Writes all chars of the given string to the current position of this - * buffer, and increases the position by the length of string. - *

    - * Calling this method has the same effect as - * {@code put(str, 0, str.length())}. - *

    - * - * @param str - * the string to write. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than the length of string. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final CharBuffer put(String str) { - return put(str, 0, str.length()); - } - - /** - * Writes chars of the given string to the current position of this buffer, - * and increases the position by the number of chars written. - * - * @param str - * the string to write. - * @param start - * the first char to write, must not be negative and not greater - * than {@code str.length()}. - * @param end - * the last char to write (excluding), must be less than - * {@code start} and not greater than {@code str.length()}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code end - start}. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code end} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public CharBuffer put(String str, int start, int end) { - int length = str.length(); - if (start < 0 || end < start || end > length) { - throw new IndexOutOfBoundsException(); - } - - if (end - start > remaining()) { - throw new BufferOverflowException(); - } - for (int i = start; i < end; i++) { - put(str.charAt(i)); - } - return this; - } - - /** - * Returns a sliced buffer that shares its content with this buffer. - *

    - * The sliced buffer's capacity will be this buffer's {@code remaining()}, - * and its zero position will correspond to this buffer's current position. - * The new buffer's position will be 0, limit will be its capacity, and its - * mark is cleared. The new buffer's read-only property and byte order are - * same as this buffer. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a sliced buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract CharBuffer slice(); - - /** - * Returns a new char buffer representing a sub-sequence of this buffer's - * current remaining content. - *

    - * The new buffer's position will be {@code position() + start}, limit will - * be {@code position() + end}, capacity will be the same as this buffer. - * The new buffer's read-only property and byte order are the same as this - * buffer. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @param start - * the start index of the sub-sequence, referenced from the - * current buffer position. Must not be less than zero and not - * greater than the value obtained from a call to - * {@code remaining()}. - * @param end - * the end index of the sub-sequence, referenced from the current - * buffer position. Must not be less than {@code start} and not - * be greater than the value obtained from a call to - * {@code remaining()}. - * @return a new char buffer represents a sub-sequence of this buffer's - * current remaining content. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code end} is invalid. - * @since Android 1.0 - */ - public abstract CharSequence subSequence(int start, int end); - - /** - * Returns a string representing the current remaining chars of this buffer. - * - * @return a string representing the current remaining chars of this buffer. - * @since Android 1.0 - */ - public String toString() { - StringBuffer strbuf = new StringBuffer(); - for (int i = position; i < limit; i++) { - strbuf.append(get(i)); - } - return strbuf.toString(); - } - - /** - * Writes the given char to the current position and increases the position - * by 1. - * - * @param c - * the char to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public CharBuffer append(char c){ - return put(c); - } - - /** - * Writes all chars of the given character sequence {@code csq} to the - * current position of this buffer, and increases the position by the length - * of the csq. - *

    - * Calling this method has the same effect as {@code append(csq.toString())}. - *

    - * If the {@code CharSequence} is {@code null} the string "null" will be - * written to the buffer. - * - * @param csq - * the {@code CharSequence} to write. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than the length of csq. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public CharBuffer append(CharSequence csq){ - if (csq != null) { - return put(csq.toString()); - } - return put("null"); //$NON-NLS-1$ - } - - /** - * Writes chars of the given {@code CharSequence} to the current position of - * this buffer, and increases the position by the number of chars written. - * - * @param csq - * the {@code CharSequence} to write. - * @param start - * the first char to write, must not be negative and not greater - * than {@code csq.length()}. - * @param end - * the last char to write (excluding), must be less than - * {@code start} and not greater than {@code csq.length()}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code end - start}. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code end} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public CharBuffer append(CharSequence csq, int start, int end){ - if (csq == null) { - csq = "null"; //$NON-NLS-1$ - } - CharSequence cs = csq.subSequence(start, end); - if (cs.length() > 0) { - return put(cs.toString()); - } - return this; - } - - /** - * Reads characters from this buffer and puts them into {@code target}. The - * number of chars that are copied is either the number of remaining chars - * in this buffer or the number of remaining chars in {@code target}, - * whichever is smaller. - * - * @param target - * the target char buffer. - * @throws IllegalArgumentException - * if {@code target} is this buffer. - * @throws IOException - * if an I/O error occurs. - * @throws ReadOnlyBufferException - * if no changes may be made to the contents of {@code target}. - * @return the number of chars copied or -1 if there are no chars left to be - * read from this buffer. - * @since Android 1.0 - */ - public int read(CharBuffer target) throws IOException { - if(target == this){ - throw new IllegalArgumentException(); - } - if (remaining() == 0) { - return target.remaining()==0?0:-1; - } - int result = Math.min(target.remaining(), remaining()); - char[] chars = new char[result]; - get(chars); - target.put(chars); - return result; - } + * @since Android 1.0 */ +public abstract class CharBuffer extends Buffer implements Comparable, CharSequence, Appendable {// , Readable { + + /** Creates a char buffer based on a newly allocated char array. + * + * @param capacity the capacity of the new buffer. + * @return the created char buffer. + * @throws IllegalArgumentException if {@code capacity} is less than zero. + * @since Android 1.0 */ + public static CharBuffer allocate (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newCharBuffer(capacity); + } + + /** Creates a new char buffer by wrapping the given char array. + *

    + * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. + *

    + * + * @param array the char array which the new buffer will be based on. + * @return the created char buffer. + * @since Android 1.0 */ + public static CharBuffer wrap (char[] array) { + return wrap(array, 0, array.length); + } + + /** Creates a new char buffer by wrapping the given char array. + *

    + * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the + * array. + *

    + * + * @param array the char array which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code array.length}. + * @param len the length, must not be negative and not greater than {@code array.length - start}. + * @return the created char buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. + * @since Android 1.0 */ + public static CharBuffer wrap (char[] array, int start, int len) { + int length = array.length; + if ((start < 0) || (len < 0) || (long)start + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + CharBuffer buf = BufferFactory.newCharBuffer(array); + buf.position = start; + buf.limit = start + len; + + return buf; + } + + /** Creates a new char buffer by wrapping the given char sequence. + *

    + * Calling this method has the same effect as {@code wrap(chseq, 0, chseq.length())}. + *

    + * + * @param chseq the char sequence which the new buffer will be based on. + * @return the created char buffer. + * @since Android 1.0 */ + public static CharBuffer wrap (CharSequence chseq) { + return BufferFactory.newCharBuffer(chseq); + } + + /** Creates a new char buffer by wrapping the given char sequence. + *

    + * The new buffer's position will be {@code start}, limit will be {@code end}, capacity will be the length of the char + * sequence. The new buffer is read-only. + *

    + * + * @param chseq the char sequence which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code chseq.length()}. + * @param end the end index, must be no less than {@code start} and no greater than {@code chseq.length()}. + * @return the created char buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code end} is invalid. + * @since Android 1.0 */ + public static CharBuffer wrap (CharSequence chseq, int start, int end) { + if (chseq == null) { + throw new NullPointerException(); + } + if (start < 0 || end < start || end > chseq.length()) { + throw new IndexOutOfBoundsException(); + } + + CharBuffer result = BufferFactory.newCharBuffer(chseq); + result.position = start; + result.limit = end; + return result; + } + + /** Constructs a {@code CharBuffer} with given capacity. + * + * @param capacity the capacity of the buffer. + * @since Android 1.0 */ + CharBuffer (int capacity) { + super(capacity); + } + + /** Returns the char array which this buffer is based on, if there is one. + * + * @return the char array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final char[] array () { + return protectedArray(); + } + + /** Returns the offset of the char array which this buffer is based on, if there is one. + *

    + * The offset is the index of the array corresponds to the zero position of the buffer. + *

    + * + * @return the offset of the char array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int arrayOffset () { + return protectedArrayOffset(); + } + + /** Returns a read-only buffer that shares its content with this buffer. + *

    + * The returned buffer is guaranteed to be a new instance, even if this buffer is read-only itself. The new buffer's position, + * limit, capacity and mark are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means this buffer's change of content will be visible to the new + * buffer. The two buffer's position, limit and mark are independent. + *

    + * + * @return a read-only version of this buffer. + * @since Android 1.0 */ + public abstract CharBuffer asReadOnlyBuffer (); + + /** Returns the character located at the specified index in the buffer. The index value is referenced from the current buffer + * position. + * + * @param index the index referenced from the current buffer position. It must not be less than zero but less than the value + * obtained from a call to {@code remaining()}. + * @return the character located at the specified index (referenced from the current position) in the buffer. + * @exception IndexOutOfBoundsException if the index is invalid. + * @since Android 1.0 */ + public final char charAt (int index) { + if (index < 0 || index >= remaining()) { + throw new IndexOutOfBoundsException(); + } + return get(position + index); + } + + /** Compacts this char buffer. + *

    + * The remaining chars will be moved to the head of the buffer, starting from position zero. Then the position is set to + * {@code remaining()}; the limit is set to capacity; the mark is cleared. + *

    + * + * @return this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract CharBuffer compact (); + + /** Compare the remaining chars of this buffer to another char buffer's remaining chars. + * + * @param otherBuffer another char buffer. + * @return a negative value if this is less than {@code otherBuffer}; 0 if this equals to {@code otherBuffer}; a positive value + * if this is greater than {@code otherBuffer}. + * @exception ClassCastException if {@code otherBuffer} is not a char buffer. + * @since Android 1.0 */ + public int compareTo (CharBuffer otherBuffer) { + int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); + int thisPos = position; + int otherPos = otherBuffer.position; + char thisByte, otherByte; + while (compareRemaining > 0) { + thisByte = get(thisPos); + otherByte = otherBuffer.get(otherPos); + if (thisByte != otherByte) { + return thisByte < otherByte ? -1 : 1; + } + thisPos++; + otherPos++; + compareRemaining--; + } + return remaining() - otherBuffer.remaining(); + } + + /** Returns a duplicated buffer that shares its content with this buffer. + *

    + * The duplicated buffer's initial position, limit, capacity and mark are the same as this buffer's. The duplicated buffer's + * read-only property and byte order are the same as this buffer's, too. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a duplicated buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract CharBuffer duplicate (); + + /** Checks whether this char buffer is equal to another object. + *

    + * If {@code other} is not a char buffer then {@code false} is returned. Two char buffers are equal if and only if their + * remaining chars are exactly the same. Position, limit, capacity and mark are not considered. + *

    + * + * @param other the object to compare with this char buffer. + * @return {@code true} if this char buffer is equal to {@code other}, {@code false} otherwise. + * @since Android 1.0 */ + public boolean equals (Object other) { + if (!(other instanceof CharBuffer)) { + return false; + } + CharBuffer otherBuffer = (CharBuffer)other; + + if (remaining() != otherBuffer.remaining()) { + return false; + } + + int myPosition = position; + int otherPosition = otherBuffer.position; + boolean equalSoFar = true; + while (equalSoFar && (myPosition < limit)) { + equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); + } + + return equalSoFar; + } + + /** Returns the char at the current position and increases the position by 1. + * + * @return the char at the current position. + * @exception BufferUnderflowException if the position is equal or greater than limit. + * @since Android 1.0 */ + public abstract char get (); + + /** Reads chars from the current position into the specified char array and increases the position by the number of chars read. + *

    + * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. + *

    + * + * @param dest the destination char array. + * @return this buffer. + * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. + * @since Android 1.0 */ + public CharBuffer get (char[] dest) { + return get(dest, 0, dest.length); + } + + /** Reads chars from the current position into the specified char array, starting from the specified offset, and increases the + * position by the number of chars read. + * + * @param dest the target char array. + * @param off the offset of the char array, must not be negative and not greater than {@code dest.length}. + * @param len The number of chars to read, must be no less than zero and no greater than {@code dest.length - off}. + * @return this buffer. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. + * @since Android 1.0 */ + public CharBuffer get (char[] dest, int off, int len) { + int length = dest.length; + if ((off < 0) || (len < 0) || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferUnderflowException(); + } + for (int i = off; i < off + len; i++) { + dest[i] = get(); + } + return this; + } + + /** Returns a char at the specified index; the position is not changed. + * + * @param index the index, must not be negative and less than limit. + * @return a char at the specified index. + * @exception IndexOutOfBoundsException if index is invalid. + * @since Android 1.0 */ + public abstract char get (int index); + + /** Indicates whether this buffer is based on a char array and is read/write. + * + * @return {@code true} if this buffer is based on a byte array and provides read/write access, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasArray () { + return protectedHasArray(); + } + + /** Calculates this buffer's hash code from the remaining chars. The position, limit, capacity and mark don't affect the hash + * code. + * + * @return the hash code calculated from the remaining chars. + * @since Android 1.0 */ + public int hashCode () { + int myPosition = position; + int hash = 0; + while (myPosition < limit) { + hash = hash + get(myPosition++); + } + return hash; + } + + /** Indicates whether this buffer is direct. A direct buffer will try its best to take advantage of native memory APIs and it + * may not stay in the Java heap, so it is not affected by garbage collection. + *

    + * A char buffer is direct if it is based on a byte buffer and the byte buffer is direct. + *

    + * + * @return {@code true} if this buffer is direct, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isDirect (); + + /** Returns the number of remaining chars. + * + * @return the number of remaining chars. + * @since Android 1.0 */ + public final int length () { + return remaining(); + } + + /** Returns the byte order used by this buffer when converting chars from/to bytes. + *

    + * If this buffer is not based on a byte buffer, then this always returns the platform's native byte order. + *

    + * + * @return the byte order used by this buffer when converting chars from/to bytes. + * @since Android 1.0 */ + public abstract ByteOrder order (); + + /** Child class implements this method to realize {@code array()}. + * + * @see #array() */ + abstract char[] protectedArray (); + + /** Child class implements this method to realize {@code arrayOffset()}. + * + * @see #arrayOffset() */ + abstract int protectedArrayOffset (); + + /** Child class implements this method to realize {@code hasArray()}. + * + * @see #hasArray() */ + abstract boolean protectedHasArray (); + + /** Writes the given char to the current position and increases the position by 1. + * + * @param c the char to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract CharBuffer put (char c); + + /** Writes chars from the given char array to the current position and increases the position by the number of chars written. + *

    + * Calling this method has the same effect as {@code put(src, 0, src.length)}. + *

    + * + * @param src the source char array. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final CharBuffer put (char[] src) { + return put(src, 0, src.length); + } + + /** Writes chars from the given char array, starting from the specified offset, to the current position and increases the + * position by the number of chars written. + * + * @param src the source char array. + * @param off the offset of char array, must not be negative and not greater than {@code src.length}. + * @param len the number of chars to write, must be no less than zero and no greater than {@code src.length - off}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public CharBuffer put (char[] src, int off, int len) { + int length = src.length; + if ((off < 0) || (len < 0) || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + for (int i = off; i < off + len; i++) { + put(src[i]); + } + return this; + } + + /** Writes all the remaining chars of the {@code src} char buffer to this buffer's current position, and increases both buffers' + * position by the number of chars copied. + * + * @param src the source char buffer. + * @return this buffer. + * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. + * @exception IllegalArgumentException if {@code src} is this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public CharBuffer put (CharBuffer src) { + if (src == this) { + throw new IllegalArgumentException(); + } + if (src.remaining() > remaining()) { + throw new BufferOverflowException(); + } + + char[] contents = new char[src.remaining()]; + src.get(contents); + put(contents); + return this; + } + + /** Writes a char to the specified index of this buffer; the position is not changed. + * + * @param index the index, must be no less than zero and less than the limit. + * @param c the char to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if index is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract CharBuffer put (int index, char c); + + /** Writes all chars of the given string to the current position of this buffer, and increases the position by the length of + * string. + *

    + * Calling this method has the same effect as {@code put(str, 0, str.length())}. + *

    + * + * @param str the string to write. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than the length of string. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final CharBuffer put (String str) { + return put(str, 0, str.length()); + } + + /** Writes chars of the given string to the current position of this buffer, and increases the position by the number of chars + * written. + * + * @param str the string to write. + * @param start the first char to write, must not be negative and not greater than {@code str.length()}. + * @param end the last char to write (excluding), must be less than {@code start} and not greater than {@code str.length()}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code end - start}. + * @exception IndexOutOfBoundsException if either {@code start} or {@code end} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public CharBuffer put (String str, int start, int end) { + int length = str.length(); + if (start < 0 || end < start || end > length) { + throw new IndexOutOfBoundsException(); + } + + if (end - start > remaining()) { + throw new BufferOverflowException(); + } + for (int i = start; i < end; i++) { + put(str.charAt(i)); + } + return this; + } + + /** Returns a sliced buffer that shares its content with this buffer. + *

    + * The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero position will correspond to this + * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new + * buffer's read-only property and byte order are same as this buffer. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a sliced buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract CharBuffer slice (); + + /** Returns a new char buffer representing a sub-sequence of this buffer's current remaining content. + *

    + * The new buffer's position will be {@code position() + start}, limit will be {@code position() + end}, capacity will be the + * same as this buffer. The new buffer's read-only property and byte order are the same as this buffer. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @param start the start index of the sub-sequence, referenced from the current buffer position. Must not be less than zero + * and not greater than the value obtained from a call to {@code remaining()}. + * @param end the end index of the sub-sequence, referenced from the current buffer position. Must not be less than + * {@code start} and not be greater than the value obtained from a call to {@code remaining()}. + * @return a new char buffer represents a sub-sequence of this buffer's current remaining content. + * @exception IndexOutOfBoundsException if either {@code start} or {@code end} is invalid. + * @since Android 1.0 */ + public abstract CharSequence subSequence (int start, int end); + + /** Returns a string representing the current remaining chars of this buffer. + * + * @return a string representing the current remaining chars of this buffer. + * @since Android 1.0 */ + public String toString () { + StringBuffer strbuf = new StringBuffer(); + for (int i = position; i < limit; i++) { + strbuf.append(get(i)); + } + return strbuf.toString(); + } + + /** Writes the given char to the current position and increases the position by 1. + * + * @param c the char to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public CharBuffer append (char c) { + return put(c); + } + + /** Writes all chars of the given character sequence {@code csq} to the current position of this buffer, and increases the + * position by the length of the csq. + *

    + * Calling this method has the same effect as {@code append(csq.toString())}. + *

    + * If the {@code CharSequence} is {@code null} the string "null" will be written to the buffer. + * + * @param csq the {@code CharSequence} to write. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than the length of csq. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public CharBuffer append (CharSequence csq) { + if (csq != null) { + return put(csq.toString()); + } + return put("null"); //$NON-NLS-1$ + } + + /** Writes chars of the given {@code CharSequence} to the current position of this buffer, and increases the position by the + * number of chars written. + * + * @param csq the {@code CharSequence} to write. + * @param start the first char to write, must not be negative and not greater than {@code csq.length()}. + * @param end the last char to write (excluding), must be less than {@code start} and not greater than {@code csq.length()}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code end - start}. + * @exception IndexOutOfBoundsException if either {@code start} or {@code end} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public CharBuffer append (CharSequence csq, int start, int end) { + if (csq == null) { + csq = "null"; //$NON-NLS-1$ + } + CharSequence cs = csq.subSequence(start, end); + if (cs.length() > 0) { + return put(cs.toString()); + } + return this; + } + + /** Reads characters from this buffer and puts them into {@code target}. The number of chars that are copied is either the + * number of remaining chars in this buffer or the number of remaining chars in {@code target}, whichever is smaller. + * + * @param target the target char buffer. + * @throws IllegalArgumentException if {@code target} is this buffer. + * @throws IOException if an I/O error occurs. + * @throws ReadOnlyBufferException if no changes may be made to the contents of {@code target}. + * @return the number of chars copied or -1 if there are no chars left to be read from this buffer. + * @since Android 1.0 */ + public int read (CharBuffer target) throws IOException { + if (target == this) { + throw new IllegalArgumentException(); + } + if (remaining() == 0) { + return target.remaining() == 0 ? 0 : -1; + } + int result = Math.min(target.remaining(), remaining()); + char[] chars = new char[result]; + get(chars); + target.put(chars); + return result; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharSequenceAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharSequenceAdapter.java index 32edc18bb8e..45b7e77ef9e 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharSequenceAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharSequenceAdapter.java @@ -17,136 +17,133 @@ package java.nio; -/** - * This class wraps a char sequence to be a char buffer. +/** This class wraps a char sequence to be a char buffer. *

    * Implementation notice: *

      *
    • Char sequence based buffer is always readonly.
    • *
    - *

    - * - */ + *

    */ final class CharSequenceAdapter extends CharBuffer { - static CharSequenceAdapter copy(CharSequenceAdapter other) { - CharSequenceAdapter buf = new CharSequenceAdapter(other.sequence); - buf.limit = other.limit; - buf.position = other.position; - buf.mark = other.mark; - return buf; - } - - final CharSequence sequence; - - CharSequenceAdapter(CharSequence chseq) { - super(chseq.length()); - sequence = chseq; - } - - public CharBuffer asReadOnlyBuffer() { - return duplicate(); - } - - public CharBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public CharBuffer duplicate() { - return copy(this); - } - - public char get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return sequence.charAt(position++); - } - - public char get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return sequence.charAt(index); - } - - public final CharBuffer get(char[] dest, int off, int len) { - int length = dest.length; - if ((off < 0 ) || (len < 0) || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - int newPosition = position + len; - sequence.toString().getChars(position, newPosition, dest, off); - position = newPosition; - return this; - } - - public boolean isDirect() { - return false; - } - - public boolean isReadOnly() { - return true; - } - - public ByteOrder order() { - return ByteOrder.nativeOrder(); - } - - protected char[] protectedArray() { - throw new UnsupportedOperationException(); - } - - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public CharBuffer put(char c) { - throw new ReadOnlyBufferException(); - } - - public CharBuffer put(int index, char c) { - throw new ReadOnlyBufferException(); - } - - public final CharBuffer put(char[] src, int off, int len) { - if ((off < 0 ) || (len < 0) || (long)off + (long)len > src.length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - - throw new ReadOnlyBufferException(); - } - - public CharBuffer put(String src, int start, int end) { - if ((start < 0 ) || (end < 0) || (long)start + (long)end > src.length()) { - throw new IndexOutOfBoundsException(); - } - throw new ReadOnlyBufferException(); - } - - public CharBuffer slice() { - return new CharSequenceAdapter(sequence.subSequence(position, limit)); - } - - public CharSequence subSequence(int start, int end) { - if (end < start || start < 0 || end > remaining()) { - throw new IndexOutOfBoundsException(); - } - - CharSequenceAdapter result = copy(this); - result.position = position + start; - result.limit = position + end; - return result; - } + static CharSequenceAdapter copy (CharSequenceAdapter other) { + CharSequenceAdapter buf = new CharSequenceAdapter(other.sequence); + buf.limit = other.limit; + buf.position = other.position; + buf.mark = other.mark; + return buf; + } + + final CharSequence sequence; + + CharSequenceAdapter (CharSequence chseq) { + super(chseq.length()); + sequence = chseq; + } + + public CharBuffer asReadOnlyBuffer () { + return duplicate(); + } + + public CharBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public CharBuffer duplicate () { + return copy(this); + } + + public char get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return sequence.charAt(position++); + } + + public char get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return sequence.charAt(index); + } + + public final CharBuffer get (char[] dest, int off, int len) { + int length = dest.length; + if ((off < 0) || (len < 0) || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + int newPosition = position + len; + sequence.toString().getChars(position, newPosition, dest, off); + position = newPosition; + return this; + } + + public boolean isDirect () { + return false; + } + + public boolean isReadOnly () { + return true; + } + + public ByteOrder order () { + return ByteOrder.nativeOrder(); + } + + protected char[] protectedArray () { + throw new UnsupportedOperationException(); + } + + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public CharBuffer put (char c) { + throw new ReadOnlyBufferException(); + } + + public CharBuffer put (int index, char c) { + throw new ReadOnlyBufferException(); + } + + public final CharBuffer put (char[] src, int off, int len) { + if ((off < 0) || (len < 0) || (long)off + (long)len > src.length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + + throw new ReadOnlyBufferException(); + } + + public CharBuffer put (String src, int start, int end) { + if ((start < 0) || (end < 0) || (long)start + (long)end > src.length()) { + throw new IndexOutOfBoundsException(); + } + throw new ReadOnlyBufferException(); + } + + public CharBuffer slice () { + return new CharSequenceAdapter(sequence.subSequence(position, limit)); + } + + public CharSequence subSequence (int start, int end) { + if (end < start || start < 0 || end > remaining()) { + throw new IndexOutOfBoundsException(); + } + + CharSequenceAdapter result = copy(this); + result.position = position + start; + result.limit = position + end; + return result; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharToByteBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharToByteBufferAdapter.java index 26ec475ce76..0f65cd43b41 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharToByteBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/CharToByteBufferAdapter.java @@ -19,198 +19,193 @@ //import org.apache.harmony.nio.internal.DirectBuffer; //import org.apache.harmony.luni.platform.PlatformAddress; -/** - * This class wraps a byte buffer to be a char buffer. +/** This class wraps a byte buffer to be a char buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ -final class CharToByteBufferAdapter extends CharBuffer { //implements DirectBuffer { - - static CharBuffer wrap(ByteBuffer byteBuffer) { - return new CharToByteBufferAdapter(byteBuffer.slice()); - } - - private final ByteBuffer byteBuffer; - - CharToByteBufferAdapter(ByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 1)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - } - -// public int getByteCapacity() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getByteCapacity(); -// } -// assert false : byteBuffer; -// return -1; -// } + *

    */ +final class CharToByteBufferAdapter extends CharBuffer { // implements DirectBuffer { + + static CharBuffer wrap (ByteBuffer byteBuffer) { + return new CharToByteBufferAdapter(byteBuffer.slice()); + } + + private final ByteBuffer byteBuffer; + + CharToByteBufferAdapter (ByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 1)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + } + +// public int getByteCapacity() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getByteCapacity(); +// } +// assert false : byteBuffer; +// return -1; +// } // -// public PlatformAddress getEffectiveAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getEffectiveAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public PlatformAddress getBaseAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getBaseAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getBaseAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getBaseAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public boolean isAddressValid() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).isAddressValid(); -// } -// assert false : byteBuffer; -// return false; -// } +// public boolean isAddressValid() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).isAddressValid(); +// } +// assert false : byteBuffer; +// return false; +// } // -// public void addressValidityCheck() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).addressValidityCheck(); -// } else { -// assert false : byteBuffer; -// } -// } +// public void addressValidityCheck() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).addressValidityCheck(); +// } else { +// assert false : byteBuffer; +// } +// } // -// public void free() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).free(); -// } else { -// assert false : byteBuffer; -// } -// } - - @Override - public CharBuffer asReadOnlyBuffer() { - CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer - .asReadOnlyBuffer()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public CharBuffer compact() { - if (byteBuffer.isReadOnly()) { - throw new ReadOnlyBufferException(); - } - byteBuffer.limit(limit << 1); - byteBuffer.position(position << 1); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public CharBuffer duplicate() { - CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer - .duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public char get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return byteBuffer.getChar(position++ << 1); - } - - @Override - public char get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return byteBuffer.getChar(index << 1); - } - - @Override - public boolean isDirect() { - return byteBuffer.isDirect(); - } - - @Override - public boolean isReadOnly() { - return byteBuffer.isReadOnly(); - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected char[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public CharBuffer put(char c) { - if (position == limit) { - throw new BufferOverflowException(); - } - byteBuffer.putChar(position++ << 1, c); - return this; - } - - @Override - public CharBuffer put(int index, char c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - byteBuffer.putChar(index << 1, c); - return this; - } - - @Override - public CharBuffer slice() { - byteBuffer.limit(limit << 1); - byteBuffer.position(position << 1); - CharBuffer result = new CharToByteBufferAdapter(byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - @Override - public CharSequence subSequence(int start, int end) { - if (start < 0 || end < start || end > remaining()) { - throw new IndexOutOfBoundsException(); - } - - CharBuffer result = duplicate(); - result.limit(position + end); - result.position(position + start); - return result; - } +// public void free() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).free(); +// } else { +// assert false : byteBuffer; +// } +// } + + @Override + public CharBuffer asReadOnlyBuffer () { + CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer.asReadOnlyBuffer()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public CharBuffer compact () { + if (byteBuffer.isReadOnly()) { + throw new ReadOnlyBufferException(); + } + byteBuffer.limit(limit << 1); + byteBuffer.position(position << 1); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public CharBuffer duplicate () { + CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public char get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return byteBuffer.getChar(position++ << 1); + } + + @Override + public char get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return byteBuffer.getChar(index << 1); + } + + @Override + public boolean isDirect () { + return byteBuffer.isDirect(); + } + + @Override + public boolean isReadOnly () { + return byteBuffer.isReadOnly(); + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected char[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public CharBuffer put (char c) { + if (position == limit) { + throw new BufferOverflowException(); + } + byteBuffer.putChar(position++ << 1, c); + return this; + } + + @Override + public CharBuffer put (int index, char c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + byteBuffer.putChar(index << 1, c); + return this; + } + + @Override + public CharBuffer slice () { + byteBuffer.limit(limit << 1); + byteBuffer.position(position << 1); + CharBuffer result = new CharToByteBufferAdapter(byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + @Override + public CharSequence subSequence (int start, int end) { + if (start < 0 || end < start || end > remaining()) { + throw new IndexOutOfBoundsException(); + } + + CharBuffer result = duplicate(); + result.limit(position + end); + result.position(position + start); + return result; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectByteBuffer.java index 522e56e1f14..6eda3eec27e 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectByteBuffer.java @@ -24,231 +24,226 @@ import com.google.gwt.corp.compatibility.Endianness; import com.google.gwt.corp.compatibility.Numbers; -/** - * DirectByteBuffer, DirectReadWriteByteBuffer and DirectReadOnlyHeapByteBuffer compose - * the implementation of direct byte buffers. +/** DirectByteBuffer, DirectReadWriteByteBuffer and DirectReadOnlyHeapByteBuffer compose the implementation of direct byte buffers. *

    - * DirectByteBuffer implements all the shared readonly methods and is extended by - * the other two classes. + * DirectByteBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class DirectByteBuffer extends BaseByteBuffer implements HasArrayBufferView { Int8Array byteArray; - DirectByteBuffer(int capacity) { - this(ArrayBuffer.create(capacity), capacity, 0); - } + DirectByteBuffer (int capacity) { + this(ArrayBuffer.create(capacity), capacity, 0); + } + + DirectByteBuffer (ArrayBuffer buf) { + this(buf, buf.getByteLength(), 0); + } - DirectByteBuffer(ArrayBuffer buf) { - this(buf, buf.getByteLength(), 0); - } - - DirectByteBuffer(ArrayBuffer buffer, int capacity, int offset) { - super(capacity); - byteArray = Int8Array.create(buffer, offset, capacity); - } + DirectByteBuffer (ArrayBuffer buffer, int capacity, int offset) { + super(capacity); + byteArray = Int8Array.create(buffer, offset, capacity); + } - public ArrayBufferView getTypedArray() { + public ArrayBufferView getTypedArray () { return byteArray; } - - public int getElementSize() { + + public int getElementSize () { return 1; } - /* - * Override ByteBuffer.get(byte[], int, int) to improve performance. - * - * (non-Javadoc) - * - * @see java.nio.ByteBuffer#get(byte[], int, int) - */ - public final ByteBuffer get(byte[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - - for (int i = 0; i < len; i++) { - dest[i + off] = get(position + i); - } - - position += len; - return this; - } - - public final byte get() { -// if (position == limit) { -// throw new BufferUnderflowException(); -// } - return (byte)byteArray.get(position++); - } - - public final byte get(int index) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - return (byte)byteArray.get(index); - } - - public final double getDouble() { - return Numbers.longBitsToDouble(getLong()); - } - - public final double getDouble(int index) { - return Numbers.longBitsToDouble(getLong(index)); - } - - public final float getFloat() { - return Numbers.intBitsToFloat(getInt()); - } - - public final float getFloat(int index) { - return Numbers.intBitsToFloat(getInt(index)); - } - - public final int getInt() { - int newPosition = position + 4; -// if (newPosition > limit) { -// throw new BufferUnderflowException(); -// } - int result = loadInt(position); - position = newPosition; - return result; - } - - public final int getInt(int index) { -// if (index < 0 || index + 4 > limit) { -// throw new IndexOutOfBoundsException(); -// } - return loadInt(index); - } - - public final long getLong() { - int newPosition = position + 8; -// if (newPosition > limit) { -// throw new BufferUnderflowException(); -// } - long result = loadLong(position); - position = newPosition; - return result; - } - - public final long getLong(int index) { -// if (index < 0 || index + 8 > limit) { -// throw new IndexOutOfBoundsException(); -// } - return loadLong(index); - } - - public final short getShort() { - int newPosition = position + 2; -// if (newPosition > limit) { -// throw new BufferUnderflowException(); -// } - short result = loadShort(position); - position = newPosition; - return result; - } - - public final short getShort(int index) { -// if (index < 0 || index + 2 > limit) { -// throw new IndexOutOfBoundsException(); -// } - return loadShort(index); - } - - public final boolean isDirect() { - return false; - } - - protected final int loadInt(int baseOffset) { - int bytes = 0; - if(order == Endianness.BIG_ENDIAN){ - for (int i = 0; i < 4; i++) { - bytes = bytes << 8; - bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); - } - }else{ - for (int i = 3; i >= 0; i--) { - bytes = bytes << 8; - bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); - } - } - return bytes; - } - - protected final long loadLong(int baseOffset) { - long bytes = 0; - if(order == Endianness.BIG_ENDIAN){ - for (int i = 0; i < 8; i++) { - bytes = bytes << 8; - bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); - } - }else{ - for (int i = 7; i >= 0; i--) { - bytes = bytes << 8; - bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); - } - } - return bytes; - } - - protected final short loadShort(int baseOffset) { - short bytes = 0; - if(order == Endianness.BIG_ENDIAN){ - bytes = (short) (byteArray.get(baseOffset) << 8); - bytes |= (byteArray.get(baseOffset + 1) & 0xFF); - }else{ - bytes = (short) (byteArray.get(baseOffset+1) << 8); - bytes |= (byteArray.get(baseOffset) & 0xFF); - } - return bytes; - } - - protected final void store(int baseOffset, int value) { - if (order == Endianness.BIG_ENDIAN) { - for (int i = 3; i >= 0; i--) { - byteArray.set(baseOffset + i, (byte) (value & 0xFF)); - value = value >> 8; - } - } else { - for (int i = 0; i <= 3; i++) { - byteArray.set(baseOffset + i, (byte) (value & 0xFF)); - value = value >> 8; - } - } - } - - protected final void store(int baseOffset, long value) { - if (order == Endianness.BIG_ENDIAN) { - for (int i = 7; i >= 0; i--) { - byteArray.set(baseOffset + i, (byte) (value & 0xFF)); - value = value >> 8; - } - } else { - for (int i = 0; i <= 7; i++) { - byteArray.set(baseOffset + i, (byte) (value & 0xFF)); - value = value >> 8; - } - } - } - - protected final void store(int baseOffset, short value) { - if (order == Endianness.BIG_ENDIAN) { - byteArray.set(baseOffset, (byte) ((value >> 8) & 0xFF)); - byteArray.set(baseOffset + 1, (byte) (value & 0xFF)); - } else { - byteArray.set(baseOffset+1, (byte) ((value >> 8) & 0xFF)); - byteArray.set(baseOffset, (byte) (value & 0xFF)); - } - } -} \ No newline at end of file + /* + * Override ByteBuffer.get(byte[], int, int) to improve performance. + * + * (non-Javadoc) + * + * @see java.nio.ByteBuffer#get(byte[], int, int) + */ + public final ByteBuffer get (byte[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + + for (int i = 0; i < len; i++) { + dest[i + off] = get(position + i); + } + + position += len; + return this; + } + + public final byte get () { +// if (position == limit) { +// throw new BufferUnderflowException(); +// } + return (byte)byteArray.get(position++); + } + + public final byte get (int index) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + return (byte)byteArray.get(index); + } + + public final double getDouble () { + return Numbers.longBitsToDouble(getLong()); + } + + public final double getDouble (int index) { + return Numbers.longBitsToDouble(getLong(index)); + } + + public final float getFloat () { + return Numbers.intBitsToFloat(getInt()); + } + + public final float getFloat (int index) { + return Numbers.intBitsToFloat(getInt(index)); + } + + public final int getInt () { + int newPosition = position + 4; +// if (newPosition > limit) { +// throw new BufferUnderflowException(); +// } + int result = loadInt(position); + position = newPosition; + return result; + } + + public final int getInt (int index) { +// if (index < 0 || index + 4 > limit) { +// throw new IndexOutOfBoundsException(); +// } + return loadInt(index); + } + + public final long getLong () { + int newPosition = position + 8; +// if (newPosition > limit) { +// throw new BufferUnderflowException(); +// } + long result = loadLong(position); + position = newPosition; + return result; + } + + public final long getLong (int index) { +// if (index < 0 || index + 8 > limit) { +// throw new IndexOutOfBoundsException(); +// } + return loadLong(index); + } + + public final short getShort () { + int newPosition = position + 2; +// if (newPosition > limit) { +// throw new BufferUnderflowException(); +// } + short result = loadShort(position); + position = newPosition; + return result; + } + + public final short getShort (int index) { +// if (index < 0 || index + 2 > limit) { +// throw new IndexOutOfBoundsException(); +// } + return loadShort(index); + } + + public final boolean isDirect () { + return false; + } + + protected final int loadInt (int baseOffset) { + int bytes = 0; + if (order == Endianness.BIG_ENDIAN) { + for (int i = 0; i < 4; i++) { + bytes = bytes << 8; + bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); + } + } else { + for (int i = 3; i >= 0; i--) { + bytes = bytes << 8; + bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); + } + } + return bytes; + } + + protected final long loadLong (int baseOffset) { + long bytes = 0; + if (order == Endianness.BIG_ENDIAN) { + for (int i = 0; i < 8; i++) { + bytes = bytes << 8; + bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); + } + } else { + for (int i = 7; i >= 0; i--) { + bytes = bytes << 8; + bytes = bytes | (byteArray.get(baseOffset + i) & 0xFF); + } + } + return bytes; + } + + protected final short loadShort (int baseOffset) { + short bytes = 0; + if (order == Endianness.BIG_ENDIAN) { + bytes = (short)(byteArray.get(baseOffset) << 8); + bytes |= (byteArray.get(baseOffset + 1) & 0xFF); + } else { + bytes = (short)(byteArray.get(baseOffset + 1) << 8); + bytes |= (byteArray.get(baseOffset) & 0xFF); + } + return bytes; + } + + protected final void store (int baseOffset, int value) { + if (order == Endianness.BIG_ENDIAN) { + for (int i = 3; i >= 0; i--) { + byteArray.set(baseOffset + i, (byte)(value & 0xFF)); + value = value >> 8; + } + } else { + for (int i = 0; i <= 3; i++) { + byteArray.set(baseOffset + i, (byte)(value & 0xFF)); + value = value >> 8; + } + } + } + + protected final void store (int baseOffset, long value) { + if (order == Endianness.BIG_ENDIAN) { + for (int i = 7; i >= 0; i--) { + byteArray.set(baseOffset + i, (byte)(value & 0xFF)); + value = value >> 8; + } + } else { + for (int i = 0; i <= 7; i++) { + byteArray.set(baseOffset + i, (byte)(value & 0xFF)); + value = value >> 8; + } + } + } + + protected final void store (int baseOffset, short value) { + if (order == Endianness.BIG_ENDIAN) { + byteArray.set(baseOffset, (byte)((value >> 8) & 0xFF)); + byteArray.set(baseOffset + 1, (byte)(value & 0xFF)); + } else { + byteArray.set(baseOffset + 1, (byte)((value >> 8) & 0xFF)); + byteArray.set(baseOffset, (byte)(value & 0xFF)); + } + } +} diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyByteBuffer.java index 9033dc734c2..6ff797e908b 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyByteBuffer.java @@ -19,138 +19,129 @@ import gwt.g3d.client.gl2.array.ArrayBuffer; -/** - * HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose - * the implementation of array based byte buffers. +/** HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose the implementation of array based byte buffers. *

    - * ReadOnlyHeapByteBuffer extends HeapByteBuffer with all the write methods - * throwing read only exception. + * ReadOnlyHeapByteBuffer extends HeapByteBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class DirectReadOnlyByteBuffer extends DirectByteBuffer { - static DirectReadOnlyByteBuffer copy(DirectByteBuffer other, int markOfOther) { - DirectReadOnlyByteBuffer buf = new DirectReadOnlyByteBuffer( - other.byteArray.getBuffer(), other.capacity(), other.byteArray.getByteOffset()); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - buf.order(other.order()); - return buf; - } - - DirectReadOnlyByteBuffer(ArrayBuffer backingArray, int capacity, int arrayOffset) { - super(backingArray, capacity, arrayOffset); - } - - public ByteBuffer asReadOnlyBuffer() { - return copy(this, mark); - } - - public ByteBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected byte[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public FloatBuffer asFloatBuffer() { - return DirectReadOnlyFloatBufferAdapter.wrap(this); - } - - public IntBuffer asIntBuffer() { - return order() == ByteOrder.nativeOrder() - ? DirectReadOnlyIntBufferAdapter.wrap(this) - : super.asIntBuffer(); - } - - public ShortBuffer asShortBuffer() { - return order() == ByteOrder.nativeOrder() - ? DirectReadOnlyShortBufferAdapter.wrap(this) - : super.asShortBuffer(); - } - - public ByteBuffer put(byte b) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer put(int index, byte b) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer put(byte[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putDouble(double value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putDouble(int index, double value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putFloat(float value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putFloat(int index, float value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putInt(int value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putInt(int index, int value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putLong(int index, long value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putLong(long value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putShort(int index, short value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putShort(short value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer put(ByteBuffer buf) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer slice() { - DirectReadOnlyByteBuffer slice = new DirectReadOnlyByteBuffer(byteArray.getBuffer(), - remaining(), byteArray.getByteOffset() + position); - slice.order = order; - return slice; - } + static DirectReadOnlyByteBuffer copy (DirectByteBuffer other, int markOfOther) { + DirectReadOnlyByteBuffer buf = new DirectReadOnlyByteBuffer(other.byteArray.getBuffer(), other.capacity(), + other.byteArray.getByteOffset()); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + buf.order(other.order()); + return buf; + } + + DirectReadOnlyByteBuffer (ArrayBuffer backingArray, int capacity, int arrayOffset) { + super(backingArray, capacity, arrayOffset); + } + + public ByteBuffer asReadOnlyBuffer () { + return copy(this, mark); + } + + public ByteBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected byte[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public FloatBuffer asFloatBuffer () { + return DirectReadOnlyFloatBufferAdapter.wrap(this); + } + + public IntBuffer asIntBuffer () { + return order() == ByteOrder.nativeOrder() ? DirectReadOnlyIntBufferAdapter.wrap(this) : super.asIntBuffer(); + } + + public ShortBuffer asShortBuffer () { + return order() == ByteOrder.nativeOrder() ? DirectReadOnlyShortBufferAdapter.wrap(this) : super.asShortBuffer(); + } + + public ByteBuffer put (byte b) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer put (int index, byte b) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer put (byte[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putDouble (double value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putDouble (int index, double value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putFloat (float value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putFloat (int index, float value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putInt (int value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putInt (int index, int value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putLong (int index, long value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putLong (long value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putShort (int index, short value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putShort (short value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer put (ByteBuffer buf) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer slice () { + DirectReadOnlyByteBuffer slice = new DirectReadOnlyByteBuffer(byteArray.getBuffer(), remaining(), byteArray.getByteOffset() + + position); + slice.order = order; + return slice; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyFloatBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyFloatBufferAdapter.java index cc50b094e32..f33e8fa6197 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyFloatBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyFloatBufferAdapter.java @@ -19,131 +19,126 @@ import gwt.g3d.client.gl2.array.ArrayBufferView; import gwt.g3d.client.gl2.array.Float32Array; -/** - * This class wraps a byte buffer to be a float buffer. +/** This class wraps a byte buffer to be a float buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class DirectReadOnlyFloatBufferAdapter extends FloatBuffer implements HasArrayBufferView { -//implements DirectBuffer { - - static FloatBuffer wrap(DirectByteBuffer byteBuffer) { - return new DirectReadOnlyFloatBufferAdapter((DirectByteBuffer) byteBuffer.slice()); - } - - private final DirectByteBuffer byteBuffer; - private final Float32Array floatArray; - - DirectReadOnlyFloatBufferAdapter(DirectByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 2)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - this.floatArray = Float32Array.create(byteBuffer.byteArray.getBuffer(), - byteBuffer.byteArray.getByteOffset(), - capacity); - } - - @Override - public FloatBuffer asReadOnlyBuffer() { - DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public FloatBuffer compact() { - throw new ReadOnlyBufferException(); - } - - @Override - public FloatBuffer duplicate() { - DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter( - (DirectByteBuffer) byteBuffer.duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public float get() { -// if (position == limit) { -// throw new BufferUnderflowException(); -// } - return floatArray.get(position++); - } - - @Override - public float get(int index) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - return floatArray.get(index); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public boolean isReadOnly() { - return true; - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - float[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override boolean protectedHasArray() { - return false; - } - - @Override - public FloatBuffer put(float c) { - throw new ReadOnlyBufferException(); - } - - @Override - public FloatBuffer put(int index, float c) { - throw new ReadOnlyBufferException(); - } - - @Override - public FloatBuffer slice() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - FloatBuffer result = new DirectReadOnlyFloatBufferAdapter((DirectByteBuffer) byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ArrayBufferView getTypedArray() { +// implements DirectBuffer { + + static FloatBuffer wrap (DirectByteBuffer byteBuffer) { + return new DirectReadOnlyFloatBufferAdapter((DirectByteBuffer)byteBuffer.slice()); + } + + private final DirectByteBuffer byteBuffer; + private final Float32Array floatArray; + + DirectReadOnlyFloatBufferAdapter (DirectByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 2)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + this.floatArray = Float32Array.create(byteBuffer.byteArray.getBuffer(), byteBuffer.byteArray.getByteOffset(), capacity); + } + + @Override + public FloatBuffer asReadOnlyBuffer () { + DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public FloatBuffer compact () { + throw new ReadOnlyBufferException(); + } + + @Override + public FloatBuffer duplicate () { + DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter((DirectByteBuffer)byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public float get () { +// if (position == limit) { +// throw new BufferUnderflowException(); +// } + return floatArray.get(position++); + } + + @Override + public float get (int index) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + return floatArray.get(index); + } + + @Override + public boolean isDirect () { + return true; + } + + @Override + public boolean isReadOnly () { + return true; + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + float[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + boolean protectedHasArray () { + return false; + } + + @Override + public FloatBuffer put (float c) { + throw new ReadOnlyBufferException(); + } + + @Override + public FloatBuffer put (int index, float c) { + throw new ReadOnlyBufferException(); + } + + @Override + public FloatBuffer slice () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + FloatBuffer result = new DirectReadOnlyFloatBufferAdapter((DirectByteBuffer)byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ArrayBufferView getTypedArray () { return floatArray; } - public int getElementSize() { + public int getElementSize () { return 4; } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyIntBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyIntBufferAdapter.java index 05ae39ea08c..745366132f9 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyIntBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyIntBufferAdapter.java @@ -19,132 +19,126 @@ import gwt.g3d.client.gl2.array.ArrayBufferView; import gwt.g3d.client.gl2.array.Int32Array; -/** - * This class wraps a byte buffer to be a int buffer. +/** This class wraps a byte buffer to be a int buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class DirectReadOnlyIntBufferAdapter extends IntBuffer implements HasArrayBufferView { -//implements DirectBuffer { - - static IntBuffer wrap(DirectByteBuffer byteBuffer) { - return new DirectReadOnlyIntBufferAdapter((DirectByteBuffer) byteBuffer.slice()); - } - - private final DirectByteBuffer byteBuffer; - private final Int32Array intArray; - - DirectReadOnlyIntBufferAdapter(DirectByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 2)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - this.intArray = Int32Array.create(byteBuffer.byteArray.getBuffer(), - byteBuffer.byteArray.getByteOffset(), - capacity); - } - - @Override - public IntBuffer asReadOnlyBuffer() { - DirectReadOnlyIntBufferAdapter buf = new DirectReadOnlyIntBufferAdapter(byteBuffer); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public IntBuffer compact() { - throw new ReadOnlyBufferException(); - } - - @Override - public IntBuffer duplicate() { - DirectReadOnlyIntBufferAdapter buf = new DirectReadOnlyIntBufferAdapter( - (DirectByteBuffer) byteBuffer.duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public int get() { -// if (position == limit) { -// throw new BufferUnderflowException(); -// } - return intArray.get(position++); - } - - @Override - public int get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return intArray.get(index); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public boolean isReadOnly() { - return true; - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected int[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public IntBuffer put(int c) { - throw new ReadOnlyBufferException(); - } - - @Override - public IntBuffer put(int index, int c) { - throw new ReadOnlyBufferException(); - } - - @Override - public IntBuffer slice() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - IntBuffer result = new DirectReadOnlyIntBufferAdapter((DirectByteBuffer) byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ArrayBufferView getTypedArray() { +// implements DirectBuffer { + + static IntBuffer wrap (DirectByteBuffer byteBuffer) { + return new DirectReadOnlyIntBufferAdapter((DirectByteBuffer)byteBuffer.slice()); + } + + private final DirectByteBuffer byteBuffer; + private final Int32Array intArray; + + DirectReadOnlyIntBufferAdapter (DirectByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 2)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + this.intArray = Int32Array.create(byteBuffer.byteArray.getBuffer(), byteBuffer.byteArray.getByteOffset(), capacity); + } + + @Override + public IntBuffer asReadOnlyBuffer () { + DirectReadOnlyIntBufferAdapter buf = new DirectReadOnlyIntBufferAdapter(byteBuffer); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public IntBuffer compact () { + throw new ReadOnlyBufferException(); + } + + @Override + public IntBuffer duplicate () { + DirectReadOnlyIntBufferAdapter buf = new DirectReadOnlyIntBufferAdapter((DirectByteBuffer)byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public int get () { +// if (position == limit) { +// throw new BufferUnderflowException(); +// } + return intArray.get(position++); + } + + @Override + public int get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return intArray.get(index); + } + + @Override + public boolean isDirect () { + return true; + } + + @Override + public boolean isReadOnly () { + return true; + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected int[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public IntBuffer put (int c) { + throw new ReadOnlyBufferException(); + } + + @Override + public IntBuffer put (int index, int c) { + throw new ReadOnlyBufferException(); + } + + @Override + public IntBuffer slice () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + IntBuffer result = new DirectReadOnlyIntBufferAdapter((DirectByteBuffer)byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ArrayBufferView getTypedArray () { return intArray; } - public int getElementSize() { + public int getElementSize () { return 4; } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyShortBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyShortBufferAdapter.java index 8aed5da4c73..0ba252522a2 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyShortBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyShortBufferAdapter.java @@ -19,131 +19,125 @@ import gwt.g3d.client.gl2.array.ArrayBufferView; import gwt.g3d.client.gl2.array.Int16Array; -/** - * This class wraps a byte buffer to be a short buffer. +/** This class wraps a byte buffer to be a short buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class DirectReadOnlyShortBufferAdapter extends ShortBuffer implements HasArrayBufferView { - static ShortBuffer wrap(DirectByteBuffer byteBuffer) { - return new DirectReadOnlyShortBufferAdapter((DirectByteBuffer) byteBuffer.slice()); - } - - private final DirectByteBuffer byteBuffer; - private final Int16Array shortArray; - - DirectReadOnlyShortBufferAdapter(DirectByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 1)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - this.shortArray = Int16Array.create(byteBuffer.byteArray.getBuffer(), - byteBuffer.byteArray.getByteOffset(), - capacity); - } - - @Override - public ShortBuffer asReadOnlyBuffer() { - DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter(byteBuffer); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public ShortBuffer compact() { - throw new ReadOnlyBufferException(); - } - - @Override - public ShortBuffer duplicate() { - DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter( - (DirectByteBuffer) byteBuffer.duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public short get() { -// if (position == limit) { -// throw new BufferUnderflowException(); -// } - return (short)shortArray.get(position++); - } - - @Override - public short get(int index) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - return (short)shortArray.get(index); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public boolean isReadOnly() { - return true; - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected short[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public ShortBuffer put(short c) { - throw new ReadOnlyBufferException(); - } - - @Override - public ShortBuffer put(int index, short c) { - throw new ReadOnlyBufferException(); - } - - @Override - public ShortBuffer slice() { - byteBuffer.limit(limit << 1); - byteBuffer.position(position << 1); - ShortBuffer result = new DirectReadOnlyShortBufferAdapter((DirectByteBuffer) byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ArrayBufferView getTypedArray() { + static ShortBuffer wrap (DirectByteBuffer byteBuffer) { + return new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.slice()); + } + + private final DirectByteBuffer byteBuffer; + private final Int16Array shortArray; + + DirectReadOnlyShortBufferAdapter (DirectByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 1)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + this.shortArray = Int16Array.create(byteBuffer.byteArray.getBuffer(), byteBuffer.byteArray.getByteOffset(), capacity); + } + + @Override + public ShortBuffer asReadOnlyBuffer () { + DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter(byteBuffer); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public ShortBuffer compact () { + throw new ReadOnlyBufferException(); + } + + @Override + public ShortBuffer duplicate () { + DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public short get () { +// if (position == limit) { +// throw new BufferUnderflowException(); +// } + return (short)shortArray.get(position++); + } + + @Override + public short get (int index) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + return (short)shortArray.get(index); + } + + @Override + public boolean isDirect () { + return true; + } + + @Override + public boolean isReadOnly () { + return true; + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected short[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public ShortBuffer put (short c) { + throw new ReadOnlyBufferException(); + } + + @Override + public ShortBuffer put (int index, short c) { + throw new ReadOnlyBufferException(); + } + + @Override + public ShortBuffer slice () { + byteBuffer.limit(limit << 1); + byteBuffer.position(position << 1); + ShortBuffer result = new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ArrayBufferView getTypedArray () { return shortArray; } - public int getElementSize() { + public int getElementSize () { return 2; } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteByteBuffer.java index 9cf19a04514..f5959278fce 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteByteBuffer.java @@ -20,210 +20,202 @@ import com.google.gwt.corp.compatibility.Numbers; -/** - * DirectByteBuffer, DirectReadWriteByteBuffer and DirectReadOnlyByteBuffer compose - * the implementation of direct byte buffers. +/** DirectByteBuffer, DirectReadWriteByteBuffer and DirectReadOnlyByteBuffer compose the implementation of direct byte buffers. *

    * DirectReadWriteByteBuffer extends DirectByteBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class DirectReadWriteByteBuffer extends DirectByteBuffer { - static DirectReadWriteByteBuffer copy(DirectByteBuffer other, int markOfOther) { - DirectReadWriteByteBuffer buf = new DirectReadWriteByteBuffer( - other.byteArray.getBuffer(), other.capacity(), other.byteArray.getByteOffset()); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - buf.order(other.order()); - return buf; - } - - DirectReadWriteByteBuffer(ArrayBuffer backingArray) { - super(backingArray); - } - - DirectReadWriteByteBuffer(int capacity) { - super(capacity); - } - - DirectReadWriteByteBuffer(ArrayBuffer backingArray, int capacity, int arrayOffset) { - super(backingArray, capacity, arrayOffset); - } - - public FloatBuffer asFloatBuffer() { - return DirectReadWriteFloatBufferAdapter.wrap(this); - } - - public IntBuffer asIntBuffer() { - return order() == ByteOrder.nativeOrder() - ? DirectReadWriteIntBufferAdapter.wrap(this) - : super.asIntBuffer(); - } - - public ShortBuffer asShortBuffer() { - return order() == ByteOrder.nativeOrder() - ? DirectReadWriteShortBufferAdapter.wrap(this) - : super.asShortBuffer(); - } - - public ByteBuffer asReadOnlyBuffer() { - return DirectReadOnlyByteBuffer.copy(this, mark); - } - - public ByteBuffer compact() { -// System.arraycopy(backingArray, position + offset, backingArray, offset, -// remaining()); - - int rem = remaining(); - for (int i = 0; i < rem; i++) { - byteArray.set(i, byteArray.get(position + i)); - } - - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public ByteBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected byte[] protectedArray() { - throw new UnsupportedOperationException(); - } - - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - protected boolean protectedHasArray() { - return true; - } - - public ByteBuffer put(byte b) { -// if (position == limit) { -// throw new BufferOverflowException(); -// } - byteArray.set(position++, b); - return this; - } - - public ByteBuffer put(int index, byte b) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - byteArray.set(index, b); - return this; - } - - /* - * Override ByteBuffer.put(byte[], int, int) to improve performance. - * - * (non-Javadoc) - * - * @see java.nio.ByteBuffer#put(byte[], int, int) - */ - public ByteBuffer put(byte[] src, int off, int len) { - if (off < 0 || len < 0 || (long)off + (long)len > src.length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - if (isReadOnly()) { - throw new ReadOnlyBufferException(); - } - for (int i = 0; i < len; i++) { - byteArray.set(i + position, src[off + i]); - } - position += len; - return this; - } - - public ByteBuffer putDouble(double value) { - return putLong(Numbers.doubleToRawLongBits(value)); - } - - public ByteBuffer putDouble(int index, double value) { - return putLong(index, Numbers.doubleToRawLongBits(value)); - } - - public ByteBuffer putFloat(float value) { - return putInt(Numbers.floatToIntBits(value)); - } - - public ByteBuffer putFloat(int index, float value) { - return putInt(index, Numbers.floatToIntBits(value)); - } - - public ByteBuffer putInt(int value) { - int newPosition = position + 4; -// if (newPosition > limit) { -// throw new BufferOverflowException(); -// } - store(position, value); - position = newPosition; - return this; - } - - public ByteBuffer putInt(int index, int value) { -// if (index < 0 || (long)index + 4 > limit) { -// throw new IndexOutOfBoundsException(); -// } - store(index, value); - return this; - } - - public ByteBuffer putLong(int index, long value) { -// if (index < 0 || (long)index + 8 > limit) { -// throw new IndexOutOfBoundsException(); -// } - store(index, value); - return this; - } - - public ByteBuffer putLong(long value) { - int newPosition = position + 8; -// if (newPosition > limit) { -// throw new BufferOverflowException(); -// } - store(position, value); - position = newPosition; - return this; - } - - public ByteBuffer putShort(int index, short value) { -// if (index < 0 || (long)index + 2 > limit) { -// throw new IndexOutOfBoundsException(); -// } - store(index, value); - return this; - } - - public ByteBuffer putShort(short value) { - int newPosition = position + 2; -// if (newPosition > limit) { -// throw new BufferOverflowException(); -// } - store(position, value); - position = newPosition; - return this; - } - - public ByteBuffer slice() { - DirectReadWriteByteBuffer slice = new DirectReadWriteByteBuffer( - byteArray.getBuffer(), remaining(), byteArray.getByteOffset() + position); - slice.order = order; - return slice; - } + static DirectReadWriteByteBuffer copy (DirectByteBuffer other, int markOfOther) { + DirectReadWriteByteBuffer buf = new DirectReadWriteByteBuffer(other.byteArray.getBuffer(), other.capacity(), + other.byteArray.getByteOffset()); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + buf.order(other.order()); + return buf; + } + + DirectReadWriteByteBuffer (ArrayBuffer backingArray) { + super(backingArray); + } + + DirectReadWriteByteBuffer (int capacity) { + super(capacity); + } + + DirectReadWriteByteBuffer (ArrayBuffer backingArray, int capacity, int arrayOffset) { + super(backingArray, capacity, arrayOffset); + } + + public FloatBuffer asFloatBuffer () { + return DirectReadWriteFloatBufferAdapter.wrap(this); + } + + public IntBuffer asIntBuffer () { + return order() == ByteOrder.nativeOrder() ? DirectReadWriteIntBufferAdapter.wrap(this) : super.asIntBuffer(); + } + + public ShortBuffer asShortBuffer () { + return order() == ByteOrder.nativeOrder() ? DirectReadWriteShortBufferAdapter.wrap(this) : super.asShortBuffer(); + } + + public ByteBuffer asReadOnlyBuffer () { + return DirectReadOnlyByteBuffer.copy(this, mark); + } + + public ByteBuffer compact () { +// System.arraycopy(backingArray, position + offset, backingArray, offset, +// remaining()); + + int rem = remaining(); + for (int i = 0; i < rem; i++) { + byteArray.set(i, byteArray.get(position + i)); + } + + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public ByteBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected byte[] protectedArray () { + throw new UnsupportedOperationException(); + } + + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + protected boolean protectedHasArray () { + return true; + } + + public ByteBuffer put (byte b) { +// if (position == limit) { +// throw new BufferOverflowException(); +// } + byteArray.set(position++, b); + return this; + } + + public ByteBuffer put (int index, byte b) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + byteArray.set(index, b); + return this; + } + + /* + * Override ByteBuffer.put(byte[], int, int) to improve performance. + * + * (non-Javadoc) + * + * @see java.nio.ByteBuffer#put(byte[], int, int) + */ + public ByteBuffer put (byte[] src, int off, int len) { + if (off < 0 || len < 0 || (long)off + (long)len > src.length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + if (isReadOnly()) { + throw new ReadOnlyBufferException(); + } + for (int i = 0; i < len; i++) { + byteArray.set(i + position, src[off + i]); + } + position += len; + return this; + } + + public ByteBuffer putDouble (double value) { + return putLong(Numbers.doubleToRawLongBits(value)); + } + + public ByteBuffer putDouble (int index, double value) { + return putLong(index, Numbers.doubleToRawLongBits(value)); + } + + public ByteBuffer putFloat (float value) { + return putInt(Numbers.floatToIntBits(value)); + } + + public ByteBuffer putFloat (int index, float value) { + return putInt(index, Numbers.floatToIntBits(value)); + } + + public ByteBuffer putInt (int value) { + int newPosition = position + 4; +// if (newPosition > limit) { +// throw new BufferOverflowException(); +// } + store(position, value); + position = newPosition; + return this; + } + + public ByteBuffer putInt (int index, int value) { +// if (index < 0 || (long)index + 4 > limit) { +// throw new IndexOutOfBoundsException(); +// } + store(index, value); + return this; + } + + public ByteBuffer putLong (int index, long value) { +// if (index < 0 || (long)index + 8 > limit) { +// throw new IndexOutOfBoundsException(); +// } + store(index, value); + return this; + } + + public ByteBuffer putLong (long value) { + int newPosition = position + 8; +// if (newPosition > limit) { +// throw new BufferOverflowException(); +// } + store(position, value); + position = newPosition; + return this; + } + + public ByteBuffer putShort (int index, short value) { +// if (index < 0 || (long)index + 2 > limit) { +// throw new IndexOutOfBoundsException(); +// } + store(index, value); + return this; + } + + public ByteBuffer putShort (short value) { + int newPosition = position + 2; +// if (newPosition > limit) { +// throw new BufferOverflowException(); +// } + store(position, value); + position = newPosition; + return this; + } + + public ByteBuffer slice () { + DirectReadWriteByteBuffer slice = new DirectReadWriteByteBuffer(byteArray.getBuffer(), remaining(), + byteArray.getByteOffset() + position); + slice.order = order; + return slice; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java index cc4878027bf..ad208eae637 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java @@ -19,149 +19,143 @@ import gwt.g3d.client.gl2.array.ArrayBufferView; import gwt.g3d.client.gl2.array.Float32Array; -/** - * This class wraps a byte buffer to be a float buffer. +/** This class wraps a byte buffer to be a float buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class DirectReadWriteFloatBufferAdapter extends FloatBuffer implements HasArrayBufferView { -//implements DirectBuffer { - - static FloatBuffer wrap(DirectReadWriteByteBuffer byteBuffer) { - return new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer) byteBuffer.slice()); - } - - private final DirectReadWriteByteBuffer byteBuffer; - private final Float32Array floatArray; - - DirectReadWriteFloatBufferAdapter(DirectReadWriteByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 2)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - this.floatArray = Float32Array.create(byteBuffer.byteArray.getBuffer(), - byteBuffer.byteArray.getByteOffset(), - capacity); - } - - // TODO(haustein) This will be slow - @Override - public FloatBuffer asReadOnlyBuffer() { - DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public FloatBuffer compact() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public FloatBuffer duplicate() { - DirectReadWriteFloatBufferAdapter buf = new DirectReadWriteFloatBufferAdapter( - (DirectReadWriteByteBuffer) byteBuffer.duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public float get() { -// if (position == limit) { -// throw new BufferUnderflowException(); -// } - return floatArray.get(position++); - } - - @Override - public float get(int index) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - return floatArray.get(index); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected float[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public FloatBuffer put(float c) { -// if (position == limit) { -// throw new BufferOverflowException(); -// } - floatArray.set(position++, c); - return this; - } - - @Override - public FloatBuffer put(int index, float c) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - floatArray.set(index, c); - return this; - } - - @Override - public FloatBuffer slice() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - FloatBuffer result = new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer) - byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ArrayBufferView getTypedArray() { +// implements DirectBuffer { + + static FloatBuffer wrap (DirectReadWriteByteBuffer byteBuffer) { + return new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); + } + + private final DirectReadWriteByteBuffer byteBuffer; + private final Float32Array floatArray; + + DirectReadWriteFloatBufferAdapter (DirectReadWriteByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 2)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + this.floatArray = Float32Array.create(byteBuffer.byteArray.getBuffer(), byteBuffer.byteArray.getByteOffset(), capacity); + } + + // TODO(haustein) This will be slow + @Override + public FloatBuffer asReadOnlyBuffer () { + DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public FloatBuffer compact () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public FloatBuffer duplicate () { + DirectReadWriteFloatBufferAdapter buf = new DirectReadWriteFloatBufferAdapter( + (DirectReadWriteByteBuffer)byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public float get () { +// if (position == limit) { +// throw new BufferUnderflowException(); +// } + return floatArray.get(position++); + } + + @Override + public float get (int index) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + return floatArray.get(index); + } + + @Override + public boolean isDirect () { + return true; + } + + @Override + public boolean isReadOnly () { + return false; + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected float[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public FloatBuffer put (float c) { +// if (position == limit) { +// throw new BufferOverflowException(); +// } + floatArray.set(position++, c); + return this; + } + + @Override + public FloatBuffer put (int index, float c) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + floatArray.set(index, c); + return this; + } + + @Override + public FloatBuffer slice () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + FloatBuffer result = new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ArrayBufferView getTypedArray () { return floatArray; } - public int getElementSize() { + public int getElementSize () { return 4; } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteIntBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteIntBufferAdapter.java index c3f6bddd12c..c79da9f6dc9 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteIntBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteIntBufferAdapter.java @@ -19,149 +19,141 @@ import gwt.g3d.client.gl2.array.ArrayBufferView; import gwt.g3d.client.gl2.array.Int32Array; -/** - * This class wraps a byte buffer to be a int buffer. +/** This class wraps a byte buffer to be a int buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class DirectReadWriteIntBufferAdapter extends IntBuffer implements HasArrayBufferView { - static IntBuffer wrap(DirectReadWriteByteBuffer byteBuffer) { - return new DirectReadWriteIntBufferAdapter((DirectReadWriteByteBuffer) byteBuffer.slice()); - } - - private final DirectReadWriteByteBuffer byteBuffer; - private final Int32Array intArray; - - DirectReadWriteIntBufferAdapter(DirectReadWriteByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 2)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - this.intArray = Int32Array.create(byteBuffer.byteArray.getBuffer(), - byteBuffer.byteArray.getByteOffset(), - capacity); - } - - // TODO(haustein) This will be slow - @Override - public IntBuffer asReadOnlyBuffer() { - DirectReadOnlyIntBufferAdapter buf = new DirectReadOnlyIntBufferAdapter(byteBuffer); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public IntBuffer compact() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public IntBuffer duplicate() { - DirectReadWriteIntBufferAdapter buf = new DirectReadWriteIntBufferAdapter( - (DirectReadWriteByteBuffer) byteBuffer.duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public int get() { -// if (position == limit) { -// throw new BufferUnderflowException(); -// } - return intArray.get(position++); - } - - @Override - public int get(int index) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - return intArray.get(index); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected int[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public IntBuffer put(int c) { -// if (position == limit) { -// throw new BufferOverflowException(); -// } - intArray.set(position++, c); - return this; - } - - @Override - public IntBuffer put(int index, int c) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - intArray.set(index, c); - return this; - } - - @Override - public IntBuffer slice() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - IntBuffer result = new DirectReadWriteIntBufferAdapter((DirectReadWriteByteBuffer) - byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ArrayBufferView getTypedArray() { - return intArray; + static IntBuffer wrap (DirectReadWriteByteBuffer byteBuffer) { + return new DirectReadWriteIntBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); + } + + private final DirectReadWriteByteBuffer byteBuffer; + private final Int32Array intArray; + + DirectReadWriteIntBufferAdapter (DirectReadWriteByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 2)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + this.intArray = Int32Array.create(byteBuffer.byteArray.getBuffer(), byteBuffer.byteArray.getByteOffset(), capacity); + } + + // TODO(haustein) This will be slow + @Override + public IntBuffer asReadOnlyBuffer () { + DirectReadOnlyIntBufferAdapter buf = new DirectReadOnlyIntBufferAdapter(byteBuffer); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public IntBuffer compact () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public IntBuffer duplicate () { + DirectReadWriteIntBufferAdapter buf = new DirectReadWriteIntBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public int get () { +// if (position == limit) { +// throw new BufferUnderflowException(); +// } + return intArray.get(position++); + } + + @Override + public int get (int index) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + return intArray.get(index); + } + + @Override + public boolean isDirect () { + return true; } + @Override + public boolean isReadOnly () { + return false; + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected int[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public IntBuffer put (int c) { +// if (position == limit) { +// throw new BufferOverflowException(); +// } + intArray.set(position++, c); + return this; + } + + @Override + public IntBuffer put (int index, int c) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + intArray.set(index, c); + return this; + } + + @Override + public IntBuffer slice () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + IntBuffer result = new DirectReadWriteIntBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ArrayBufferView getTypedArray () { + return intArray; + } - public int getElementSize() { + public int getElementSize () { return 4; } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteShortBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteShortBufferAdapter.java index 153b00c039c..b04b7c12155 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteShortBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteShortBufferAdapter.java @@ -19,150 +19,143 @@ import gwt.g3d.client.gl2.array.ArrayBufferView; import gwt.g3d.client.gl2.array.Int16Array; -/** - * This class wraps a byte buffer to be a short buffer. +/** This class wraps a byte buffer to be a short buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class DirectReadWriteShortBufferAdapter extends ShortBuffer implements HasArrayBufferView { -//implements DirectBuffer { - - static ShortBuffer wrap(DirectReadWriteByteBuffer byteBuffer) { - return new DirectReadWriteShortBufferAdapter((DirectReadWriteByteBuffer) byteBuffer.slice()); - } - - private final DirectReadWriteByteBuffer byteBuffer; - private final Int16Array shortArray; - - DirectReadWriteShortBufferAdapter(DirectReadWriteByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 1)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - this.shortArray = Int16Array.create(byteBuffer.byteArray.getBuffer(), - byteBuffer.byteArray.getByteOffset(), - capacity); - } - - // TODO(haustein) This will be slow - @Override - public ShortBuffer asReadOnlyBuffer() { - DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter(byteBuffer); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public ShortBuffer compact() { - byteBuffer.limit(limit << 1); - byteBuffer.position(position << 1); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public ShortBuffer duplicate() { - DirectReadWriteShortBufferAdapter buf = new DirectReadWriteShortBufferAdapter( - (DirectReadWriteByteBuffer) byteBuffer.duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public short get() { -// if (position == limit) { -// throw new BufferUnderflowException(); -// } - return (short)shortArray.get(position++); - } - - @Override - public short get(int index) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - return (short)shortArray.get(index); - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected short[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public ShortBuffer put(short c) { -// if (position == limit) { -// throw new BufferOverflowException(); -// } - shortArray.set(position++, c); - return this; - } - - @Override - public ShortBuffer put(int index, short c) { -// if (index < 0 || index >= limit) { -// throw new IndexOutOfBoundsException(); -// } - shortArray.set(index, c); - return this; - } - - @Override - public ShortBuffer slice() { - byteBuffer.limit(limit << 1); - byteBuffer.position(position << 1); - ShortBuffer result = new DirectReadWriteShortBufferAdapter((DirectReadWriteByteBuffer) - byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ArrayBufferView getTypedArray() { +// implements DirectBuffer { + + static ShortBuffer wrap (DirectReadWriteByteBuffer byteBuffer) { + return new DirectReadWriteShortBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); + } + + private final DirectReadWriteByteBuffer byteBuffer; + private final Int16Array shortArray; + + DirectReadWriteShortBufferAdapter (DirectReadWriteByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 1)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + this.shortArray = Int16Array.create(byteBuffer.byteArray.getBuffer(), byteBuffer.byteArray.getByteOffset(), capacity); + } + + // TODO(haustein) This will be slow + @Override + public ShortBuffer asReadOnlyBuffer () { + DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter(byteBuffer); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public ShortBuffer compact () { + byteBuffer.limit(limit << 1); + byteBuffer.position(position << 1); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public ShortBuffer duplicate () { + DirectReadWriteShortBufferAdapter buf = new DirectReadWriteShortBufferAdapter( + (DirectReadWriteByteBuffer)byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public short get () { +// if (position == limit) { +// throw new BufferUnderflowException(); +// } + return (short)shortArray.get(position++); + } + + @Override + public short get (int index) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + return (short)shortArray.get(index); + } + + @Override + public boolean isDirect () { + return true; + } + + @Override + public boolean isReadOnly () { + return false; + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected short[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public ShortBuffer put (short c) { +// if (position == limit) { +// throw new BufferOverflowException(); +// } + shortArray.set(position++, c); + return this; + } + + @Override + public ShortBuffer put (int index, short c) { +// if (index < 0 || index >= limit) { +// throw new IndexOutOfBoundsException(); +// } + shortArray.set(index, c); + return this; + } + + @Override + public ShortBuffer slice () { + byteBuffer.limit(limit << 1); + byteBuffer.position(position << 1); + ShortBuffer result = new DirectReadWriteShortBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ArrayBufferView getTypedArray () { return shortArray; } - - public int getElementSize() { + public int getElementSize () { return 2; } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleArrayBuffer.java index ad488eac13c..f7270be8d95 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleArrayBuffer.java @@ -15,74 +15,69 @@ * limitations under the License. */ -package java.nio; +package java.nio; -/** - * DoubleArrayBuffer, ReadWriteDoubleArrayBuffer and ReadOnlyDoubleArrayBuffer - * compose the implementation of array based double buffers. +/** DoubleArrayBuffer, ReadWriteDoubleArrayBuffer and ReadOnlyDoubleArrayBuffer compose the implementation of array based double + * buffers. *

    - * DoubleArrayBuffer implements all the shared readonly methods and is extended - * by the other two classes. + * DoubleArrayBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class DoubleArrayBuffer extends DoubleBuffer { - protected final double[] backingArray; + protected final double[] backingArray; + + protected final int offset; - protected final int offset; + DoubleArrayBuffer (double[] array) { + this(array.length, array, 0); + } - DoubleArrayBuffer(double[] array) { - this(array.length, array, 0); - } + DoubleArrayBuffer (int capacity) { + this(capacity, new double[capacity], 0); + } - DoubleArrayBuffer(int capacity) { - this(capacity, new double[capacity], 0); - } + DoubleArrayBuffer (int capacity, double[] backingArray, int offset) { + super(capacity); + this.backingArray = backingArray; + this.offset = offset; + } - DoubleArrayBuffer(int capacity, double[] backingArray, int offset) { - super(capacity); - this.backingArray = backingArray; - this.offset = offset; - } + public final double get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return backingArray[offset + position++]; + } - public final double get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return backingArray[offset + position++]; - } + public final double get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return backingArray[offset + index]; + } - public final double get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return backingArray[offset + index]; - } + public final DoubleBuffer get (double[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + System.arraycopy(backingArray, offset + position, dest, off, len); + position += len; + return this; + } - public final DoubleBuffer get(double[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - System.arraycopy(backingArray, offset + position, dest, - off, len); - position += len; - return this; - } - - public final boolean isDirect() { - return false; - } + public final boolean isDirect () { + return false; + } - public final ByteOrder order() { - return ByteOrder.nativeOrder(); - } + public final ByteOrder order () { + return ByteOrder.nativeOrder(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleBuffer.java index ac19f0ba08a..861b4ee3dc3 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleBuffer.java @@ -17,566 +17,420 @@ package java.nio; -/** - * A buffer of doubles. +/** A buffer of doubles. *

    * A double buffer can be created in either one of the following ways: *

    *
      - *
    • {@link #allocate(int) Allocate} a new double array and create a buffer - * based on it;
    • - *
    • {@link #wrap(double[]) Wrap} an existing double array to create a new - * buffer;
    • - *
    • Use - * {@link java.nio.ByteBuffer#asDoubleBuffer() ByteBuffer.asDoubleBuffer} to - * create a double buffer based on a byte buffer.
    • + *
    • {@link #allocate(int) Allocate} a new double array and create a buffer based on it;
    • + *
    • {@link #wrap(double[]) Wrap} an existing double array to create a new buffer;
    • + *
    • Use {@link java.nio.ByteBuffer#asDoubleBuffer() ByteBuffer.asDoubleBuffer} to create a double buffer based on a byte + * buffer.
    • *
    * - * @since Android 1.0 - */ + * @since Android 1.0 */ public abstract class DoubleBuffer extends Buffer implements Comparable { - /** - * Creates a double buffer based on a newly allocated double array. - * - * @param capacity - * the capacity of the new buffer. - * @return the created double buffer. - * @throws IllegalArgumentException - * if {@code capacity} is less than zero. - * @since Android 1.0 - */ - public static DoubleBuffer allocate(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newDoubleBuffer(capacity); - } - - /** - * Creates a new double buffer by wrapping the given double array. - *

    - * Calling this method has the same effect as - * {@code wrap(array, 0, array.length)}. - *

    - * - * @param array - * the double array which the new buffer will be based on. - * @return the created double buffer. - * @since Android 1.0 - */ - public static DoubleBuffer wrap(double[] array) { - return wrap(array, 0, array.length); - } - - /** - * Creates a new double buffer by wrapping the given double array. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code start + len}, capacity will be the length of the array. - *

    - * - * @param array - * the double array which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code array.length}. - * @param len - * the length, must not be negative and not greater than - * {@code array.length - start}. - * @return the created double buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code len} is invalid. - * @since Android 1.0 - */ - public static DoubleBuffer wrap(double[] array, int start, int len) { - int length = array.length; - if (start < 0 || len < 0 || (long)start + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - DoubleBuffer buf = BufferFactory.newDoubleBuffer(array); - buf.position = start; - buf.limit = start + len; - - return buf; - } - - /** - * Constructs a {@code DoubleBuffer} with given capacity. - * - * @param capacity - * the capacity of the buffer. - */ - DoubleBuffer(int capacity) { - super(capacity); - } - - /** - * Returns the double array which this buffer is based on, if there is one. - * - * @return the double array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final double[] array() { - return protectedArray(); - } - - /** - * Returns the offset of the double array which this buffer is based on, if - * there is one. - *

    - * The offset is the index of the array corresponding to the zero position - * of the buffer. - *

    - * - * @return the offset of the double array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int arrayOffset() { - return protectedArrayOffset(); - } - - /** - * Returns a read-only buffer that shares its content with this buffer. - *

    - * The returned buffer is guaranteed to be a new instance, even if this - * buffer is read-only itself. The new buffer's position, limit, capacity - * and mark are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means that this - * buffer's change of content will be visible to the new buffer. The two - * buffer's position, limit and mark are independent. - *

    - * - * @return a read-only version of this buffer. - * @since Android 1.0 - */ - public abstract DoubleBuffer asReadOnlyBuffer(); - - /** - * Compacts this double buffer. - *

    - * The remaining doubles will be moved to the head of the buffer, staring - * from position zero. Then the position is set to {@code remaining()}; the - * limit is set to capacity; the mark is cleared. - *

    - * - * @return this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract DoubleBuffer compact(); - - /** - * Compare the remaining doubles of this buffer to another double buffer's - * remaining doubles. - * - * @param otherBuffer - * another double buffer. - * @return a negative value if this is less than {@code other}; 0 if this - * equals to {@code other}; a positive value if this is greater - * than {@code other}. - * @exception ClassCastException - * if {@code other} is not a double buffer. - * @since Android 1.0 - */ - public int compareTo(DoubleBuffer otherBuffer) { - int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() - : otherBuffer.remaining(); - int thisPos = position; - int otherPos = otherBuffer.position; - // BEGIN android-changed - double thisDouble, otherDouble; - while (compareRemaining > 0) { - thisDouble = get(thisPos); - otherDouble = otherBuffer.get(otherPos); - // checks for double and NaN inequality - if ((thisDouble != otherDouble) - && ((thisDouble == thisDouble) || (otherDouble == otherDouble))) { - return thisDouble < otherDouble ? -1 : 1; - } - thisPos++; - otherPos++; - compareRemaining--; - } - // END android-changed - return remaining() - otherBuffer.remaining(); - } - - /** - * Returns a duplicated buffer that shares its content with this buffer. - *

    - * The duplicated buffer's position, limit, capacity and mark are the same - * as this buffer's. The duplicated buffer's read-only property and byte - * order are the same as this buffer's, too. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a duplicated buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract DoubleBuffer duplicate(); - - /** - * Checks whether this double buffer is equal to another object. - *

    - * If {@code other} is not a double buffer then {@code false} is returned. - * Two double buffers are equal if and only if their remaining doubles are - * exactly the same. Position, limit, capacity and mark are not considered. - *

    - * - * @param other - * the object to compare with this double buffer. - * @return {@code true} if this double buffer is equal to {@code other}, - * {@code false} otherwise. - * @since Android 1.0 - */ - public boolean equals(Object other) { - if (!(other instanceof DoubleBuffer)) { - return false; - } - DoubleBuffer otherBuffer = (DoubleBuffer) other; - - if (remaining() != otherBuffer.remaining()) { - return false; - } - - int myPosition = position; - int otherPosition = otherBuffer.position; - boolean equalSoFar = true; - while (equalSoFar && (myPosition < limit)) { - equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); - } - - return equalSoFar; - } - - /** - * Returns the double at the current position and increases the position by - * 1. - * - * @return the double at the current position. - * @exception BufferUnderflowException - * if the position is equal or greater than limit. - * @since Android 1.0 - */ - public abstract double get(); - - /** - * Reads doubles from the current position into the specified double array - * and increases the position by the number of doubles read. - *

    - * Calling this method has the same effect as - * {@code get(dest, 0, dest.length)}. - *

    - * - * @param dest - * the destination double array. - * @return this buffer. - * @exception BufferUnderflowException - * if {@code dest.length} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public DoubleBuffer get(double[] dest) { - return get(dest, 0, dest.length); - } - - /** - * Reads doubles from the current position into the specified double array, - * starting from the specified offset, and increases the position by the - * number of doubles read. - * - * @param dest - * the target double array. - * @param off - * the offset of the double array, must not be negative and not - * greater than {@code dest.length}. - * @param len - * the number of doubles to read, must be no less than zero and - * not greater than {@code dest.length - off}. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception BufferUnderflowException - * if {@code len} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public DoubleBuffer get(double[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferUnderflowException(); - } - for (int i = off; i < off + len; i++) { - dest[i] = get(); - } - return this; - } - - /** - * Returns a double at the specified index; the position is not changed. - * - * @param index - * the index, must not be negative and less than limit. - * @return a double at the specified index. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @since Android 1.0 - */ - public abstract double get(int index); - - /** - * Indicates whether this buffer is based on a double array and is - * read/write. - * - * @return {@code true} if this buffer is based on a double array and - * provides read/write access, {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasArray() { - return protectedHasArray(); - } - -// /** -// * Calculates this buffer's hash code from the remaining chars. The -// * position, limit, capacity and mark don't affect the hash code. -// * -// * @return the hash code calculated from the remaining chars. -// * @since Android 1.0 -// */ -// public int hashCode() { -// int myPosition = position; -// int hash = 0; -// long l; -// while (myPosition < limit) { -// l = Double.doubleToLongBits(get(myPosition++)); -// hash = hash + ((int) l) ^ ((int) (l >> 32)); -// } -// return hash; -// } - - /** - * Indicates whether this buffer is direct. A direct buffer will try its - * best to take advantage of native memory APIs and it may not stay in the - * Java heap, so it is not affected by garbage collection. - *

    - * A double buffer is direct if it is based on a byte buffer and the byte - * buffer is direct. - *

    - * - * @return {@code true} if this buffer is direct, {@code false} otherwise. - * @since Android 1.0 - */ - public abstract boolean isDirect(); - - /** - * Returns the byte order used by this buffer when converting doubles - * from/to bytes. - *

    - * If this buffer is not based on a byte buffer, then this always returns - * the platform's native byte order. - *

    - * - * @return the byte order used by this buffer when converting doubles - * from/to bytes. - * @since Android 1.0 - */ - public abstract ByteOrder order(); - - /** - * Child class implements this method to realize {@code array()}. - * - * @see #array() - */ - abstract double[] protectedArray(); - - /** - * Child class implements this method to realize {@code arrayOffset()}. - * - * @see #arrayOffset() - */ - abstract int protectedArrayOffset(); - - /** - * Child class implements this method to realize {@code hasArray()}. - * - * @see #hasArray() - */ - abstract boolean protectedHasArray(); - - /** - * Writes the given double to the current position and increases the - * position by 1. - * - * @param d - * the double to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract DoubleBuffer put(double d); - - /** - * Writes doubles from the given double array to the current position and - * increases the position by the number of doubles written. - *

    - * Calling this method has the same effect as - * {@code put(src, 0, src.length)}. - *

    - * - * @param src - * the source double array. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code src.length}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final DoubleBuffer put(double[] src) { - return put(src, 0, src.length); - } - - /** - * Writes doubles from the given double array, starting from the specified - * offset, to the current position and increases the position by the number - * of doubles written. - * - * @param src - * the source double array. - * @param off - * the offset of double array, must not be negative and not - * greater than {@code src.length}. - * @param len - * the number of doubles to write, must be no less than zero and - * not greater than {@code src.length - off}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code len}. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public DoubleBuffer put(double[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - for (int i = off; i < off + len; i++) { - put(src[i]); - } - return this; - } - - /** - * Writes all the remaining doubles of the {@code src} double buffer to this - * buffer's current position, and increases both buffers' position by the - * number of doubles copied. - * - * @param src - * the source double buffer. - * @return this buffer. - * @exception BufferOverflowException - * if {@code src.remaining()} is greater than this buffer's - * {@code remaining()}. - * @exception IllegalArgumentException - * if {@code src} is this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public DoubleBuffer put(DoubleBuffer src) { - if (src == this) { - throw new IllegalArgumentException(); - } - if (src.remaining() > remaining()) { - throw new BufferOverflowException(); - } - double[] doubles = new double[src.remaining()]; - src.get(doubles); - put(doubles); - return this; - } - - /** - * Write a double to the specified index of this buffer and the position is - * not changed. - * - * @param index - * the index, must not be negative and less than the limit. - * @param d - * the double to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract DoubleBuffer put(int index, double d); - - /** - * Returns a sliced buffer that shares its content with this buffer. - *

    - * The sliced buffer's capacity will be this buffer's {@code remaining()}, - * and its zero position will correspond to this buffer's current position. - * The new buffer's position will be 0, limit will be its capacity, and its - * mark is cleared. The new buffer's read-only property and byte order are - * the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a sliced buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract DoubleBuffer slice(); - - /** - * Returns a string representing the state of this double buffer. - * - * @return A string representing the state of this double buffer. - * @since Android 1.0 - */ - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append(getClass().getName()); - buf.append(", status: capacity="); //$NON-NLS-1$ - buf.append(capacity()); - buf.append(" position="); //$NON-NLS-1$ - buf.append(position()); - buf.append(" limit="); //$NON-NLS-1$ - buf.append(limit()); - return buf.toString(); - } + /** Creates a double buffer based on a newly allocated double array. + * + * @param capacity the capacity of the new buffer. + * @return the created double buffer. + * @throws IllegalArgumentException if {@code capacity} is less than zero. + * @since Android 1.0 */ + public static DoubleBuffer allocate (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newDoubleBuffer(capacity); + } + + /** Creates a new double buffer by wrapping the given double array. + *

    + * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. + *

    + * + * @param array the double array which the new buffer will be based on. + * @return the created double buffer. + * @since Android 1.0 */ + public static DoubleBuffer wrap (double[] array) { + return wrap(array, 0, array.length); + } + + /** Creates a new double buffer by wrapping the given double array. + *

    + * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the + * array. + *

    + * + * @param array the double array which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code array.length}. + * @param len the length, must not be negative and not greater than {@code array.length - start}. + * @return the created double buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. + * @since Android 1.0 */ + public static DoubleBuffer wrap (double[] array, int start, int len) { + int length = array.length; + if (start < 0 || len < 0 || (long)start + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + DoubleBuffer buf = BufferFactory.newDoubleBuffer(array); + buf.position = start; + buf.limit = start + len; + + return buf; + } + + /** Constructs a {@code DoubleBuffer} with given capacity. + * + * @param capacity the capacity of the buffer. */ + DoubleBuffer (int capacity) { + super(capacity); + } + + /** Returns the double array which this buffer is based on, if there is one. + * + * @return the double array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final double[] array () { + return protectedArray(); + } + + /** Returns the offset of the double array which this buffer is based on, if there is one. + *

    + * The offset is the index of the array corresponding to the zero position of the buffer. + *

    + * + * @return the offset of the double array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int arrayOffset () { + return protectedArrayOffset(); + } + + /** Returns a read-only buffer that shares its content with this buffer. + *

    + * The returned buffer is guaranteed to be a new instance, even if this buffer is read-only itself. The new buffer's position, + * limit, capacity and mark are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means that this buffer's change of content will be visible to the + * new buffer. The two buffer's position, limit and mark are independent. + *

    + * + * @return a read-only version of this buffer. + * @since Android 1.0 */ + public abstract DoubleBuffer asReadOnlyBuffer (); + + /** Compacts this double buffer. + *

    + * The remaining doubles will be moved to the head of the buffer, staring from position zero. Then the position is set to + * {@code remaining()}; the limit is set to capacity; the mark is cleared. + *

    + * + * @return this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract DoubleBuffer compact (); + + /** Compare the remaining doubles of this buffer to another double buffer's remaining doubles. + * + * @param otherBuffer another double buffer. + * @return a negative value if this is less than {@code other}; 0 if this equals to {@code other}; a positive value if this is + * greater than {@code other}. + * @exception ClassCastException if {@code other} is not a double buffer. + * @since Android 1.0 */ + public int compareTo (DoubleBuffer otherBuffer) { + int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); + int thisPos = position; + int otherPos = otherBuffer.position; + // BEGIN android-changed + double thisDouble, otherDouble; + while (compareRemaining > 0) { + thisDouble = get(thisPos); + otherDouble = otherBuffer.get(otherPos); + // checks for double and NaN inequality + if ((thisDouble != otherDouble) && ((thisDouble == thisDouble) || (otherDouble == otherDouble))) { + return thisDouble < otherDouble ? -1 : 1; + } + thisPos++; + otherPos++; + compareRemaining--; + } + // END android-changed + return remaining() - otherBuffer.remaining(); + } + + /** Returns a duplicated buffer that shares its content with this buffer. + *

    + * The duplicated buffer's position, limit, capacity and mark are the same as this buffer's. The duplicated buffer's read-only + * property and byte order are the same as this buffer's, too. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a duplicated buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract DoubleBuffer duplicate (); + + /** Checks whether this double buffer is equal to another object. + *

    + * If {@code other} is not a double buffer then {@code false} is returned. Two double buffers are equal if and only if their + * remaining doubles are exactly the same. Position, limit, capacity and mark are not considered. + *

    + * + * @param other the object to compare with this double buffer. + * @return {@code true} if this double buffer is equal to {@code other}, {@code false} otherwise. + * @since Android 1.0 */ + public boolean equals (Object other) { + if (!(other instanceof DoubleBuffer)) { + return false; + } + DoubleBuffer otherBuffer = (DoubleBuffer)other; + + if (remaining() != otherBuffer.remaining()) { + return false; + } + + int myPosition = position; + int otherPosition = otherBuffer.position; + boolean equalSoFar = true; + while (equalSoFar && (myPosition < limit)) { + equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); + } + + return equalSoFar; + } + + /** Returns the double at the current position and increases the position by 1. + * + * @return the double at the current position. + * @exception BufferUnderflowException if the position is equal or greater than limit. + * @since Android 1.0 */ + public abstract double get (); + + /** Reads doubles from the current position into the specified double array and increases the position by the number of doubles + * read. + *

    + * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. + *

    + * + * @param dest the destination double array. + * @return this buffer. + * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. + * @since Android 1.0 */ + public DoubleBuffer get (double[] dest) { + return get(dest, 0, dest.length); + } + + /** Reads doubles from the current position into the specified double array, starting from the specified offset, and increases + * the position by the number of doubles read. + * + * @param dest the target double array. + * @param off the offset of the double array, must not be negative and not greater than {@code dest.length}. + * @param len the number of doubles to read, must be no less than zero and not greater than {@code dest.length - off}. + * @return this buffer. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. + * @since Android 1.0 */ + public DoubleBuffer get (double[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferUnderflowException(); + } + for (int i = off; i < off + len; i++) { + dest[i] = get(); + } + return this; + } + + /** Returns a double at the specified index; the position is not changed. + * + * @param index the index, must not be negative and less than limit. + * @return a double at the specified index. + * @exception IndexOutOfBoundsException if index is invalid. + * @since Android 1.0 */ + public abstract double get (int index); + + /** Indicates whether this buffer is based on a double array and is read/write. + * + * @return {@code true} if this buffer is based on a double array and provides read/write access, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasArray () { + return protectedHasArray(); + } + +// /** +// * Calculates this buffer's hash code from the remaining chars. The +// * position, limit, capacity and mark don't affect the hash code. +// * +// * @return the hash code calculated from the remaining chars. +// * @since Android 1.0 +// */ +// public int hashCode() { +// int myPosition = position; +// int hash = 0; +// long l; +// while (myPosition < limit) { +// l = Double.doubleToLongBits(get(myPosition++)); +// hash = hash + ((int) l) ^ ((int) (l >> 32)); +// } +// return hash; +// } + + /** Indicates whether this buffer is direct. A direct buffer will try its best to take advantage of native memory APIs and it + * may not stay in the Java heap, so it is not affected by garbage collection. + *

    + * A double buffer is direct if it is based on a byte buffer and the byte buffer is direct. + *

    + * + * @return {@code true} if this buffer is direct, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isDirect (); + + /** Returns the byte order used by this buffer when converting doubles from/to bytes. + *

    + * If this buffer is not based on a byte buffer, then this always returns the platform's native byte order. + *

    + * + * @return the byte order used by this buffer when converting doubles from/to bytes. + * @since Android 1.0 */ + public abstract ByteOrder order (); + + /** Child class implements this method to realize {@code array()}. + * + * @see #array() */ + abstract double[] protectedArray (); + + /** Child class implements this method to realize {@code arrayOffset()}. + * + * @see #arrayOffset() */ + abstract int protectedArrayOffset (); + + /** Child class implements this method to realize {@code hasArray()}. + * + * @see #hasArray() */ + abstract boolean protectedHasArray (); + + /** Writes the given double to the current position and increases the position by 1. + * + * @param d the double to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract DoubleBuffer put (double d); + + /** Writes doubles from the given double array to the current position and increases the position by the number of doubles + * written. + *

    + * Calling this method has the same effect as {@code put(src, 0, src.length)}. + *

    + * + * @param src the source double array. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final DoubleBuffer put (double[] src) { + return put(src, 0, src.length); + } + + /** Writes doubles from the given double array, starting from the specified offset, to the current position and increases the + * position by the number of doubles written. + * + * @param src the source double array. + * @param off the offset of double array, must not be negative and not greater than {@code src.length}. + * @param len the number of doubles to write, must be no less than zero and not greater than {@code src.length - off}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public DoubleBuffer put (double[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + for (int i = off; i < off + len; i++) { + put(src[i]); + } + return this; + } + + /** Writes all the remaining doubles of the {@code src} double buffer to this buffer's current position, and increases both + * buffers' position by the number of doubles copied. + * + * @param src the source double buffer. + * @return this buffer. + * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. + * @exception IllegalArgumentException if {@code src} is this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public DoubleBuffer put (DoubleBuffer src) { + if (src == this) { + throw new IllegalArgumentException(); + } + if (src.remaining() > remaining()) { + throw new BufferOverflowException(); + } + double[] doubles = new double[src.remaining()]; + src.get(doubles); + put(doubles); + return this; + } + + /** Write a double to the specified index of this buffer and the position is not changed. + * + * @param index the index, must not be negative and less than the limit. + * @param d the double to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if index is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract DoubleBuffer put (int index, double d); + + /** Returns a sliced buffer that shares its content with this buffer. + *

    + * The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero position will correspond to this + * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new + * buffer's read-only property and byte order are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a sliced buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract DoubleBuffer slice (); + + /** Returns a string representing the state of this double buffer. + * + * @return A string representing the state of this double buffer. + * @since Android 1.0 */ + public String toString () { + StringBuffer buf = new StringBuffer(); + buf.append(getClass().getName()); + buf.append(", status: capacity="); //$NON-NLS-1$ + buf.append(capacity()); + buf.append(" position="); //$NON-NLS-1$ + buf.append(position()); + buf.append(" limit="); //$NON-NLS-1$ + buf.append(limit()); + return buf.toString(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleToByteBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleToByteBufferAdapter.java index c8d73dfeb1d..10c9ad9d423 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleToByteBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DoubleToByteBufferAdapter.java @@ -19,188 +19,183 @@ //import org.apache.harmony.nio.internal.DirectBuffer; //import org.apache.harmony.luni.platform.PlatformAddress; -/** - * This class wraps a byte buffer to be a double buffer. +/** This class wraps a byte buffer to be a double buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ -final class DoubleToByteBufferAdapter extends DoubleBuffer { - //implements DirectBuffer { - - static DoubleBuffer wrap(ByteBuffer byteBuffer) { - return new DoubleToByteBufferAdapter(byteBuffer.slice()); - } - - private final ByteBuffer byteBuffer; - - DoubleToByteBufferAdapter(ByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 3)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - } - -// public int getByteCapacity() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getByteCapacity(); -// } -// assert false : byteBuffer; -// return -1; -// } + *

    */ +final class DoubleToByteBufferAdapter extends DoubleBuffer { + // implements DirectBuffer { + + static DoubleBuffer wrap (ByteBuffer byteBuffer) { + return new DoubleToByteBufferAdapter(byteBuffer.slice()); + } + + private final ByteBuffer byteBuffer; + + DoubleToByteBufferAdapter (ByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 3)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + } + +// public int getByteCapacity() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getByteCapacity(); +// } +// assert false : byteBuffer; +// return -1; +// } // -// public PlatformAddress getEffectiveAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getEffectiveAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public PlatformAddress getBaseAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getBaseAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getBaseAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getBaseAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public boolean isAddressValid() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).isAddressValid(); -// } -// assert false : byteBuffer; -// return false; -// } +// public boolean isAddressValid() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).isAddressValid(); +// } +// assert false : byteBuffer; +// return false; +// } // -// public void addressValidityCheck() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).addressValidityCheck(); -// } else { -// assert false : byteBuffer; -// } -// } +// public void addressValidityCheck() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).addressValidityCheck(); +// } else { +// assert false : byteBuffer; +// } +// } // -// public void free() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).free(); -// } else { -// assert false : byteBuffer; -// } -// } - - @Override - public DoubleBuffer asReadOnlyBuffer() { - DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter( - byteBuffer.asReadOnlyBuffer()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public DoubleBuffer compact() { - if (byteBuffer.isReadOnly()) { - throw new ReadOnlyBufferException(); - } - byteBuffer.limit(limit << 3); - byteBuffer.position(position << 3); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public DoubleBuffer duplicate() { - DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter( - byteBuffer.duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public double get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return byteBuffer.getDouble(position++ << 3); - } - - @Override - public double get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return byteBuffer.getDouble(index << 3); - } - - @Override - public boolean isDirect() { - return byteBuffer.isDirect(); - } - - @Override - public boolean isReadOnly() { - return byteBuffer.isReadOnly(); - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected double[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public DoubleBuffer put(double c) { - if (position == limit) { - throw new BufferOverflowException(); - } - byteBuffer.putDouble(position++ << 3, c); - return this; - } - - @Override - public DoubleBuffer put(int index, double c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - byteBuffer.putDouble(index << 3, c); - return this; - } - - @Override - public DoubleBuffer slice() { - byteBuffer.limit(limit << 3); - byteBuffer.position(position << 3); - DoubleBuffer result = new DoubleToByteBufferAdapter(byteBuffer.slice()); - byteBuffer.clear(); - return result; - } +// public void free() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).free(); +// } else { +// assert false : byteBuffer; +// } +// } + + @Override + public DoubleBuffer asReadOnlyBuffer () { + DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(byteBuffer.asReadOnlyBuffer()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public DoubleBuffer compact () { + if (byteBuffer.isReadOnly()) { + throw new ReadOnlyBufferException(); + } + byteBuffer.limit(limit << 3); + byteBuffer.position(position << 3); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public DoubleBuffer duplicate () { + DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public double get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return byteBuffer.getDouble(position++ << 3); + } + + @Override + public double get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return byteBuffer.getDouble(index << 3); + } + + @Override + public boolean isDirect () { + return byteBuffer.isDirect(); + } + + @Override + public boolean isReadOnly () { + return byteBuffer.isReadOnly(); + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected double[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public DoubleBuffer put (double c) { + if (position == limit) { + throw new BufferOverflowException(); + } + byteBuffer.putDouble(position++ << 3, c); + return this; + } + + @Override + public DoubleBuffer put (int index, double c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + byteBuffer.putDouble(index << 3, c); + return this; + } + + @Override + public DoubleBuffer slice () { + byteBuffer.limit(limit << 3); + byteBuffer.position(position << 3); + DoubleBuffer result = new DoubleToByteBufferAdapter(byteBuffer.slice()); + byteBuffer.clear(); + return result; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatArrayBuffer.java index bb07e977a24..4c6eca80c6b 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatArrayBuffer.java @@ -17,71 +17,67 @@ package java.nio; -/** - * FloatArrayBuffer, ReadWriteFloatArrayBuffer and ReadOnlyFloatArrayBuffer - * compose the implementation of array based float buffers. +/** FloatArrayBuffer, ReadWriteFloatArrayBuffer and ReadOnlyFloatArrayBuffer compose the implementation of array based float + * buffers. *

    - * FloatArrayBuffer implements all the shared readonly methods and is extended - * by the other two classes. + * FloatArrayBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class FloatArrayBuffer extends FloatBuffer { - protected final float[] backingArray; + protected final float[] backingArray; + + protected final int offset; - protected final int offset; + FloatArrayBuffer (float[] array) { + this(array.length, array, 0); + } - FloatArrayBuffer(float[] array) { - this(array.length, array, 0); - } + FloatArrayBuffer (int capacity) { + this(capacity, new float[capacity], 0); + } - FloatArrayBuffer(int capacity) { - this(capacity, new float[capacity], 0); - } + FloatArrayBuffer (int capacity, float[] backingArray, int offset) { + super(capacity); + this.backingArray = backingArray; + this.offset = offset; + } - FloatArrayBuffer(int capacity, float[] backingArray, int offset) { - super(capacity); - this.backingArray = backingArray; - this.offset = offset; - } + public final float get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return backingArray[offset + position++]; + } - public final float get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return backingArray[offset + position++]; - } + public final float get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return backingArray[offset + index]; + } - public final float get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return backingArray[offset + index]; - } + public final FloatBuffer get (float[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + System.arraycopy(backingArray, offset + position, dest, off, len); + position += len; + return this; + } - public final FloatBuffer get(float[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - System.arraycopy(backingArray, offset+position, dest, off, len); - position += len; - return this; - } - - public final boolean isDirect() { - return false; - } + public final boolean isDirect () { + return false; + } - public final ByteOrder order() { - return ByteOrder.nativeOrder(); - } + public final ByteOrder order () { + return ByteOrder.nativeOrder(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatBuffer.java index e6103061444..6d3f39073f6 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatBuffer.java @@ -17,566 +17,419 @@ package java.nio; -/** - * A buffer of floats. +/** A buffer of floats. *

    * A float buffer can be created in either of the following ways: *

    *
      - *
    • {@link #allocate(int) Allocate} a new float array and create a buffer - * based on it;
    • - *
    • {@link #wrap(float[]) Wrap} an existing float array to create a new - * buffer;
    • - *
    • Use {@link java.nio.ByteBuffer#asFloatBuffer() ByteBuffer.asFloatBuffer} - * to create a float buffer based on a byte buffer.
    • + *
    • {@link #allocate(int) Allocate} a new float array and create a buffer based on it;
    • + *
    • {@link #wrap(float[]) Wrap} an existing float array to create a new buffer;
    • + *
    • Use {@link java.nio.ByteBuffer#asFloatBuffer() ByteBuffer.asFloatBuffer} to create a float buffer based on a byte buffer.
    • *
    * - * @since Android 1.0 - */ + * @since Android 1.0 */ public abstract class FloatBuffer extends Buffer implements Comparable { - /** - * Creates a float buffer based on a newly allocated float array. - * - * @param capacity - * the capacity of the new buffer. - * @return the created float buffer. - * @throws IllegalArgumentException - * if {@code capacity} is less than zero. - * @since Android 1.0 - */ - public static FloatBuffer allocate(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newFloatBuffer(capacity); - } - - /** - * Creates a new float buffer by wrapping the given float array. - *

    - * Calling this method has the same effect as - * {@code wrap(array, 0, array.length)}. - *

    - * - * @param array - * the float array which the new buffer will be based on. - * @return the created float buffer. - * @since Android 1.0 - */ - public static FloatBuffer wrap(float[] array) { - return wrap(array, 0, array.length); - } - - /** - * Creates a new float buffer by wrapping the given float array. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code start + len}, capacity will be the length of the array. - *

    - * - * @param array - * the float array which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code array.length}. - * @param len - * the length, must not be negative and not greater than - * {@code array.length - start}. - * @return the created float buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code len} is invalid. - * @exception NullPointerException - * if {@code array} is null. - * @since Android 1.0 - */ - public static FloatBuffer wrap(float[] array, int start, int len) { - if (array == null) { - throw new NullPointerException(); - } - if (start < 0 || len < 0 || (long)start + (long)len > array.length) { - throw new IndexOutOfBoundsException(); - } - - FloatBuffer buf = BufferFactory.newFloatBuffer(array); - buf.position = start; - buf.limit = start + len; - - return buf; - } - - /** - * Constructs a {@code FloatBuffer} with given capacity. - * - * @param capacity The capacity of the buffer - */ - FloatBuffer(int capacity) { - super(capacity); - } - - /** - * Returns the float array which this buffer is based on, if there is one. - * - * @return the float array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final float[] array() { - return protectedArray(); - } - - /** - * Returns the offset of the float array which this buffer is based on, if - * there is one. - *

    - * The offset is the index of the array and corresponds to the zero position - * of the buffer. - *

    - * - * @return the offset of the float array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int arrayOffset() { - return protectedArrayOffset(); - } - - /** - * Returns a read-only buffer that shares its content with this buffer. - *

    - * The returned buffer is guaranteed to be a new instance, even if this - * buffer is read-only itself. The new buffer's position, limit, capacity - * and mark are the same as this buffer. - *

    - *

    - * The new buffer shares its content with this buffer, which means this - * buffer's change of content will be visible to the new buffer. The two - * buffer's position, limit and mark are independent. - *

    - * - * @return a read-only version of this buffer. - * @since Android 1.0 - */ - public abstract FloatBuffer asReadOnlyBuffer(); - - /** - * Compacts this float buffer. - *

    - * The remaining floats will be moved to the head of the buffer, starting - * from position zero. Then the position is set to {@code remaining()}; the - * limit is set to capacity; the mark is cleared. - *

    - * - * @return this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract FloatBuffer compact(); - - /** - * Compare the remaining floats of this buffer to another float buffer's - * remaining floats. - * - * @param otherBuffer - * another float buffer. - * @return a negative value if this is less than {@code otherBuffer}; 0 if - * this equals to {@code otherBuffer}; a positive value if this is - * greater than {@code otherBuffer}. - * @exception ClassCastException - * if {@code otherBuffer} is not a float buffer. - * @since Android 1.0 - */ - public int compareTo(FloatBuffer otherBuffer) { - int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() - : otherBuffer.remaining(); - int thisPos = position; - int otherPos = otherBuffer.position; - // BEGIN android-changed - float thisFloat, otherFloat; - while (compareRemaining > 0) { - thisFloat = get(thisPos); - otherFloat = otherBuffer.get(otherPos); - // checks for float and NaN inequality - if ((thisFloat != otherFloat) - && ((thisFloat == thisFloat) || (otherFloat == otherFloat))) { - return thisFloat < otherFloat ? -1 : 1; - } - thisPos++; - otherPos++; - compareRemaining--; - } - // END android-changed - return remaining() - otherBuffer.remaining(); - } - - /** - * Returns a duplicated buffer that shares its content with this buffer. - *

    - * The duplicated buffer's position, limit, capacity and mark are the same - * as this buffer. The duplicated buffer's read-only property and byte order - * are same as this buffer too. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a duplicated buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract FloatBuffer duplicate(); - - /** - * Checks whether this float buffer is equal to another object. - *

    - * If {@code other} is not a float buffer then {@code false} is returned. - * Two float buffers are equal if and only if their remaining floats are - * exactly the same. Position, limit, capacity and mark are not considered. - *

    - * - * @param other - * the object to compare with this float buffer. - * @return {@code true} if this float buffer is equal to {@code other}, - * {@code false} otherwise. - * @since Android 1.0 - */ - public boolean equals(Object other) { - if (!(other instanceof FloatBuffer)) { - return false; - } - FloatBuffer otherBuffer = (FloatBuffer) other; - - if (remaining() != otherBuffer.remaining()) { - return false; - } - - int myPosition = position; - int otherPosition = otherBuffer.position; - boolean equalSoFar = true; - while (equalSoFar && (myPosition < limit)) { - equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); - } - - return equalSoFar; - } - - /** - * Returns the float at the current position and increases the position by - * 1. - * - * @return the float at the current position. - * @exception BufferUnderflowException - * if the position is equal or greater than limit. - * @since Android 1.0 - */ - public abstract float get(); - - /** - * Reads floats from the current position into the specified float array and - * increases the position by the number of floats read. - *

    - * Calling this method has the same effect as - * {@code get(dest, 0, dest.length)}. - *

    - * - * @param dest - * the destination float array. - * @return this buffer. - * @exception BufferUnderflowException - * if {@code dest.length} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public FloatBuffer get(float[] dest) { - return get(dest, 0, dest.length); - } - - /** - * Reads floats from the current position into the specified float array, - * starting from the specified offset, and increases the position by the - * number of floats read. - * - * @param dest - * the target float array. - * @param off - * the offset of the float array, must not be negative and no - * greater than {@code dest.length}. - * @param len - * the number of floats to read, must be no less than zero and no - * greater than {@code dest.length - off}. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception BufferUnderflowException - * if {@code len} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public FloatBuffer get(float[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferUnderflowException(); - } - for (int i = off; i < off + len; i++) { - dest[i] = get(); - } - return this; - } - - /** - * Returns a float at the specified index; the position is not changed. - * - * @param index - * the index, must not be negative and less than limit. - * @return a float at the specified index. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @since Android 1.0 - */ - public abstract float get(int index); - - /** - * Indicates whether this buffer is based on a float array and is - * read/write. - * - * @return {@code true} if this buffer is based on a float array and - * provides read/write access, {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasArray() { - return protectedHasArray(); - } - -// /** -// * Calculates this buffer's hash code from the remaining chars. The -// * position, limit, capacity and mark don't affect the hash code. -// * -// * @return the hash code calculated from the remaining floats. -// * @since Android 1.0 -// */ -// public int hashCode() { -// int myPosition = position; -// int hash = 0; -// while (myPosition < limit) { -// hash = hash + Float.floatToIntBits(get(myPosition++)); -// } -// return hash; -// } - - /** - * Indicates whether this buffer is direct. A direct buffer will try its - * best to take advantage of native memory APIs and it may not stay in the - * Java heap, so it is not affected by garbage collection. - *

    - * A float buffer is direct if it is based on a byte buffer and the byte - * buffer is direct. - *

    - * - * @return {@code true} if this buffer is direct, {@code false} otherwise. - * @since Android 1.0 - */ - public abstract boolean isDirect(); - - /** - * Returns the byte order used by this buffer when converting floats from/to - * bytes. - *

    - * If this buffer is not based on a byte buffer, then always return the - * platform's native byte order. - *

    - * - * @return the byte order used by this buffer when converting floats from/to - * bytes. - * @since Android 1.0 - */ - public abstract ByteOrder order(); - - /** - * Child class implements this method to realize {@code array()}. - * - * @return see {@code array()} - */ - abstract float[] protectedArray(); - - /** - * Child class implements this method to realize {@code arrayOffset()}. - * - * @return see {@code arrayOffset()} - */ - abstract int protectedArrayOffset(); - - /** - * Child class implements this method to realize {@code hasArray()}. - * - * @return see {@code hasArray()} - */ - abstract boolean protectedHasArray(); - - /** - * Writes the given float to the current position and increases the position - * by 1. - * - * @param f - * the float to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract FloatBuffer put(float f); - - /** - * Writes floats from the given float array to the current position and - * increases the position by the number of floats written. - *

    - * Calling this method has the same effect as - * {@code put(src, 0, src.length)}. - *

    - * - * @param src - * the source float array. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code src.length}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final FloatBuffer put(float[] src) { - return put(src, 0, src.length); - } - - /** - * Writes floats from the given float array, starting from the specified - * offset, to the current position and increases the position by the number - * of floats written. - * - * @param src - * the source float array. - * @param off - * the offset of float array, must not be negative and not - * greater than {@code src.length}. - * @param len - * the number of floats to write, must be no less than zero and - * no greater than {@code src.length - off}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code len}. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public FloatBuffer put(float[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - for (int i = off; i < off + len; i++) { - put(src[i]); - } - return this; - } - - /** - * Writes all the remaining floats of the {@code src} float buffer to this - * buffer's current position, and increases both buffers' position by the - * number of floats copied. - * - * @param src - * the source float buffer. - * @return this buffer. - * @exception BufferOverflowException - * if {@code src.remaining()} is greater than this buffer's - * {@code remaining()}. - * @exception IllegalArgumentException - * if {@code src} is this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public FloatBuffer put(FloatBuffer src) { - if (src == this) { - throw new IllegalArgumentException(); - } - if (src.remaining() > remaining()) { - throw new BufferOverflowException(); - } - float[] contents = new float[src.remaining()]; - src.get(contents); - put(contents); - return this; - } - - /** - * Writes a float to the specified index of this buffer; the position is not - * changed. - * - * @param index - * the index, must not be negative and less than the limit. - * @param f - * the float to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract FloatBuffer put(int index, float f); - - /** - * Returns a sliced buffer that shares its content with this buffer. - *

    - * The sliced buffer's capacity will be this buffer's {@code remaining()}, - * and its zero position will correspond to this buffer's current position. - * The new buffer's position will be 0, limit will be its capacity, and its - * mark is cleared. The new buffer's read-only property and byte order are - * same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a sliced buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract FloatBuffer slice(); - - /** - * Returns a string representing the state of this float buffer. - * - * @return a string representing the state of this float buffer. - * @since Android 1.0 - */ - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append(getClass().getName()); - buf.append(", status: capacity="); //$NON-NLS-1$ - buf.append(capacity()); - buf.append(" position="); //$NON-NLS-1$ - buf.append(position()); - buf.append(" limit="); //$NON-NLS-1$ - buf.append(limit()); - return buf.toString(); - } + /** Creates a float buffer based on a newly allocated float array. + * + * @param capacity the capacity of the new buffer. + * @return the created float buffer. + * @throws IllegalArgumentException if {@code capacity} is less than zero. + * @since Android 1.0 */ + public static FloatBuffer allocate (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newFloatBuffer(capacity); + } + + /** Creates a new float buffer by wrapping the given float array. + *

    + * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. + *

    + * + * @param array the float array which the new buffer will be based on. + * @return the created float buffer. + * @since Android 1.0 */ + public static FloatBuffer wrap (float[] array) { + return wrap(array, 0, array.length); + } + + /** Creates a new float buffer by wrapping the given float array. + *

    + * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the + * array. + *

    + * + * @param array the float array which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code array.length}. + * @param len the length, must not be negative and not greater than {@code array.length - start}. + * @return the created float buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. + * @exception NullPointerException if {@code array} is null. + * @since Android 1.0 */ + public static FloatBuffer wrap (float[] array, int start, int len) { + if (array == null) { + throw new NullPointerException(); + } + if (start < 0 || len < 0 || (long)start + (long)len > array.length) { + throw new IndexOutOfBoundsException(); + } + + FloatBuffer buf = BufferFactory.newFloatBuffer(array); + buf.position = start; + buf.limit = start + len; + + return buf; + } + + /** Constructs a {@code FloatBuffer} with given capacity. + * + * @param capacity The capacity of the buffer */ + FloatBuffer (int capacity) { + super(capacity); + } + + /** Returns the float array which this buffer is based on, if there is one. + * + * @return the float array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final float[] array () { + return protectedArray(); + } + + /** Returns the offset of the float array which this buffer is based on, if there is one. + *

    + * The offset is the index of the array and corresponds to the zero position of the buffer. + *

    + * + * @return the offset of the float array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int arrayOffset () { + return protectedArrayOffset(); + } + + /** Returns a read-only buffer that shares its content with this buffer. + *

    + * The returned buffer is guaranteed to be a new instance, even if this buffer is read-only itself. The new buffer's position, + * limit, capacity and mark are the same as this buffer. + *

    + *

    + * The new buffer shares its content with this buffer, which means this buffer's change of content will be visible to the new + * buffer. The two buffer's position, limit and mark are independent. + *

    + * + * @return a read-only version of this buffer. + * @since Android 1.0 */ + public abstract FloatBuffer asReadOnlyBuffer (); + + /** Compacts this float buffer. + *

    + * The remaining floats will be moved to the head of the buffer, starting from position zero. Then the position is set to + * {@code remaining()}; the limit is set to capacity; the mark is cleared. + *

    + * + * @return this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract FloatBuffer compact (); + + /** Compare the remaining floats of this buffer to another float buffer's remaining floats. + * + * @param otherBuffer another float buffer. + * @return a negative value if this is less than {@code otherBuffer}; 0 if this equals to {@code otherBuffer}; a positive value + * if this is greater than {@code otherBuffer}. + * @exception ClassCastException if {@code otherBuffer} is not a float buffer. + * @since Android 1.0 */ + public int compareTo (FloatBuffer otherBuffer) { + int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); + int thisPos = position; + int otherPos = otherBuffer.position; + // BEGIN android-changed + float thisFloat, otherFloat; + while (compareRemaining > 0) { + thisFloat = get(thisPos); + otherFloat = otherBuffer.get(otherPos); + // checks for float and NaN inequality + if ((thisFloat != otherFloat) && ((thisFloat == thisFloat) || (otherFloat == otherFloat))) { + return thisFloat < otherFloat ? -1 : 1; + } + thisPos++; + otherPos++; + compareRemaining--; + } + // END android-changed + return remaining() - otherBuffer.remaining(); + } + + /** Returns a duplicated buffer that shares its content with this buffer. + *

    + * The duplicated buffer's position, limit, capacity and mark are the same as this buffer. The duplicated buffer's read-only + * property and byte order are same as this buffer too. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a duplicated buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract FloatBuffer duplicate (); + + /** Checks whether this float buffer is equal to another object. + *

    + * If {@code other} is not a float buffer then {@code false} is returned. Two float buffers are equal if and only if their + * remaining floats are exactly the same. Position, limit, capacity and mark are not considered. + *

    + * + * @param other the object to compare with this float buffer. + * @return {@code true} if this float buffer is equal to {@code other}, {@code false} otherwise. + * @since Android 1.0 */ + public boolean equals (Object other) { + if (!(other instanceof FloatBuffer)) { + return false; + } + FloatBuffer otherBuffer = (FloatBuffer)other; + + if (remaining() != otherBuffer.remaining()) { + return false; + } + + int myPosition = position; + int otherPosition = otherBuffer.position; + boolean equalSoFar = true; + while (equalSoFar && (myPosition < limit)) { + equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); + } + + return equalSoFar; + } + + /** Returns the float at the current position and increases the position by 1. + * + * @return the float at the current position. + * @exception BufferUnderflowException if the position is equal or greater than limit. + * @since Android 1.0 */ + public abstract float get (); + + /** Reads floats from the current position into the specified float array and increases the position by the number of floats + * read. + *

    + * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. + *

    + * + * @param dest the destination float array. + * @return this buffer. + * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. + * @since Android 1.0 */ + public FloatBuffer get (float[] dest) { + return get(dest, 0, dest.length); + } + + /** Reads floats from the current position into the specified float array, starting from the specified offset, and increases the + * position by the number of floats read. + * + * @param dest the target float array. + * @param off the offset of the float array, must not be negative and no greater than {@code dest.length}. + * @param len the number of floats to read, must be no less than zero and no greater than {@code dest.length - off}. + * @return this buffer. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. + * @since Android 1.0 */ + public FloatBuffer get (float[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferUnderflowException(); + } + for (int i = off; i < off + len; i++) { + dest[i] = get(); + } + return this; + } + + /** Returns a float at the specified index; the position is not changed. + * + * @param index the index, must not be negative and less than limit. + * @return a float at the specified index. + * @exception IndexOutOfBoundsException if index is invalid. + * @since Android 1.0 */ + public abstract float get (int index); + + /** Indicates whether this buffer is based on a float array and is read/write. + * + * @return {@code true} if this buffer is based on a float array and provides read/write access, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasArray () { + return protectedHasArray(); + } + +// /** +// * Calculates this buffer's hash code from the remaining chars. The +// * position, limit, capacity and mark don't affect the hash code. +// * +// * @return the hash code calculated from the remaining floats. +// * @since Android 1.0 +// */ +// public int hashCode() { +// int myPosition = position; +// int hash = 0; +// while (myPosition < limit) { +// hash = hash + Float.floatToIntBits(get(myPosition++)); +// } +// return hash; +// } + + /** Indicates whether this buffer is direct. A direct buffer will try its best to take advantage of native memory APIs and it + * may not stay in the Java heap, so it is not affected by garbage collection. + *

    + * A float buffer is direct if it is based on a byte buffer and the byte buffer is direct. + *

    + * + * @return {@code true} if this buffer is direct, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isDirect (); + + /** Returns the byte order used by this buffer when converting floats from/to bytes. + *

    + * If this buffer is not based on a byte buffer, then always return the platform's native byte order. + *

    + * + * @return the byte order used by this buffer when converting floats from/to bytes. + * @since Android 1.0 */ + public abstract ByteOrder order (); + + /** Child class implements this method to realize {@code array()}. + * + * @return see {@code array()} */ + abstract float[] protectedArray (); + + /** Child class implements this method to realize {@code arrayOffset()}. + * + * @return see {@code arrayOffset()} */ + abstract int protectedArrayOffset (); + + /** Child class implements this method to realize {@code hasArray()}. + * + * @return see {@code hasArray()} */ + abstract boolean protectedHasArray (); + + /** Writes the given float to the current position and increases the position by 1. + * + * @param f the float to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract FloatBuffer put (float f); + + /** Writes floats from the given float array to the current position and increases the position by the number of floats written. + *

    + * Calling this method has the same effect as {@code put(src, 0, src.length)}. + *

    + * + * @param src the source float array. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final FloatBuffer put (float[] src) { + return put(src, 0, src.length); + } + + /** Writes floats from the given float array, starting from the specified offset, to the current position and increases the + * position by the number of floats written. + * + * @param src the source float array. + * @param off the offset of float array, must not be negative and not greater than {@code src.length}. + * @param len the number of floats to write, must be no less than zero and no greater than {@code src.length - off}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public FloatBuffer put (float[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + for (int i = off; i < off + len; i++) { + put(src[i]); + } + return this; + } + + /** Writes all the remaining floats of the {@code src} float buffer to this buffer's current position, and increases both + * buffers' position by the number of floats copied. + * + * @param src the source float buffer. + * @return this buffer. + * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. + * @exception IllegalArgumentException if {@code src} is this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public FloatBuffer put (FloatBuffer src) { + if (src == this) { + throw new IllegalArgumentException(); + } + if (src.remaining() > remaining()) { + throw new BufferOverflowException(); + } + float[] contents = new float[src.remaining()]; + src.get(contents); + put(contents); + return this; + } + + /** Writes a float to the specified index of this buffer; the position is not changed. + * + * @param index the index, must not be negative and less than the limit. + * @param f the float to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if index is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract FloatBuffer put (int index, float f); + + /** Returns a sliced buffer that shares its content with this buffer. + *

    + * The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero position will correspond to this + * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new + * buffer's read-only property and byte order are same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a sliced buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract FloatBuffer slice (); + + /** Returns a string representing the state of this float buffer. + * + * @return a string representing the state of this float buffer. + * @since Android 1.0 */ + public String toString () { + StringBuffer buf = new StringBuffer(); + buf.append(getClass().getName()); + buf.append(", status: capacity="); //$NON-NLS-1$ + buf.append(capacity()); + buf.append(" position="); //$NON-NLS-1$ + buf.append(position()); + buf.append(" limit="); //$NON-NLS-1$ + buf.append(limit()); + return buf.toString(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatToByteBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatToByteBufferAdapter.java index 0c19d8fd191..c0722b7ae3d 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatToByteBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/FloatToByteBufferAdapter.java @@ -19,188 +19,183 @@ //import org.apache.harmony.nio.internal.DirectBuffer; //import org.apache.harmony.luni.platform.PlatformAddress; -/** - * This class wraps a byte buffer to be a float buffer. +/** This class wraps a byte buffer to be a float buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class FloatToByteBufferAdapter extends FloatBuffer { -// implements DirectBuffer { - - static FloatBuffer wrap(ByteBuffer byteBuffer) { - return new FloatToByteBufferAdapter(byteBuffer.slice()); - } - - private final ByteBuffer byteBuffer; - - FloatToByteBufferAdapter(ByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 2)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - } - -// public int getByteCapacity() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getByteCapacity(); -// } -// assert false : byteBuffer; -// return -1; -// } +// implements DirectBuffer { + + static FloatBuffer wrap (ByteBuffer byteBuffer) { + return new FloatToByteBufferAdapter(byteBuffer.slice()); + } + + private final ByteBuffer byteBuffer; + + FloatToByteBufferAdapter (ByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 2)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + } + +// public int getByteCapacity() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getByteCapacity(); +// } +// assert false : byteBuffer; +// return -1; +// } // -// public PlatformAddress getEffectiveAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getEffectiveAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public PlatformAddress getBaseAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getBaseAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getBaseAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getBaseAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public boolean isAddressValid() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).isAddressValid(); -// } -// assert false : byteBuffer; -// return false; -// } +// public boolean isAddressValid() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).isAddressValid(); +// } +// assert false : byteBuffer; +// return false; +// } // -// public void addressValidityCheck() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).addressValidityCheck(); -// } else { -// assert false : byteBuffer; -// } -// } +// public void addressValidityCheck() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).addressValidityCheck(); +// } else { +// assert false : byteBuffer; +// } +// } // -// public void free() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).free(); -// } else { -// assert false : byteBuffer; -// } -// } - - @Override - public FloatBuffer asReadOnlyBuffer() { - FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer - .asReadOnlyBuffer()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public FloatBuffer compact() { - if (byteBuffer.isReadOnly()) { - throw new ReadOnlyBufferException(); - } - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public FloatBuffer duplicate() { - FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer - .duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public float get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return byteBuffer.getFloat(position++ << 2); - } - - @Override - public float get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return byteBuffer.getFloat(index << 2); - } - - @Override - public boolean isDirect() { - return byteBuffer.isDirect(); - } - - @Override - public boolean isReadOnly() { - return byteBuffer.isReadOnly(); - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected float[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public FloatBuffer put(float c) { - if (position == limit) { - throw new BufferOverflowException(); - } - byteBuffer.putFloat(position++ << 2, c); - return this; - } - - @Override - public FloatBuffer put(int index, float c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - byteBuffer.putFloat(index << 2, c); - return this; - } - - @Override - public FloatBuffer slice() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - FloatBuffer result = new FloatToByteBufferAdapter(byteBuffer.slice()); - byteBuffer.clear(); - return result; - } +// public void free() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).free(); +// } else { +// assert false : byteBuffer; +// } +// } + + @Override + public FloatBuffer asReadOnlyBuffer () { + FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer.asReadOnlyBuffer()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public FloatBuffer compact () { + if (byteBuffer.isReadOnly()) { + throw new ReadOnlyBufferException(); + } + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public FloatBuffer duplicate () { + FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public float get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return byteBuffer.getFloat(position++ << 2); + } + + @Override + public float get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return byteBuffer.getFloat(index << 2); + } + + @Override + public boolean isDirect () { + return byteBuffer.isDirect(); + } + + @Override + public boolean isReadOnly () { + return byteBuffer.isReadOnly(); + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected float[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public FloatBuffer put (float c) { + if (position == limit) { + throw new BufferOverflowException(); + } + byteBuffer.putFloat(position++ << 2, c); + return this; + } + + @Override + public FloatBuffer put (int index, float c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + byteBuffer.putFloat(index << 2, c); + return this; + } + + @Override + public FloatBuffer slice () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + FloatBuffer result = new FloatToByteBufferAdapter(byteBuffer.slice()); + byteBuffer.clear(); + return result; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HasArrayBufferView.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HasArrayBufferView.java index 14a9bef24eb..16afdfe0350 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HasArrayBufferView.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HasArrayBufferView.java @@ -1,9 +1,11 @@ + package java.nio; import gwt.g3d.client.gl2.array.ArrayBufferView; public interface HasArrayBufferView { - public ArrayBufferView getTypedArray(); - public int getElementSize(); + public ArrayBufferView getTypedArray (); + + public int getElementSize (); } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HeapByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HeapByteBuffer.java index e0fb524f75f..3c90ff87642 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HeapByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/HeapByteBuffer.java @@ -20,232 +20,227 @@ import com.google.gwt.corp.compatibility.Endianness; import com.google.gwt.corp.compatibility.Numbers; -/** - * HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose - * the implementation of array based byte buffers. +/** HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose the implementation of array based byte buffers. *

    - * HeapByteBuffer implements all the shared readonly methods and is extended by - * the other two classes. + * HeapByteBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class HeapByteBuffer extends BaseByteBuffer { - protected final byte[] backingArray; - - protected final int offset; - - HeapByteBuffer(byte[] backingArray) { - this(backingArray, backingArray.length, 0); - } - - HeapByteBuffer(int capacity) { - this(new byte[capacity], capacity, 0); - } - - HeapByteBuffer(byte[] backingArray, int capacity, int offset) { - super(capacity); - this.backingArray = backingArray; - this.offset = offset; - - if (offset + capacity > backingArray.length) { - throw new IndexOutOfBoundsException(); - } - } - - /* - * Override ByteBuffer.get(byte[], int, int) to improve performance. - * - * (non-Javadoc) - * - * @see java.nio.ByteBuffer#get(byte[], int, int) - */ - public final ByteBuffer get(byte[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - System.arraycopy(backingArray, offset + position, dest, off, len); - position += len; - return this; - } - - public final byte get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return backingArray[offset + position++]; - } - - public final byte get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return backingArray[offset + index]; - } - - public final double getDouble() { - return Numbers.longBitsToDouble(getLong()); - } - - public final double getDouble(int index) { - return Numbers.longBitsToDouble(getLong(index)); - } - - public final float getFloat() { - return Numbers.intBitsToFloat(getInt()); - } - - public final float getFloat(int index) { - return Numbers.intBitsToFloat(getInt(index)); - } - - public final int getInt() { - int newPosition = position + 4; - if (newPosition > limit) { - throw new BufferUnderflowException(); - } - int result = loadInt(position); - position = newPosition; - return result; - } - - public final int getInt(int index) { - if (index < 0 || index + 4 > limit) { - throw new IndexOutOfBoundsException(); - } - return loadInt(index); - } - - public final long getLong() { - int newPosition = position + 8; - if (newPosition > limit) { - throw new BufferUnderflowException(); - } - long result = loadLong(position); - position = newPosition; - return result; - } - - public final long getLong(int index) { - if (index < 0 || index + 8 > limit) { - throw new IndexOutOfBoundsException(); - } - return loadLong(index); - } - - public final short getShort() { - int newPosition = position + 2; - if (newPosition > limit) { - throw new BufferUnderflowException(); - } - short result = loadShort(position); - position = newPosition; - return result; - } - - public final short getShort(int index) { - if (index < 0 || index + 2 > limit) { - throw new IndexOutOfBoundsException(); - } - return loadShort(index); - } - - public final boolean isDirect() { - return false; - } - - protected final int loadInt(int index) { - int baseOffset = offset + index; - int bytes = 0; - if(order == Endianness.BIG_ENDIAN){ - for (int i = 0; i < 4; i++) { - bytes = bytes << 8; - bytes = bytes | (backingArray[baseOffset + i] & 0xFF); - } - }else{ - for (int i = 3; i >= 0; i--) { - bytes = bytes << 8; - bytes = bytes | (backingArray[baseOffset + i] & 0xFF); - } - } - return bytes; - } - - protected final long loadLong(int index) { - int baseOffset = offset + index; - long bytes = 0; - if(order == Endianness.BIG_ENDIAN){ - for (int i = 0; i < 8; i++) { - bytes = bytes << 8; - bytes = bytes | (backingArray[baseOffset + i] & 0xFF); - } - }else{ - for (int i = 7; i >= 0; i--) { - bytes = bytes << 8; - bytes = bytes | (backingArray[baseOffset + i] & 0xFF); - } - } - return bytes; - } - - protected final short loadShort(int index) { - int baseOffset = offset + index; - short bytes = 0; - if(order == Endianness.BIG_ENDIAN){ - bytes = (short) (backingArray[baseOffset] << 8); - bytes |= (backingArray[baseOffset + 1] & 0xFF); - }else{ - bytes = (short) (backingArray[baseOffset+1] << 8); - bytes |= (backingArray[baseOffset] & 0xFF); - } - return bytes; - } - - protected final void store(int index, int value) { - int baseOffset = offset + index; - if (order == Endianness.BIG_ENDIAN) { - for (int i = 3; i >= 0; i--) { - backingArray[baseOffset + i] = (byte) (value & 0xFF); - value = value >> 8; - } - } else { - for (int i = 0; i <= 3; i++) { - backingArray[baseOffset + i] = (byte) (value & 0xFF); - value = value >> 8; - } - } - } - - protected final void store(int index, long value) { - int baseOffset = offset + index; - if (order == Endianness.BIG_ENDIAN) { - for (int i = 7; i >= 0; i--) { - backingArray[baseOffset + i] = (byte) (value & 0xFF); - value = value >> 8; - } - } else { - for (int i = 0; i <= 7; i++) { - backingArray[baseOffset + i] = (byte) (value & 0xFF); - value = value >> 8; - } - } - } - - protected final void store(int index, short value) { - int baseOffset = offset + index; - if (order == Endianness.BIG_ENDIAN) { - backingArray[baseOffset] = (byte) ((value >> 8) & 0xFF); - backingArray[baseOffset + 1] = (byte) (value & 0xFF); - } else { - backingArray[baseOffset+1] = (byte) ((value >> 8) & 0xFF); - backingArray[baseOffset] = (byte) (value & 0xFF); - } - } + protected final byte[] backingArray; + + protected final int offset; + + HeapByteBuffer (byte[] backingArray) { + this(backingArray, backingArray.length, 0); + } + + HeapByteBuffer (int capacity) { + this(new byte[capacity], capacity, 0); + } + + HeapByteBuffer (byte[] backingArray, int capacity, int offset) { + super(capacity); + this.backingArray = backingArray; + this.offset = offset; + + if (offset + capacity > backingArray.length) { + throw new IndexOutOfBoundsException(); + } + } + + /* + * Override ByteBuffer.get(byte[], int, int) to improve performance. + * + * (non-Javadoc) + * + * @see java.nio.ByteBuffer#get(byte[], int, int) + */ + public final ByteBuffer get (byte[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + System.arraycopy(backingArray, offset + position, dest, off, len); + position += len; + return this; + } + + public final byte get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return backingArray[offset + position++]; + } + + public final byte get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return backingArray[offset + index]; + } + + public final double getDouble () { + return Numbers.longBitsToDouble(getLong()); + } + + public final double getDouble (int index) { + return Numbers.longBitsToDouble(getLong(index)); + } + + public final float getFloat () { + return Numbers.intBitsToFloat(getInt()); + } + + public final float getFloat (int index) { + return Numbers.intBitsToFloat(getInt(index)); + } + + public final int getInt () { + int newPosition = position + 4; + if (newPosition > limit) { + throw new BufferUnderflowException(); + } + int result = loadInt(position); + position = newPosition; + return result; + } + + public final int getInt (int index) { + if (index < 0 || index + 4 > limit) { + throw new IndexOutOfBoundsException(); + } + return loadInt(index); + } + + public final long getLong () { + int newPosition = position + 8; + if (newPosition > limit) { + throw new BufferUnderflowException(); + } + long result = loadLong(position); + position = newPosition; + return result; + } + + public final long getLong (int index) { + if (index < 0 || index + 8 > limit) { + throw new IndexOutOfBoundsException(); + } + return loadLong(index); + } + + public final short getShort () { + int newPosition = position + 2; + if (newPosition > limit) { + throw new BufferUnderflowException(); + } + short result = loadShort(position); + position = newPosition; + return result; + } + + public final short getShort (int index) { + if (index < 0 || index + 2 > limit) { + throw new IndexOutOfBoundsException(); + } + return loadShort(index); + } + + public final boolean isDirect () { + return false; + } + + protected final int loadInt (int index) { + int baseOffset = offset + index; + int bytes = 0; + if (order == Endianness.BIG_ENDIAN) { + for (int i = 0; i < 4; i++) { + bytes = bytes << 8; + bytes = bytes | (backingArray[baseOffset + i] & 0xFF); + } + } else { + for (int i = 3; i >= 0; i--) { + bytes = bytes << 8; + bytes = bytes | (backingArray[baseOffset + i] & 0xFF); + } + } + return bytes; + } + + protected final long loadLong (int index) { + int baseOffset = offset + index; + long bytes = 0; + if (order == Endianness.BIG_ENDIAN) { + for (int i = 0; i < 8; i++) { + bytes = bytes << 8; + bytes = bytes | (backingArray[baseOffset + i] & 0xFF); + } + } else { + for (int i = 7; i >= 0; i--) { + bytes = bytes << 8; + bytes = bytes | (backingArray[baseOffset + i] & 0xFF); + } + } + return bytes; + } + + protected final short loadShort (int index) { + int baseOffset = offset + index; + short bytes = 0; + if (order == Endianness.BIG_ENDIAN) { + bytes = (short)(backingArray[baseOffset] << 8); + bytes |= (backingArray[baseOffset + 1] & 0xFF); + } else { + bytes = (short)(backingArray[baseOffset + 1] << 8); + bytes |= (backingArray[baseOffset] & 0xFF); + } + return bytes; + } + + protected final void store (int index, int value) { + int baseOffset = offset + index; + if (order == Endianness.BIG_ENDIAN) { + for (int i = 3; i >= 0; i--) { + backingArray[baseOffset + i] = (byte)(value & 0xFF); + value = value >> 8; + } + } else { + for (int i = 0; i <= 3; i++) { + backingArray[baseOffset + i] = (byte)(value & 0xFF); + value = value >> 8; + } + } + } + + protected final void store (int index, long value) { + int baseOffset = offset + index; + if (order == Endianness.BIG_ENDIAN) { + for (int i = 7; i >= 0; i--) { + backingArray[baseOffset + i] = (byte)(value & 0xFF); + value = value >> 8; + } + } else { + for (int i = 0; i <= 7; i++) { + backingArray[baseOffset + i] = (byte)(value & 0xFF); + value = value >> 8; + } + } + } + + protected final void store (int index, short value) { + int baseOffset = offset + index; + if (order == Endianness.BIG_ENDIAN) { + backingArray[baseOffset] = (byte)((value >> 8) & 0xFF); + backingArray[baseOffset + 1] = (byte)(value & 0xFF); + } else { + backingArray[baseOffset + 1] = (byte)((value >> 8) & 0xFF); + backingArray[baseOffset] = (byte)(value & 0xFF); + } + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntArrayBuffer.java index d77268e4566..10a62ad4289 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntArrayBuffer.java @@ -15,73 +15,68 @@ * limitations under the License. */ -package java.nio; +package java.nio; -/** - * IntArrayBuffer, ReadWriteIntArrayBuffer and ReadOnlyIntArrayBuffer compose - * the implementation of array based int buffers. +/** IntArrayBuffer, ReadWriteIntArrayBuffer and ReadOnlyIntArrayBuffer compose the implementation of array based int buffers. *

    - * IntArrayBuffer implements all the shared readonly methods and is extended by - * the other two classes. + * IntArrayBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class IntArrayBuffer extends IntBuffer { - protected final int[] backingArray; + protected final int[] backingArray; + + protected final int offset; - protected final int offset; + IntArrayBuffer (int[] array) { + this(array.length, array, 0); + } - IntArrayBuffer(int[] array) { - this(array.length, array, 0); - } + IntArrayBuffer (int capacity) { + this(capacity, new int[capacity], 0); + } - IntArrayBuffer(int capacity) { - this(capacity, new int[capacity], 0); - } + IntArrayBuffer (int capacity, int[] backingArray, int offset) { + super(capacity); + this.backingArray = backingArray; + this.offset = offset; + } - IntArrayBuffer(int capacity, int[] backingArray, int offset) { - super(capacity); - this.backingArray = backingArray; - this.offset = offset; - } + public final int get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return backingArray[offset + position++]; + } - public final int get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return backingArray[offset + position++]; - } + public final int get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return backingArray[offset + index]; + } - public final int get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return backingArray[offset + index]; - } + public final IntBuffer get (int[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)len + (long)off > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + System.arraycopy(backingArray, offset + position, dest, off, len); + position += len; + return this; + } - public final IntBuffer get(int[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)len + (long)off > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - System.arraycopy(backingArray, offset+position, dest, off, len); - position += len; - return this; - } - - public final boolean isDirect() { - return false; - } + public final boolean isDirect () { + return false; + } - public final ByteOrder order() { - return ByteOrder.nativeOrder(); - } + public final ByteOrder order () { + return ByteOrder.nativeOrder(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntBuffer.java index 60f8a0263b4..b88e59ed07f 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntBuffer.java @@ -17,559 +17,413 @@ package java.nio; -/** - * A buffer of ints. +/** A buffer of ints. *

    * A int buffer can be created in either of the following ways: *

    *
      - *
    • {@link #allocate(int) Allocate} a new int array and create a buffer - * based on it;
    • + *
    • {@link #allocate(int) Allocate} a new int array and create a buffer based on it;
    • *
    • {@link #wrap(int[]) Wrap} an existing int array to create a new buffer;
    • - *
    • Use {@link java.nio.ByteBuffer#asIntBuffer() ByteBuffer.asIntBuffer} to - * create a int buffer based on a byte buffer.
    • + *
    • Use {@link java.nio.ByteBuffer#asIntBuffer() ByteBuffer.asIntBuffer} to create a int buffer based on a byte buffer.
    • *
    * - * @since Android 1.0 - */ + * @since Android 1.0 */ public abstract class IntBuffer extends Buffer implements Comparable { - /** - * Creates an int buffer based on a newly allocated int array. - * - * @param capacity - * the capacity of the new buffer. - * @return the created int buffer. - * @throws IllegalArgumentException - * if {@code capacity} is less than zero. - * @since Android 1.0 - */ - public static IntBuffer allocate(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newIntBuffer(capacity); - } - - /** - * Creates a new int buffer by wrapping the given int array. - *

    - * Calling this method has the same effect as - * {@code wrap(array, 0, array.length)}. - *

    - * - * @param array - * the int array which the new buffer will be based on. - * @return the created int buffer. - * @since Android 1.0 - */ - public static IntBuffer wrap(int[] array) { - return wrap(array, 0, array.length); - } - - /** - * Creates a new int buffer by wrapping the given int array. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code start + len}, capacity will be the length of the array. - *

    - * - * @param array - * the int array which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code array.length} - * @param len - * the length, must not be negative and not greater than - * {@code array.length - start}. - * @return the created int buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code len} is invalid. - * @since Android 1.0 - */ - public static IntBuffer wrap(int[] array, int start, int len) { - if (array == null) { - throw new NullPointerException(); - } - if (start < 0 || len < 0 || (long)len + (long)start > array.length) { - throw new IndexOutOfBoundsException(); - } - - IntBuffer buf = BufferFactory.newIntBuffer(array); - buf.position = start; - buf.limit = start + len; - - return buf; - } - - /** - * Constructs a {@code IntBuffer} with given capacity. - * - * @param capacity - * the capacity of the buffer. - */ - IntBuffer(int capacity) { - super(capacity); - } - - /** - * Returns the int array which this buffer is based on, if there is one. - * - * @return the int array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int[] array() { - return protectedArray(); - } - - /** - * Returns the offset of the int array which this buffer is based on, if - * there is one. - *

    - * The offset is the index of the array corresponds to the zero position of - * the buffer. - *

    - * - * @return the offset of the int array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int arrayOffset() { - return protectedArrayOffset(); - } - - /** - * Returns a read-only buffer that shares its content with this buffer. - *

    - * The returned buffer is guaranteed to be a new instance, even this buffer - * is read-only itself. The new buffer's position, limit, capacity and mark - * are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means this - * buffer's change of content will be visible to the new buffer. The two - * buffer's position, limit and mark are independent. - *

    - * - * @return a read-only version of this buffer. - * @since Android 1.0 - */ - public abstract IntBuffer asReadOnlyBuffer(); - - /** - * Compacts this int buffer. - *

    - * The remaining ints will be moved to the head of the buffer, starting from - * position zero. Then the position is set to {@code remaining()}; the - * limit is set to capacity; the mark is cleared. - *

    - * - * @return this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract IntBuffer compact(); - - /** - * Compares the remaining ints of this buffer to another int buffer's - * remaining ints. - * - * @param otherBuffer - * another int buffer. - * @return a negative value if this is less than {@code other}; 0 if this - * equals to {@code other}; a positive value if this is greater - * than {@code other}. - * @exception ClassCastException - * if {@code other} is not an int buffer. - * @since Android 1.0 - */ - public int compareTo(IntBuffer otherBuffer) { - int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() - : otherBuffer.remaining(); - int thisPos = position; - int otherPos = otherBuffer.position; - // BEGIN android-changed - int thisInt, otherInt; - while (compareRemaining > 0) { - thisInt = get(thisPos); - otherInt = otherBuffer.get(otherPos); - if (thisInt != otherInt) { - return thisInt < otherInt ? -1 : 1; - } - thisPos++; - otherPos++; - compareRemaining--; - } - // END android-changed - return remaining() - otherBuffer.remaining(); - } - - /** - * Returns a duplicated buffer that shares its content with this buffer. - *

    - * The duplicated buffer's position, limit, capacity and mark are the same - * as this buffer. The duplicated buffer's read-only property and byte order - * are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a duplicated buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract IntBuffer duplicate(); - - /** - * Checks whether this int buffer is equal to another object. - *

    - * If {@code other} is not a int buffer then {@code false} is returned. Two - * int buffers are equal if and only if their remaining ints are exactly the - * same. Position, limit, capacity and mark are not considered. - *

    - * - * @param other - * the object to compare with this int buffer. - * @return {@code true} if this int buffer is equal to {@code other}, - * {@code false} otherwise. - * @since Android 1.0 - */ - public boolean equals(Object other) { - if (!(other instanceof IntBuffer)) { - return false; - } - IntBuffer otherBuffer = (IntBuffer) other; - - if (remaining() != otherBuffer.remaining()) { - return false; - } - - int myPosition = position; - int otherPosition = otherBuffer.position; - boolean equalSoFar = true; - while (equalSoFar && (myPosition < limit)) { - equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); - } - - return equalSoFar; - } - - /** - * Returns the int at the current position and increases the position by 1. - * - * @return the int at the current position. - * @exception BufferUnderflowException - * if the position is equal or greater than limit. - * @since Android 1.0 - */ - public abstract int get(); - - /** - * Reads ints from the current position into the specified int array and - * increases the position by the number of ints read. - *

    - * Calling this method has the same effect as - * {@code get(dest, 0, dest.length)}. - *

    - * - * @param dest - * the destination int array. - * @return this buffer. - * @exception BufferUnderflowException - * if {@code dest.length} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public IntBuffer get(int[] dest) { - return get(dest, 0, dest.length); - } - - /** - * Reads ints from the current position into the specified int array, - * starting from the specified offset, and increases the position by the - * number of ints read. - * - * @param dest - * the target int array. - * @param off - * the offset of the int array, must not be negative and not - * greater than {@code dest.length}. - * @param len - * the number of ints to read, must be no less than zero and not - * greater than {@code dest.length - off}. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception BufferUnderflowException - * if {@code len} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public IntBuffer get(int[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)len + (long)off > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - for (int i = off; i < off + len; i++) { - dest[i] = get(); - } - return this; - } - - /** - * Returns an int at the specified index; the position is not changed. - * - * @param index - * the index, must not be negative and less than limit. - * @return an int at the specified index. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @since Android 1.0 - */ - public abstract int get(int index); - - /** - * Indicates whether this buffer is based on a int array and is read/write. - * - * @return {@code true} if this buffer is based on a int array and provides - * read/write access, {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasArray() { - return protectedHasArray(); - } - - /** - * Calculates this buffer's hash code from the remaining chars. The - * position, limit, capacity and mark don't affect the hash code. - * - * @return the hash code calculated from the remaining ints. - * @since Android 1.0 - */ - public int hashCode() { - int myPosition = position; - int hash = 0; - while (myPosition < limit) { - hash = hash + get(myPosition++); - } - return hash; - } - - /** - * Indicates whether this buffer is direct. A direct buffer will try its - * best to take advantage of native memory APIs and it may not stay in the - * Java heap, so it is not affected by garbage collection. - *

    - * An int buffer is direct if it is based on a byte buffer and the byte - * buffer is direct. - *

    - * - * @return {@code true} if this buffer is direct, {@code false} otherwise. - * @since Android 1.0 - */ - public abstract boolean isDirect(); - - /** - * Returns the byte order used by this buffer when converting ints from/to - * bytes. - *

    - * If this buffer is not based on a byte buffer, then always return the - * platform's native byte order. - *

    - * - * @return the byte order used by this buffer when converting ints from/to - * bytes. - * @since Android 1.0 - */ - public abstract ByteOrder order(); - - /** - * Child class implements this method to realize {@code array()}. - * - * @return see {@code array()} - */ - protected abstract int[] protectedArray(); - - /** - * Child class implements this method to realize {@code arrayOffset()}. - * - * @return see {@code arrayOffset()} - */ - protected abstract int protectedArrayOffset(); - - /** - * Child class implements this method to realize {@code hasArray()}. - * - * @return see {@code hasArray()} - */ - protected abstract boolean protectedHasArray(); - - /** - * Writes the given int to the current position and increases the position - * by 1. - * - * @param i - * the int to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract IntBuffer put(int i); - - /** - * Writes ints from the given int array to the current position and - * increases the position by the number of ints written. - *

    - * Calling this method has the same effect as - * {@code put(src, 0, src.length)}. - *

    - * - * @param src - * the source int array. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code src.length}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final IntBuffer put(int[] src) { - return put(src, 0, src.length); - } - - /** - * Writes ints from the given int array, starting from the specified offset, - * to the current position and increases the position by the number of ints - * written. - * - * @param src - * the source int array. - * @param off - * the offset of int array, must not be negative and not greater - * than {@code src.length}. - * @param len - * the number of ints to write, must be no less than zero and not - * greater than {@code src.length - off}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code len}. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public IntBuffer put(int[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)len + (long)off > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - for (int i = off; i < off + len; i++) { - put(src[i]); - } - return this; - } - - /** - * Writes all the remaining ints of the {@code src} int buffer to this - * buffer's current position, and increases both buffers' position by the - * number of ints copied. - * - * @param src - * the source int buffer. - * @return this buffer. - * @exception BufferOverflowException - * if {@code src.remaining()} is greater than this buffer's - * {@code remaining()}. - * @exception IllegalArgumentException - * if {@code src} is this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public IntBuffer put(IntBuffer src) { - if (src == this) { - throw new IllegalArgumentException(); - } - if (src.remaining() > remaining()) { - throw new BufferOverflowException(); - } - int[] contents = new int[src.remaining()]; - src.get(contents); - put(contents); - return this; - } - - /** - * Write a int to the specified index of this buffer; the position is not - * changed. - * - * @param index - * the index, must not be negative and less than the limit. - * @param i - * the int to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract IntBuffer put(int index, int i); - - /** - * Returns a sliced buffer that shares its content with this buffer. - *

    - * The sliced buffer's capacity will be this buffer's {@code remaining()}, - * and its zero position will correspond to this buffer's current position. - * The new buffer's position will be 0, limit will be its capacity, and its - * mark is cleared. The new buffer's read-only property and byte order are - * same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a sliced buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract IntBuffer slice(); - - /** - * Returns a string represents of the state of this int buffer. - * - * @return a string represents of the state of this int buffer. - * @since Android 1.0 - */ - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append(getClass().getName()); - buf.append(", status: capacity="); //$NON-NLS-1$ - buf.append(capacity()); - buf.append(" position="); //$NON-NLS-1$ - buf.append(position()); - buf.append(" limit="); //$NON-NLS-1$ - buf.append(limit()); - return buf.toString(); - } + /** Creates an int buffer based on a newly allocated int array. + * + * @param capacity the capacity of the new buffer. + * @return the created int buffer. + * @throws IllegalArgumentException if {@code capacity} is less than zero. + * @since Android 1.0 */ + public static IntBuffer allocate (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newIntBuffer(capacity); + } + + /** Creates a new int buffer by wrapping the given int array. + *

    + * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. + *

    + * + * @param array the int array which the new buffer will be based on. + * @return the created int buffer. + * @since Android 1.0 */ + public static IntBuffer wrap (int[] array) { + return wrap(array, 0, array.length); + } + + /** Creates a new int buffer by wrapping the given int array. + *

    + * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the + * array. + *

    + * + * @param array the int array which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code array.length} + * @param len the length, must not be negative and not greater than {@code array.length - start}. + * @return the created int buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. + * @since Android 1.0 */ + public static IntBuffer wrap (int[] array, int start, int len) { + if (array == null) { + throw new NullPointerException(); + } + if (start < 0 || len < 0 || (long)len + (long)start > array.length) { + throw new IndexOutOfBoundsException(); + } + + IntBuffer buf = BufferFactory.newIntBuffer(array); + buf.position = start; + buf.limit = start + len; + + return buf; + } + + /** Constructs a {@code IntBuffer} with given capacity. + * + * @param capacity the capacity of the buffer. */ + IntBuffer (int capacity) { + super(capacity); + } + + /** Returns the int array which this buffer is based on, if there is one. + * + * @return the int array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int[] array () { + return protectedArray(); + } + + /** Returns the offset of the int array which this buffer is based on, if there is one. + *

    + * The offset is the index of the array corresponds to the zero position of the buffer. + *

    + * + * @return the offset of the int array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int arrayOffset () { + return protectedArrayOffset(); + } + + /** Returns a read-only buffer that shares its content with this buffer. + *

    + * The returned buffer is guaranteed to be a new instance, even this buffer is read-only itself. The new buffer's position, + * limit, capacity and mark are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means this buffer's change of content will be visible to the new + * buffer. The two buffer's position, limit and mark are independent. + *

    + * + * @return a read-only version of this buffer. + * @since Android 1.0 */ + public abstract IntBuffer asReadOnlyBuffer (); + + /** Compacts this int buffer. + *

    + * The remaining ints will be moved to the head of the buffer, starting from position zero. Then the position is set to + * {@code remaining()}; the limit is set to capacity; the mark is cleared. + *

    + * + * @return this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract IntBuffer compact (); + + /** Compares the remaining ints of this buffer to another int buffer's remaining ints. + * + * @param otherBuffer another int buffer. + * @return a negative value if this is less than {@code other}; 0 if this equals to {@code other}; a positive value if this is + * greater than {@code other}. + * @exception ClassCastException if {@code other} is not an int buffer. + * @since Android 1.0 */ + public int compareTo (IntBuffer otherBuffer) { + int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); + int thisPos = position; + int otherPos = otherBuffer.position; + // BEGIN android-changed + int thisInt, otherInt; + while (compareRemaining > 0) { + thisInt = get(thisPos); + otherInt = otherBuffer.get(otherPos); + if (thisInt != otherInt) { + return thisInt < otherInt ? -1 : 1; + } + thisPos++; + otherPos++; + compareRemaining--; + } + // END android-changed + return remaining() - otherBuffer.remaining(); + } + + /** Returns a duplicated buffer that shares its content with this buffer. + *

    + * The duplicated buffer's position, limit, capacity and mark are the same as this buffer. The duplicated buffer's read-only + * property and byte order are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a duplicated buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract IntBuffer duplicate (); + + /** Checks whether this int buffer is equal to another object. + *

    + * If {@code other} is not a int buffer then {@code false} is returned. Two int buffers are equal if and only if their + * remaining ints are exactly the same. Position, limit, capacity and mark are not considered. + *

    + * + * @param other the object to compare with this int buffer. + * @return {@code true} if this int buffer is equal to {@code other}, {@code false} otherwise. + * @since Android 1.0 */ + public boolean equals (Object other) { + if (!(other instanceof IntBuffer)) { + return false; + } + IntBuffer otherBuffer = (IntBuffer)other; + + if (remaining() != otherBuffer.remaining()) { + return false; + } + + int myPosition = position; + int otherPosition = otherBuffer.position; + boolean equalSoFar = true; + while (equalSoFar && (myPosition < limit)) { + equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); + } + + return equalSoFar; + } + + /** Returns the int at the current position and increases the position by 1. + * + * @return the int at the current position. + * @exception BufferUnderflowException if the position is equal or greater than limit. + * @since Android 1.0 */ + public abstract int get (); + + /** Reads ints from the current position into the specified int array and increases the position by the number of ints read. + *

    + * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. + *

    + * + * @param dest the destination int array. + * @return this buffer. + * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. + * @since Android 1.0 */ + public IntBuffer get (int[] dest) { + return get(dest, 0, dest.length); + } + + /** Reads ints from the current position into the specified int array, starting from the specified offset, and increases the + * position by the number of ints read. + * + * @param dest the target int array. + * @param off the offset of the int array, must not be negative and not greater than {@code dest.length}. + * @param len the number of ints to read, must be no less than zero and not greater than {@code dest.length - off}. + * @return this buffer. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. + * @since Android 1.0 */ + public IntBuffer get (int[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)len + (long)off > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + for (int i = off; i < off + len; i++) { + dest[i] = get(); + } + return this; + } + + /** Returns an int at the specified index; the position is not changed. + * + * @param index the index, must not be negative and less than limit. + * @return an int at the specified index. + * @exception IndexOutOfBoundsException if index is invalid. + * @since Android 1.0 */ + public abstract int get (int index); + + /** Indicates whether this buffer is based on a int array and is read/write. + * + * @return {@code true} if this buffer is based on a int array and provides read/write access, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasArray () { + return protectedHasArray(); + } + + /** Calculates this buffer's hash code from the remaining chars. The position, limit, capacity and mark don't affect the hash + * code. + * + * @return the hash code calculated from the remaining ints. + * @since Android 1.0 */ + public int hashCode () { + int myPosition = position; + int hash = 0; + while (myPosition < limit) { + hash = hash + get(myPosition++); + } + return hash; + } + + /** Indicates whether this buffer is direct. A direct buffer will try its best to take advantage of native memory APIs and it + * may not stay in the Java heap, so it is not affected by garbage collection. + *

    + * An int buffer is direct if it is based on a byte buffer and the byte buffer is direct. + *

    + * + * @return {@code true} if this buffer is direct, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isDirect (); + + /** Returns the byte order used by this buffer when converting ints from/to bytes. + *

    + * If this buffer is not based on a byte buffer, then always return the platform's native byte order. + *

    + * + * @return the byte order used by this buffer when converting ints from/to bytes. + * @since Android 1.0 */ + public abstract ByteOrder order (); + + /** Child class implements this method to realize {@code array()}. + * + * @return see {@code array()} */ + protected abstract int[] protectedArray (); + + /** Child class implements this method to realize {@code arrayOffset()}. + * + * @return see {@code arrayOffset()} */ + protected abstract int protectedArrayOffset (); + + /** Child class implements this method to realize {@code hasArray()}. + * + * @return see {@code hasArray()} */ + protected abstract boolean protectedHasArray (); + + /** Writes the given int to the current position and increases the position by 1. + * + * @param i the int to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract IntBuffer put (int i); + + /** Writes ints from the given int array to the current position and increases the position by the number of ints written. + *

    + * Calling this method has the same effect as {@code put(src, 0, src.length)}. + *

    + * + * @param src the source int array. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final IntBuffer put (int[] src) { + return put(src, 0, src.length); + } + + /** Writes ints from the given int array, starting from the specified offset, to the current position and increases the position + * by the number of ints written. + * + * @param src the source int array. + * @param off the offset of int array, must not be negative and not greater than {@code src.length}. + * @param len the number of ints to write, must be no less than zero and not greater than {@code src.length - off}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public IntBuffer put (int[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)len + (long)off > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + for (int i = off; i < off + len; i++) { + put(src[i]); + } + return this; + } + + /** Writes all the remaining ints of the {@code src} int buffer to this buffer's current position, and increases both buffers' + * position by the number of ints copied. + * + * @param src the source int buffer. + * @return this buffer. + * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. + * @exception IllegalArgumentException if {@code src} is this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public IntBuffer put (IntBuffer src) { + if (src == this) { + throw new IllegalArgumentException(); + } + if (src.remaining() > remaining()) { + throw new BufferOverflowException(); + } + int[] contents = new int[src.remaining()]; + src.get(contents); + put(contents); + return this; + } + + /** Write a int to the specified index of this buffer; the position is not changed. + * + * @param index the index, must not be negative and less than the limit. + * @param i the int to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if index is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract IntBuffer put (int index, int i); + + /** Returns a sliced buffer that shares its content with this buffer. + *

    + * The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero position will correspond to this + * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new + * buffer's read-only property and byte order are same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a sliced buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract IntBuffer slice (); + + /** Returns a string represents of the state of this int buffer. + * + * @return a string represents of the state of this int buffer. + * @since Android 1.0 */ + public String toString () { + StringBuffer buf = new StringBuffer(); + buf.append(getClass().getName()); + buf.append(", status: capacity="); //$NON-NLS-1$ + buf.append(capacity()); + buf.append(" position="); //$NON-NLS-1$ + buf.append(position()); + buf.append(" limit="); //$NON-NLS-1$ + buf.append(limit()); + return buf.toString(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntToByteBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntToByteBufferAdapter.java index 98faca97e1c..f2151ff5e77 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntToByteBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/IntToByteBufferAdapter.java @@ -16,195 +16,189 @@ package java.nio; - //import org.apache.harmony.nio.internal.DirectBuffer; //import org.apache.harmony.luni.platform.PlatformAddress; -/** - * This class wraps a byte buffer to be a int buffer. +/** This class wraps a byte buffer to be a int buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ + *

    */ final class IntToByteBufferAdapter extends IntBuffer implements ByteBufferWrapper { -//implements DirectBuffer { - - static IntBuffer wrap(ByteBuffer byteBuffer) { - return new IntToByteBufferAdapter(byteBuffer.slice()); - } - - private final ByteBuffer byteBuffer; - - IntToByteBufferAdapter(ByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 2)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - } - -// public int getByteCapacity() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getByteCapacity(); -// } -// assert false : byteBuffer; -// return -1; -// } +// implements DirectBuffer { + + static IntBuffer wrap (ByteBuffer byteBuffer) { + return new IntToByteBufferAdapter(byteBuffer.slice()); + } + + private final ByteBuffer byteBuffer; + + IntToByteBufferAdapter (ByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 2)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + } + +// public int getByteCapacity() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getByteCapacity(); +// } +// assert false : byteBuffer; +// return -1; +// } // -// public PlatformAddress getEffectiveAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getEffectiveAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public PlatformAddress getBaseAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getBaseAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getBaseAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getBaseAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public boolean isAddressValid() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).isAddressValid(); -// } -// assert false : byteBuffer; -// return false; -// } +// public boolean isAddressValid() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).isAddressValid(); +// } +// assert false : byteBuffer; +// return false; +// } // -// public void addressValidityCheck() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).addressValidityCheck(); -// } else { -// assert false : byteBuffer; -// } -// } +// public void addressValidityCheck() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).addressValidityCheck(); +// } else { +// assert false : byteBuffer; +// } +// } // -// public void free() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).free(); -// } else { -// assert false : byteBuffer; -// } -// } - - @Override - public IntBuffer asReadOnlyBuffer() { - IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer - .asReadOnlyBuffer()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public IntBuffer compact() { - if (byteBuffer.isReadOnly()) { - throw new ReadOnlyBufferException(); - } - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public IntBuffer duplicate() { - IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer - .duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public int get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return byteBuffer.getInt(position++ << 2); - } - - @Override - public int get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return byteBuffer.getInt(index << 2); - } - - @Override - public boolean isDirect() { - return byteBuffer.isDirect(); - } - - @Override - public boolean isReadOnly() { - return byteBuffer.isReadOnly(); - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected int[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public IntBuffer put(int c) { - if (position == limit) { - throw new BufferOverflowException(); - } - byteBuffer.putInt(position++ << 2, c); - return this; - } - - @Override - public IntBuffer put(int index, int c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - byteBuffer.putInt(index << 2, c); - return this; - } - - @Override - public IntBuffer slice() { - byteBuffer.limit(limit << 2); - byteBuffer.position(position << 2); - IntBuffer result = new IntToByteBufferAdapter(byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ByteBuffer getByteBuffer() { +// public void free() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).free(); +// } else { +// assert false : byteBuffer; +// } +// } + + @Override + public IntBuffer asReadOnlyBuffer () { + IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer.asReadOnlyBuffer()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public IntBuffer compact () { + if (byteBuffer.isReadOnly()) { + throw new ReadOnlyBufferException(); + } + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public IntBuffer duplicate () { + IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public int get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return byteBuffer.getInt(position++ << 2); + } + + @Override + public int get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return byteBuffer.getInt(index << 2); + } + + @Override + public boolean isDirect () { + return byteBuffer.isDirect(); + } + + @Override + public boolean isReadOnly () { + return byteBuffer.isReadOnly(); + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected int[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public IntBuffer put (int c) { + if (position == limit) { + throw new BufferOverflowException(); + } + byteBuffer.putInt(position++ << 2, c); + return this; + } + + @Override + public IntBuffer put (int index, int c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + byteBuffer.putInt(index << 2, c); + return this; + } + + @Override + public IntBuffer slice () { + byteBuffer.limit(limit << 2); + byteBuffer.position(position << 2); + IntBuffer result = new IntToByteBufferAdapter(byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ByteBuffer getByteBuffer () { return byteBuffer; } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/InvalidMarkException.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/InvalidMarkException.java index 530d9cfad00..a523dc5bcb4 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/InvalidMarkException.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/InvalidMarkException.java @@ -16,23 +16,17 @@ package java.nio; - -/** - * An {@code InvalidMarkException} is thrown when {@code reset()} is called on a - * buffer, but no mark has been set previously. +/** An {@code InvalidMarkException} is thrown when {@code reset()} is called on a buffer, but no mark has been set previously. * - * @since Android 1.0 - */ + * @since Android 1.0 */ public class InvalidMarkException extends IllegalStateException { - private static final long serialVersionUID = 1698329710438510774L; + private static final long serialVersionUID = 1698329710438510774L; - /** - * Constructs an {@code InvalidMarkException}. - * - * @since Android 1.0 - */ - public InvalidMarkException() { - super(); - } + /** Constructs an {@code InvalidMarkException}. + * + * @since Android 1.0 */ + public InvalidMarkException () { + super(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongArrayBuffer.java index efd259cc0fa..73c9be06a78 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongArrayBuffer.java @@ -17,71 +17,66 @@ package java.nio; -/** - * LongArrayBuffer, ReadWriteLongArrayBuffer and ReadOnlyLongArrayBuffer compose - * the implementation of array based long buffers. +/** LongArrayBuffer, ReadWriteLongArrayBuffer and ReadOnlyLongArrayBuffer compose the implementation of array based long buffers. *

    - * LongArrayBuffer implements all the shared readonly methods and is extended by - * the other two classes. + * LongArrayBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class LongArrayBuffer extends LongBuffer { - protected final long[] backingArray; + protected final long[] backingArray; + + protected final int offset; - protected final int offset; + LongArrayBuffer (long[] array) { + this(array.length, array, 0); + } - LongArrayBuffer(long[] array) { - this(array.length, array, 0); - } + LongArrayBuffer (int capacity) { + this(capacity, new long[capacity], 0); + } - LongArrayBuffer(int capacity) { - this(capacity, new long[capacity], 0); - } + LongArrayBuffer (int capacity, long[] backingArray, int offset) { + super(capacity); + this.backingArray = backingArray; + this.offset = offset; + } - LongArrayBuffer(int capacity, long[] backingArray, int offset) { - super(capacity); - this.backingArray = backingArray; - this.offset = offset; - } + public final long get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return backingArray[offset + position++]; + } - public final long get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return backingArray[offset + position++]; - } + public final long get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return backingArray[offset + index]; + } - public final long get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return backingArray[offset + index]; - } + public final LongBuffer get (long[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)len + (long)off > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + System.arraycopy(backingArray, offset + position, dest, off, len); + position += len; + return this; + } - public final LongBuffer get(long[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)len + (long)off > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - System.arraycopy(backingArray, offset+position, dest, off, len); - position += len; - return this; - } - - public final boolean isDirect() { - return false; - } + public final boolean isDirect () { + return false; + } - public final ByteOrder order() { - return ByteOrder.nativeOrder(); - } + public final ByteOrder order () { + return ByteOrder.nativeOrder(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongBuffer.java index 022db5bfeec..97a8a12be15 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongBuffer.java @@ -17,563 +17,416 @@ package java.nio; -/** - * A buffer of longs. +/** A buffer of longs. *

    * A long buffer can be created in either of the following ways: *

    *
      - *
    • {@link #allocate(int) Allocate} a new long array and create a buffer - * based on it;
    • - *
    • {@link #wrap(long[]) Wrap} an existing long array to create a new - * buffer;
    • - *
    • Use {@link java.nio.ByteBuffer#asLongBuffer() ByteBuffer.asLongBuffer} - * to create a long buffer based on a byte buffer.
    • + *
    • {@link #allocate(int) Allocate} a new long array and create a buffer based on it;
    • + *
    • {@link #wrap(long[]) Wrap} an existing long array to create a new buffer;
    • + *
    • Use {@link java.nio.ByteBuffer#asLongBuffer() ByteBuffer.asLongBuffer} to create a long buffer based on a byte buffer.
    • *
    * - * @since Android 1.0 - */ + * @since Android 1.0 */ public abstract class LongBuffer extends Buffer implements Comparable { - /** - * Creates a long buffer based on a newly allocated long array. - * - * @param capacity - * the capacity of the new buffer. - * @return the created long buffer. - * @throws IllegalArgumentException - * if {@code capacity} is less than zero. - * @since Android 1.0 - */ - public static LongBuffer allocate(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newLongBuffer(capacity); - } - - /** - * Creates a new long buffer by wrapping the given long array. - *

    - * Calling this method has the same effect as - * {@code wrap(array, 0, array.length)}. - *

    - * - * @param array - * the long array which the new buffer will be based on. - * @return the created long buffer. - * @since Android 1.0 - */ - public static LongBuffer wrap(long[] array) { - return wrap(array, 0, array.length); - } - - /** - * Creates a new long buffer by wrapping the given long array. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code start + len}, capacity will be the length of the array. - *

    - * - * @param array - * the long array which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code array.length}. - * @param len - * the length, must not be negative and not greater than - * {@code array.length - start}. - * @return the created long buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code len} is invalid. - * @since Android 1.0 - */ - public static LongBuffer wrap(long[] array, int start, int len) { - if (array == null) { - throw new NullPointerException(); - } - if (start < 0 || len < 0 || (long)len + (long)start > array.length) { - throw new IndexOutOfBoundsException(); - } - - LongBuffer buf = BufferFactory.newLongBuffer(array); - buf.position = start; - buf.limit = start + len; - - return buf; - } - - /** - * Constructs a {@code LongBuffer} with given capacity. - * - * @param capacity - * The capacity of the buffer - */ - LongBuffer(int capacity) { - super(capacity); - } - - /** - * Returns the long array which this buffer is based on, if there is one. - * - * @return the long array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final long[] array() { - return protectedArray(); - } - - /** - * Returns the offset of the long array which this buffer is based on, if - * there is one. - *

    - * The offset is the index of the array and corresponds to the zero position - * of the buffer. - *

    - * - * @return the offset of the long array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int arrayOffset() { - return protectedArrayOffset(); - } - - /** - * Returns a read-only buffer that shares its content with this buffer. - *

    - * The returned buffer is guaranteed to be a new instance, even if this - * buffer is read-only itself. The new buffer's position, limit, capacity - * and mark are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means this - * buffer's change of content will be visible to the new buffer. The two - * buffer's position, limit and mark are independent. - *

    - * - * @return a read-only version of this buffer. - * @since Android 1.0 - */ - public abstract LongBuffer asReadOnlyBuffer(); - - /** - * Compacts this long buffer. - *

    - * The remaining longs will be moved to the head of the buffer, staring from - * position zero. Then the position is set to {@code remaining()}; the - * limit is set to capacity; the mark is cleared. - *

    - * - * @return this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract LongBuffer compact(); - - /** - * Compare the remaining longs of this buffer to another long buffer's - * remaining longs. - * - * @param otherBuffer - * another long buffer. - * @return a negative value if this is less than {@code otherBuffer}; 0 if - * this equals to {@code otherBuffer}; a positive value if this is - * greater than {@code otherBuffer} - * @exception ClassCastException - * if {@code otherBuffer} is not a long buffer. - * @since Android 1.0 - */ - public int compareTo(LongBuffer otherBuffer) { - int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() - : otherBuffer.remaining(); - int thisPos = position; - int otherPos = otherBuffer.position; - // BEGIN android-changed - long thisLong, otherLong; - while (compareRemaining > 0) { - thisLong = get(thisPos); - otherLong = otherBuffer.get(otherPos); - if (thisLong != otherLong) { - return thisLong < otherLong ? -1 : 1; - } - thisPos++; - otherPos++; - compareRemaining--; - } - // END android-changed - return remaining() - otherBuffer.remaining(); - } - - /** - * Returns a duplicated buffer that shares its content with this buffer. - *

    - * The duplicated buffer's position, limit, capacity and mark are the same - * as this buffer. The duplicated buffer's read-only property and byte order - * are same as this buffer's, too. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a duplicated buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract LongBuffer duplicate(); - - /** - * Checks whether this long buffer is equal to another object. - *

    - * If {@code other} is not a long buffer then {@code false} is returned. Two - * long buffers are equal if and only if their remaining longs are exactly - * the same. Position, limit, capacity and mark are not considered. - *

    - * - * @param other - * the object to compare with this long buffer. - * @return {@code true} if this long buffer is equal to {@code other}, - * {@code false} otherwise. - * @since Android 1.0 - */ - public boolean equals(Object other) { - if (!(other instanceof LongBuffer)) { - return false; - } - LongBuffer otherBuffer = (LongBuffer) other; - - if (remaining() != otherBuffer.remaining()) { - return false; - } - - int myPosition = position; - int otherPosition = otherBuffer.position; - boolean equalSoFar = true; - while (equalSoFar && (myPosition < limit)) { - equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); - } - - return equalSoFar; - } - - /** - * Returns the long at the current position and increase the position by 1. - * - * @return the long at the current position. - * @exception BufferUnderflowException - * if the position is equal or greater than limit. - * @since Android 1.0 - */ - public abstract long get(); - - /** - * Reads longs from the current position into the specified long array and - * increases the position by the number of longs read. - *

    - * Calling this method has the same effect as - * {@code get(dest, 0, dest.length)}. - *

    - * - * @param dest - * the destination long array. - * @return this buffer. - * @exception BufferUnderflowException - * if {@code dest.length} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public LongBuffer get(long[] dest) { - return get(dest, 0, dest.length); - } - - /** - * Reads longs from the current position into the specified long array, - * starting from the specified offset, and increase the position by the - * number of longs read. - * - * @param dest - * the target long array. - * @param off - * the offset of the long array, must not be negative and not - * greater than {@code dest.length}. - * @param len - * the number of longs to read, must be no less than zero and not - * greater than {@code dest.length - off}. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception BufferUnderflowException - * if {@code len} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public LongBuffer get(long[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)len + (long)off > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferUnderflowException(); - } - for (int i = off; i < off + len; i++) { - dest[i] = get(); - } - return this; - } - - /** - * Returns the long at the specified index; the position is not changed. - * - * @param index - * the index, must not be negative and less than limit. - * @return the long at the specified index. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @since Android 1.0 - */ - public abstract long get(int index); - - /** - * Indicates whether this buffer is based on a long array and is read/write. - * - * @return {@code true} if this buffer is based on a long array and provides - * read/write access, {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasArray() { - return protectedHasArray(); - } - - /** - * Calculates this buffer's hash code from the remaining chars. The - * position, limit, capacity and mark don't affect the hash code. - * - * @return the hash code calculated from the remaining longs. - * @since Android 1.0 - */ - public int hashCode() { - int myPosition = position; - int hash = 0; - long l; - while (myPosition < limit) { - l = get(myPosition++); - hash = hash + ((int) l) ^ ((int) (l >> 32)); - } - return hash; - } - - /** - * Indicates whether this buffer is direct. A direct buffer will try its - * best to take advantage of native memory APIs and it may not stay in the - * Java heap, so it is not affected by garbage collection. - *

    - * A long buffer is direct if it is based on a byte buffer and the byte - * buffer is direct. - *

    - * - * @return {@code true} if this buffer is direct, {@code false} otherwise. - * @since Android 1.0 - */ - public abstract boolean isDirect(); - - /** - * Returns the byte order used by this buffer when converting longs from/to - * bytes. - *

    - * If this buffer is not based on a byte buffer, then always return the - * platform's native byte order. - *

    - * - * @return the byte order used by this buffer when converting longs from/to - * bytes. - * @since Android 1.0 - */ - public abstract ByteOrder order(); - - /** - * Child class implements this method to realize {@code array()}. - * - * @return see {@code array()} - */ - abstract long[] protectedArray(); - - /** - * Child class implements this method to realize {@code arrayOffset()}. - * - * @return see {@code arrayOffset()} - */ - abstract int protectedArrayOffset(); - - /** - * Child class implements this method to realize {@code hasArray()}. - * - * @return see {@code hasArray()} - */ - abstract boolean protectedHasArray(); - - /** - * Writes the given long to the current position and increases the position - * by 1. - * - * @param l - * the long to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract LongBuffer put(long l); - - /** - * Writes longs from the given long array to the current position and - * increases the position by the number of longs written. - *

    - * Calling this method has the same effect as - * {@code put(src, 0, src.length)}. - *

    - * - * @param src - * the source long array. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code src.length}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final LongBuffer put(long[] src) { - return put(src, 0, src.length); - } - - /** - * Writes longs from the given long array, starting from the specified - * offset, to the current position and increases the position by the number - * of longs written. - * - * @param src - * the source long array. - * @param off - * the offset of long array, must not be negative and not greater - * than {@code src.length}. - * @param len - * the number of longs to write, must be no less than zero and - * not greater than {@code src.length - off}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code len}. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public LongBuffer put(long[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)len + (long)off > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - for (int i = off; i < off + len; i++) { - put(src[i]); - } - return this; - } - - /** - * Writes all the remaining longs of the {@code src} long buffer to this - * buffer's current position, and increases both buffers' position by the - * number of longs copied. - * - * @param src - * the source long buffer. - * @return this buffer. - * @exception BufferOverflowException - * if {@code src.remaining()} is greater than this buffer's - * {@code remaining()}. - * @exception IllegalArgumentException - * if {@code src} is this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public LongBuffer put(LongBuffer src) { - if (src == this) { - throw new IllegalArgumentException(); - } - if (src.remaining() > remaining()) { - throw new BufferOverflowException(); - } - long[] contents = new long[src.remaining()]; - src.get(contents); - put(contents); - return this; - } - - /** - * Writes a long to the specified index of this buffer; the position is not - * changed. - * - * @param index - * the index, must not be negative and less than the limit. - * @param l - * the long to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract LongBuffer put(int index, long l); - - /** - * Returns a sliced buffer that shares its content with this buffer. - *

    - * The sliced buffer's capacity will be this buffer's {@code remaining()}, - * and its zero position will correspond to this buffer's current position. - * The new buffer's position will be 0, limit will be its capacity, and its - * mark is cleared. The new buffer's read-only property and byte order are - * same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a sliced buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract LongBuffer slice(); - - /** - * Returns a string representing the state of this long buffer. - * - * @return a string representing the state of this long buffer. - * @since Android 1.0 - */ - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append(getClass().getName()); - buf.append(", status: capacity="); //$NON-NLS-1$ - buf.append(capacity()); - buf.append(" position="); //$NON-NLS-1$ - buf.append(position()); - buf.append(" limit="); //$NON-NLS-1$ - buf.append(limit()); - return buf.toString(); - } + /** Creates a long buffer based on a newly allocated long array. + * + * @param capacity the capacity of the new buffer. + * @return the created long buffer. + * @throws IllegalArgumentException if {@code capacity} is less than zero. + * @since Android 1.0 */ + public static LongBuffer allocate (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newLongBuffer(capacity); + } + + /** Creates a new long buffer by wrapping the given long array. + *

    + * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. + *

    + * + * @param array the long array which the new buffer will be based on. + * @return the created long buffer. + * @since Android 1.0 */ + public static LongBuffer wrap (long[] array) { + return wrap(array, 0, array.length); + } + + /** Creates a new long buffer by wrapping the given long array. + *

    + * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the + * array. + *

    + * + * @param array the long array which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code array.length}. + * @param len the length, must not be negative and not greater than {@code array.length - start}. + * @return the created long buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. + * @since Android 1.0 */ + public static LongBuffer wrap (long[] array, int start, int len) { + if (array == null) { + throw new NullPointerException(); + } + if (start < 0 || len < 0 || (long)len + (long)start > array.length) { + throw new IndexOutOfBoundsException(); + } + + LongBuffer buf = BufferFactory.newLongBuffer(array); + buf.position = start; + buf.limit = start + len; + + return buf; + } + + /** Constructs a {@code LongBuffer} with given capacity. + * + * @param capacity The capacity of the buffer */ + LongBuffer (int capacity) { + super(capacity); + } + + /** Returns the long array which this buffer is based on, if there is one. + * + * @return the long array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final long[] array () { + return protectedArray(); + } + + /** Returns the offset of the long array which this buffer is based on, if there is one. + *

    + * The offset is the index of the array and corresponds to the zero position of the buffer. + *

    + * + * @return the offset of the long array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int arrayOffset () { + return protectedArrayOffset(); + } + + /** Returns a read-only buffer that shares its content with this buffer. + *

    + * The returned buffer is guaranteed to be a new instance, even if this buffer is read-only itself. The new buffer's position, + * limit, capacity and mark are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means this buffer's change of content will be visible to the new + * buffer. The two buffer's position, limit and mark are independent. + *

    + * + * @return a read-only version of this buffer. + * @since Android 1.0 */ + public abstract LongBuffer asReadOnlyBuffer (); + + /** Compacts this long buffer. + *

    + * The remaining longs will be moved to the head of the buffer, staring from position zero. Then the position is set to + * {@code remaining()}; the limit is set to capacity; the mark is cleared. + *

    + * + * @return this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract LongBuffer compact (); + + /** Compare the remaining longs of this buffer to another long buffer's remaining longs. + * + * @param otherBuffer another long buffer. + * @return a negative value if this is less than {@code otherBuffer}; 0 if this equals to {@code otherBuffer}; a positive value + * if this is greater than {@code otherBuffer} + * @exception ClassCastException if {@code otherBuffer} is not a long buffer. + * @since Android 1.0 */ + public int compareTo (LongBuffer otherBuffer) { + int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); + int thisPos = position; + int otherPos = otherBuffer.position; + // BEGIN android-changed + long thisLong, otherLong; + while (compareRemaining > 0) { + thisLong = get(thisPos); + otherLong = otherBuffer.get(otherPos); + if (thisLong != otherLong) { + return thisLong < otherLong ? -1 : 1; + } + thisPos++; + otherPos++; + compareRemaining--; + } + // END android-changed + return remaining() - otherBuffer.remaining(); + } + + /** Returns a duplicated buffer that shares its content with this buffer. + *

    + * The duplicated buffer's position, limit, capacity and mark are the same as this buffer. The duplicated buffer's read-only + * property and byte order are same as this buffer's, too. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a duplicated buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract LongBuffer duplicate (); + + /** Checks whether this long buffer is equal to another object. + *

    + * If {@code other} is not a long buffer then {@code false} is returned. Two long buffers are equal if and only if their + * remaining longs are exactly the same. Position, limit, capacity and mark are not considered. + *

    + * + * @param other the object to compare with this long buffer. + * @return {@code true} if this long buffer is equal to {@code other}, {@code false} otherwise. + * @since Android 1.0 */ + public boolean equals (Object other) { + if (!(other instanceof LongBuffer)) { + return false; + } + LongBuffer otherBuffer = (LongBuffer)other; + + if (remaining() != otherBuffer.remaining()) { + return false; + } + + int myPosition = position; + int otherPosition = otherBuffer.position; + boolean equalSoFar = true; + while (equalSoFar && (myPosition < limit)) { + equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); + } + + return equalSoFar; + } + + /** Returns the long at the current position and increase the position by 1. + * + * @return the long at the current position. + * @exception BufferUnderflowException if the position is equal or greater than limit. + * @since Android 1.0 */ + public abstract long get (); + + /** Reads longs from the current position into the specified long array and increases the position by the number of longs read. + *

    + * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. + *

    + * + * @param dest the destination long array. + * @return this buffer. + * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. + * @since Android 1.0 */ + public LongBuffer get (long[] dest) { + return get(dest, 0, dest.length); + } + + /** Reads longs from the current position into the specified long array, starting from the specified offset, and increase the + * position by the number of longs read. + * + * @param dest the target long array. + * @param off the offset of the long array, must not be negative and not greater than {@code dest.length}. + * @param len the number of longs to read, must be no less than zero and not greater than {@code dest.length - off}. + * @return this buffer. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. + * @since Android 1.0 */ + public LongBuffer get (long[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)len + (long)off > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferUnderflowException(); + } + for (int i = off; i < off + len; i++) { + dest[i] = get(); + } + return this; + } + + /** Returns the long at the specified index; the position is not changed. + * + * @param index the index, must not be negative and less than limit. + * @return the long at the specified index. + * @exception IndexOutOfBoundsException if index is invalid. + * @since Android 1.0 */ + public abstract long get (int index); + + /** Indicates whether this buffer is based on a long array and is read/write. + * + * @return {@code true} if this buffer is based on a long array and provides read/write access, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasArray () { + return protectedHasArray(); + } + + /** Calculates this buffer's hash code from the remaining chars. The position, limit, capacity and mark don't affect the hash + * code. + * + * @return the hash code calculated from the remaining longs. + * @since Android 1.0 */ + public int hashCode () { + int myPosition = position; + int hash = 0; + long l; + while (myPosition < limit) { + l = get(myPosition++); + hash = hash + ((int)l) ^ ((int)(l >> 32)); + } + return hash; + } + + /** Indicates whether this buffer is direct. A direct buffer will try its best to take advantage of native memory APIs and it + * may not stay in the Java heap, so it is not affected by garbage collection. + *

    + * A long buffer is direct if it is based on a byte buffer and the byte buffer is direct. + *

    + * + * @return {@code true} if this buffer is direct, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isDirect (); + + /** Returns the byte order used by this buffer when converting longs from/to bytes. + *

    + * If this buffer is not based on a byte buffer, then always return the platform's native byte order. + *

    + * + * @return the byte order used by this buffer when converting longs from/to bytes. + * @since Android 1.0 */ + public abstract ByteOrder order (); + + /** Child class implements this method to realize {@code array()}. + * + * @return see {@code array()} */ + abstract long[] protectedArray (); + + /** Child class implements this method to realize {@code arrayOffset()}. + * + * @return see {@code arrayOffset()} */ + abstract int protectedArrayOffset (); + + /** Child class implements this method to realize {@code hasArray()}. + * + * @return see {@code hasArray()} */ + abstract boolean protectedHasArray (); + + /** Writes the given long to the current position and increases the position by 1. + * + * @param l the long to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract LongBuffer put (long l); + + /** Writes longs from the given long array to the current position and increases the position by the number of longs written. + *

    + * Calling this method has the same effect as {@code put(src, 0, src.length)}. + *

    + * + * @param src the source long array. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final LongBuffer put (long[] src) { + return put(src, 0, src.length); + } + + /** Writes longs from the given long array, starting from the specified offset, to the current position and increases the + * position by the number of longs written. + * + * @param src the source long array. + * @param off the offset of long array, must not be negative and not greater than {@code src.length}. + * @param len the number of longs to write, must be no less than zero and not greater than {@code src.length - off}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public LongBuffer put (long[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)len + (long)off > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + for (int i = off; i < off + len; i++) { + put(src[i]); + } + return this; + } + + /** Writes all the remaining longs of the {@code src} long buffer to this buffer's current position, and increases both buffers' + * position by the number of longs copied. + * + * @param src the source long buffer. + * @return this buffer. + * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. + * @exception IllegalArgumentException if {@code src} is this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public LongBuffer put (LongBuffer src) { + if (src == this) { + throw new IllegalArgumentException(); + } + if (src.remaining() > remaining()) { + throw new BufferOverflowException(); + } + long[] contents = new long[src.remaining()]; + src.get(contents); + put(contents); + return this; + } + + /** Writes a long to the specified index of this buffer; the position is not changed. + * + * @param index the index, must not be negative and less than the limit. + * @param l the long to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if index is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract LongBuffer put (int index, long l); + + /** Returns a sliced buffer that shares its content with this buffer. + *

    + * The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero position will correspond to this + * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new + * buffer's read-only property and byte order are same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a sliced buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract LongBuffer slice (); + + /** Returns a string representing the state of this long buffer. + * + * @return a string representing the state of this long buffer. + * @since Android 1.0 */ + public String toString () { + StringBuffer buf = new StringBuffer(); + buf.append(getClass().getName()); + buf.append(", status: capacity="); //$NON-NLS-1$ + buf.append(capacity()); + buf.append(" position="); //$NON-NLS-1$ + buf.append(position()); + buf.append(" limit="); //$NON-NLS-1$ + buf.append(limit()); + return buf.toString(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongToByteBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongToByteBufferAdapter.java index b4e6b9d733a..410b3b30f88 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongToByteBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongToByteBufferAdapter.java @@ -19,187 +19,182 @@ //import org.apache.harmony.nio.internal.DirectBuffer; //import org.apache.harmony.luni.platform.PlatformAddress; -/** - * This class wraps a byte buffer to be a long buffer. +/** This class wraps a byte buffer to be a long buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - * - */ -final class LongToByteBufferAdapter extends LongBuffer {//implements DirectBuffer { - - static LongBuffer wrap(ByteBuffer byteBuffer) { - return new LongToByteBufferAdapter(byteBuffer.slice()); - } - - private final ByteBuffer byteBuffer; - - LongToByteBufferAdapter(ByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 3)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - } - -// public int getByteCapacity() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getByteCapacity(); -// } -// assert false : byteBuffer; -// return -1; -// } + *

    */ +final class LongToByteBufferAdapter extends LongBuffer {// implements DirectBuffer { + + static LongBuffer wrap (ByteBuffer byteBuffer) { + return new LongToByteBufferAdapter(byteBuffer.slice()); + } + + private final ByteBuffer byteBuffer; + + LongToByteBufferAdapter (ByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 3)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + } + +// public int getByteCapacity() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getByteCapacity(); +// } +// assert false : byteBuffer; +// return -1; +// } // -// public PlatformAddress getEffectiveAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getEffectiveAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public PlatformAddress getBaseAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getBaseAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getBaseAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getBaseAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public boolean isAddressValid() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).isAddressValid(); -// } -// assert false : byteBuffer; -// return false; -// } +// public boolean isAddressValid() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).isAddressValid(); +// } +// assert false : byteBuffer; +// return false; +// } // -// public void addressValidityCheck() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).addressValidityCheck(); -// } else { -// assert false : byteBuffer; -// } -// } +// public void addressValidityCheck() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).addressValidityCheck(); +// } else { +// assert false : byteBuffer; +// } +// } // -// public void free() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).free(); -// } else { -// assert false : byteBuffer; -// } -// } - - @Override - public LongBuffer asReadOnlyBuffer() { - LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer - .asReadOnlyBuffer()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public LongBuffer compact() { - if (byteBuffer.isReadOnly()) { - throw new ReadOnlyBufferException(); - } - byteBuffer.limit(limit << 3); - byteBuffer.position(position << 3); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public LongBuffer duplicate() { - LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer - .duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public long get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return byteBuffer.getLong(position++ << 3); - } - - @Override - public long get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return byteBuffer.getLong(index << 3); - } - - @Override - public boolean isDirect() { - return byteBuffer.isDirect(); - } - - @Override - public boolean isReadOnly() { - return byteBuffer.isReadOnly(); - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected long[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public LongBuffer put(long c) { - if (position == limit) { - throw new BufferOverflowException(); - } - byteBuffer.putLong(position++ << 3, c); - return this; - } - - @Override - public LongBuffer put(int index, long c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - byteBuffer.putLong(index << 3, c); - return this; - } - - @Override - public LongBuffer slice() { - byteBuffer.limit(limit << 3); - byteBuffer.position(position << 3); - LongBuffer result = new LongToByteBufferAdapter(byteBuffer.slice()); - byteBuffer.clear(); - return result; - } +// public void free() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).free(); +// } else { +// assert false : byteBuffer; +// } +// } + + @Override + public LongBuffer asReadOnlyBuffer () { + LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.asReadOnlyBuffer()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public LongBuffer compact () { + if (byteBuffer.isReadOnly()) { + throw new ReadOnlyBufferException(); + } + byteBuffer.limit(limit << 3); + byteBuffer.position(position << 3); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public LongBuffer duplicate () { + LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public long get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return byteBuffer.getLong(position++ << 3); + } + + @Override + public long get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return byteBuffer.getLong(index << 3); + } + + @Override + public boolean isDirect () { + return byteBuffer.isDirect(); + } + + @Override + public boolean isReadOnly () { + return byteBuffer.isReadOnly(); + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected long[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public LongBuffer put (long c) { + if (position == limit) { + throw new BufferOverflowException(); + } + byteBuffer.putLong(position++ << 3, c); + return this; + } + + @Override + public LongBuffer put (int index, long c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + byteBuffer.putLong(index << 3, c); + return this; + } + + @Override + public LongBuffer slice () { + byteBuffer.limit(limit << 3); + byteBuffer.position(position << 3); + LongBuffer result = new LongToByteBufferAdapter(byteBuffer.slice()); + byteBuffer.clear(); + return result; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyBufferException.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyBufferException.java index 62e2d5ff908..100ce78be31 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyBufferException.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyBufferException.java @@ -16,23 +16,17 @@ package java.nio; - -/** - * A {@code ReadOnlyBufferException} is thrown when some write operation is - * called on a read-only buffer. +/** A {@code ReadOnlyBufferException} is thrown when some write operation is called on a read-only buffer. * - * @since Android 1.0 - */ + * @since Android 1.0 */ public class ReadOnlyBufferException extends UnsupportedOperationException { - private static final long serialVersionUID = -1210063976496234090L; + private static final long serialVersionUID = -1210063976496234090L; - /** - * Constructs a {@code ReadOnlyBufferException}. - * - * @since Android 1.0 - */ - public ReadOnlyBufferException() { - super(); - } + /** Constructs a {@code ReadOnlyBufferException}. + * + * @since Android 1.0 */ + public ReadOnlyBufferException () { + super(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyCharArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyCharArrayBuffer.java index 461ea4f70c9..773ab12deba 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyCharArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyCharArrayBuffer.java @@ -17,86 +17,79 @@ package java.nio; -/** - * CharArrayBuffer, ReadWriteCharArrayBuffer and ReadOnlyCharArrayBuffer compose - * the implementation of array based char buffers. +/** CharArrayBuffer, ReadWriteCharArrayBuffer and ReadOnlyCharArrayBuffer compose the implementation of array based char buffers. *

    - * ReadOnlyCharArrayBuffer extends CharArrayBuffer with all the write methods - * throwing read only exception. + * ReadOnlyCharArrayBuffer extends CharArrayBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadOnlyCharArrayBuffer extends CharArrayBuffer { - static ReadOnlyCharArrayBuffer copy(CharArrayBuffer other, int markOfOther) { - ReadOnlyCharArrayBuffer buf = new ReadOnlyCharArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadOnlyCharArrayBuffer(int capacity, char[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public CharBuffer asReadOnlyBuffer() { - return duplicate(); - } - - public CharBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public CharBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected char[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public CharBuffer put(char c) { - throw new ReadOnlyBufferException(); - } - - public CharBuffer put(int index, char c) { - throw new ReadOnlyBufferException(); - } - - public final CharBuffer put(char[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public final CharBuffer put(CharBuffer src) { - throw new ReadOnlyBufferException(); - } - - public CharBuffer put(String src, int start, int end) { - if ((start < 0 ) || (end < 0) || (long)start + (long)end > src.length()) { - throw new IndexOutOfBoundsException(); - } - throw new ReadOnlyBufferException(); - } - - public CharBuffer slice() { - return new ReadOnlyCharArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadOnlyCharArrayBuffer copy (CharArrayBuffer other, int markOfOther) { + ReadOnlyCharArrayBuffer buf = new ReadOnlyCharArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadOnlyCharArrayBuffer (int capacity, char[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public CharBuffer asReadOnlyBuffer () { + return duplicate(); + } + + public CharBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public CharBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected char[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public CharBuffer put (char c) { + throw new ReadOnlyBufferException(); + } + + public CharBuffer put (int index, char c) { + throw new ReadOnlyBufferException(); + } + + public final CharBuffer put (char[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public final CharBuffer put (CharBuffer src) { + throw new ReadOnlyBufferException(); + } + + public CharBuffer put (String src, int start, int end) { + if ((start < 0) || (end < 0) || (long)start + (long)end > src.length()) { + throw new IndexOutOfBoundsException(); + } + throw new ReadOnlyBufferException(); + } + + public CharBuffer slice () { + return new ReadOnlyCharArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyDoubleArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyDoubleArrayBuffer.java index 4f0b5d2d9bc..372ac4e305a 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyDoubleArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyDoubleArrayBuffer.java @@ -17,82 +17,74 @@ package java.nio; -/** - * DoubleArrayBuffer, ReadWriteDoubleArrayBuffer and ReadOnlyDoubleArrayBuffer - * compose the implementation of array based double buffers. +/** DoubleArrayBuffer, ReadWriteDoubleArrayBuffer and ReadOnlyDoubleArrayBuffer compose the implementation of array based double + * buffers. *

    - * ReadOnlyDoubleArrayBuffer extends DoubleArrayBuffer with all the write - * methods throwing read only exception. + * ReadOnlyDoubleArrayBuffer extends DoubleArrayBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadOnlyDoubleArrayBuffer extends DoubleArrayBuffer { - static ReadOnlyDoubleArrayBuffer copy(DoubleArrayBuffer other, - int markOfOther) { - ReadOnlyDoubleArrayBuffer buf = new ReadOnlyDoubleArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadOnlyDoubleArrayBuffer(int capacity, double[] backingArray, - int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public DoubleBuffer asReadOnlyBuffer() { - return duplicate(); - } - - public DoubleBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public DoubleBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected double[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public DoubleBuffer put(double c) { - throw new ReadOnlyBufferException(); - } - - public DoubleBuffer put(int index, double c) { - throw new ReadOnlyBufferException(); - } - - public final DoubleBuffer put(double[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public final DoubleBuffer put(DoubleBuffer buf) { - throw new ReadOnlyBufferException(); - } - - public DoubleBuffer slice() { - return new ReadOnlyDoubleArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadOnlyDoubleArrayBuffer copy (DoubleArrayBuffer other, int markOfOther) { + ReadOnlyDoubleArrayBuffer buf = new ReadOnlyDoubleArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadOnlyDoubleArrayBuffer (int capacity, double[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public DoubleBuffer asReadOnlyBuffer () { + return duplicate(); + } + + public DoubleBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public DoubleBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected double[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public DoubleBuffer put (double c) { + throw new ReadOnlyBufferException(); + } + + public DoubleBuffer put (int index, double c) { + throw new ReadOnlyBufferException(); + } + + public final DoubleBuffer put (double[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public final DoubleBuffer put (DoubleBuffer buf) { + throw new ReadOnlyBufferException(); + } + + public DoubleBuffer slice () { + return new ReadOnlyDoubleArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyFloatArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyFloatArrayBuffer.java index 7559ffa9782..9bb46e2c4e1 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyFloatArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyFloatArrayBuffer.java @@ -17,80 +17,74 @@ package java.nio; -/** - * FloatArrayBuffer, ReadWriteFloatArrayBuffer and ReadOnlyFloatArrayBuffer - * compose the implementation of array based float buffers. +/** FloatArrayBuffer, ReadWriteFloatArrayBuffer and ReadOnlyFloatArrayBuffer compose the implementation of array based float + * buffers. *

    - * ReadOnlyFloatArrayBuffer extends FloatArrayBuffer with all the write methods - * throwing read only exception. + * ReadOnlyFloatArrayBuffer extends FloatArrayBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadOnlyFloatArrayBuffer extends FloatArrayBuffer { - static ReadOnlyFloatArrayBuffer copy(FloatArrayBuffer other, int markOfOther) { - ReadOnlyFloatArrayBuffer buf = new ReadOnlyFloatArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadOnlyFloatArrayBuffer(int capacity, float[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public FloatBuffer asReadOnlyBuffer() { - return duplicate(); - } - - public FloatBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public FloatBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected float[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public FloatBuffer put(float c) { - throw new ReadOnlyBufferException(); - } - - public FloatBuffer put(int index, float c) { - throw new ReadOnlyBufferException(); - } - - public FloatBuffer put(FloatBuffer buf) { - throw new ReadOnlyBufferException(); - } - - public final FloatBuffer put(float[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public FloatBuffer slice() { - return new ReadOnlyFloatArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadOnlyFloatArrayBuffer copy (FloatArrayBuffer other, int markOfOther) { + ReadOnlyFloatArrayBuffer buf = new ReadOnlyFloatArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadOnlyFloatArrayBuffer (int capacity, float[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public FloatBuffer asReadOnlyBuffer () { + return duplicate(); + } + + public FloatBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public FloatBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected float[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public FloatBuffer put (float c) { + throw new ReadOnlyBufferException(); + } + + public FloatBuffer put (int index, float c) { + throw new ReadOnlyBufferException(); + } + + public FloatBuffer put (FloatBuffer buf) { + throw new ReadOnlyBufferException(); + } + + public final FloatBuffer put (float[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public FloatBuffer slice () { + return new ReadOnlyFloatArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyHeapByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyHeapByteBuffer.java index 857ecff0b9f..5e6a467147c 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyHeapByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyHeapByteBuffer.java @@ -17,122 +17,115 @@ package java.nio; -/** - * HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose - * the implementation of array based byte buffers. +/** HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose the implementation of array based byte buffers. *

    - * ReadOnlyHeapByteBuffer extends HeapByteBuffer with all the write methods - * throwing read only exception. + * ReadOnlyHeapByteBuffer extends HeapByteBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadOnlyHeapByteBuffer extends HeapByteBuffer { - static ReadOnlyHeapByteBuffer copy(HeapByteBuffer other, int markOfOther) { - ReadOnlyHeapByteBuffer buf = new ReadOnlyHeapByteBuffer( - other.backingArray, other.capacity(), other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - buf.order(other.order()); - return buf; - } - - ReadOnlyHeapByteBuffer(byte[] backingArray, int capacity, int arrayOffset) { - super(backingArray, capacity, arrayOffset); - } - - public ByteBuffer asReadOnlyBuffer() { - return copy(this, mark); - } - - public ByteBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected byte[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public ByteBuffer put(byte b) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer put(int index, byte b) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer put(byte[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putDouble(double value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putDouble(int index, double value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putFloat(float value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putFloat(int index, float value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putInt(int value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putInt(int index, int value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putLong(int index, long value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putLong(long value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putShort(int index, short value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer putShort(short value) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer put(ByteBuffer buf) { - throw new ReadOnlyBufferException(); - } - - public ByteBuffer slice() { - ReadOnlyHeapByteBuffer slice = new ReadOnlyHeapByteBuffer(backingArray, - remaining(), offset + position); - slice.order = order; - return slice; - } + static ReadOnlyHeapByteBuffer copy (HeapByteBuffer other, int markOfOther) { + ReadOnlyHeapByteBuffer buf = new ReadOnlyHeapByteBuffer(other.backingArray, other.capacity(), other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + buf.order(other.order()); + return buf; + } + + ReadOnlyHeapByteBuffer (byte[] backingArray, int capacity, int arrayOffset) { + super(backingArray, capacity, arrayOffset); + } + + public ByteBuffer asReadOnlyBuffer () { + return copy(this, mark); + } + + public ByteBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected byte[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public ByteBuffer put (byte b) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer put (int index, byte b) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer put (byte[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putDouble (double value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putDouble (int index, double value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putFloat (float value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putFloat (int index, float value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putInt (int value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putInt (int index, int value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putLong (int index, long value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putLong (long value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putShort (int index, short value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer putShort (short value) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer put (ByteBuffer buf) { + throw new ReadOnlyBufferException(); + } + + public ByteBuffer slice () { + ReadOnlyHeapByteBuffer slice = new ReadOnlyHeapByteBuffer(backingArray, remaining(), offset + position); + slice.order = order; + return slice; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyIntArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyIntArrayBuffer.java index ba9380e0ce8..228db222f4a 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyIntArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyIntArrayBuffer.java @@ -17,80 +17,73 @@ package java.nio; -/** - * IntArrayBuffer, ReadWriteIntArrayBuffer and ReadOnlyIntArrayBuffer compose - * the implementation of array based int buffers. +/** IntArrayBuffer, ReadWriteIntArrayBuffer and ReadOnlyIntArrayBuffer compose the implementation of array based int buffers. *

    - * ReadOnlyIntArrayBuffer extends IntArrayBuffer with all the write methods - * throwing read only exception. + * ReadOnlyIntArrayBuffer extends IntArrayBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadOnlyIntArrayBuffer extends IntArrayBuffer { - static ReadOnlyIntArrayBuffer copy(IntArrayBuffer other, int markOfOther) { - ReadOnlyIntArrayBuffer buf = new ReadOnlyIntArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadOnlyIntArrayBuffer(int capacity, int[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public IntBuffer asReadOnlyBuffer() { - return duplicate(); - } - - public IntBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public IntBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected int[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public IntBuffer put(int c) { - throw new ReadOnlyBufferException(); - } - - public IntBuffer put(int index, int c) { - throw new ReadOnlyBufferException(); - } - - public IntBuffer put(IntBuffer buf) { - throw new ReadOnlyBufferException(); - } - - public final IntBuffer put(int[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public IntBuffer slice() { - return new ReadOnlyIntArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadOnlyIntArrayBuffer copy (IntArrayBuffer other, int markOfOther) { + ReadOnlyIntArrayBuffer buf = new ReadOnlyIntArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadOnlyIntArrayBuffer (int capacity, int[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public IntBuffer asReadOnlyBuffer () { + return duplicate(); + } + + public IntBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public IntBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected int[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public IntBuffer put (int c) { + throw new ReadOnlyBufferException(); + } + + public IntBuffer put (int index, int c) { + throw new ReadOnlyBufferException(); + } + + public IntBuffer put (IntBuffer buf) { + throw new ReadOnlyBufferException(); + } + + public final IntBuffer put (int[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public IntBuffer slice () { + return new ReadOnlyIntArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyLongArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyLongArrayBuffer.java index 76c1a4adb44..bca9209b007 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyLongArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyLongArrayBuffer.java @@ -17,80 +17,73 @@ package java.nio; -/** - * LongArrayBuffer, ReadWriteLongArrayBuffer and ReadOnlyLongArrayBuffer compose - * the implementation of array based long buffers. +/** LongArrayBuffer, ReadWriteLongArrayBuffer and ReadOnlyLongArrayBuffer compose the implementation of array based long buffers. *

    - * ReadOnlyLongArrayBuffer extends LongArrayBuffer with all the write methods - * throwing read only exception. + * ReadOnlyLongArrayBuffer extends LongArrayBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadOnlyLongArrayBuffer extends LongArrayBuffer { - static ReadOnlyLongArrayBuffer copy(LongArrayBuffer other, int markOfOther) { - ReadOnlyLongArrayBuffer buf = new ReadOnlyLongArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadOnlyLongArrayBuffer(int capacity, long[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public LongBuffer asReadOnlyBuffer() { - return duplicate(); - } - - public LongBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public LongBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected long[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public LongBuffer put(long c) { - throw new ReadOnlyBufferException(); - } - - public LongBuffer put(int index, long c) { - throw new ReadOnlyBufferException(); - } - - public LongBuffer put(LongBuffer buf) { - throw new ReadOnlyBufferException(); - } - - public final LongBuffer put(long[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public LongBuffer slice() { - return new ReadOnlyLongArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadOnlyLongArrayBuffer copy (LongArrayBuffer other, int markOfOther) { + ReadOnlyLongArrayBuffer buf = new ReadOnlyLongArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadOnlyLongArrayBuffer (int capacity, long[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public LongBuffer asReadOnlyBuffer () { + return duplicate(); + } + + public LongBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public LongBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected long[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public LongBuffer put (long c) { + throw new ReadOnlyBufferException(); + } + + public LongBuffer put (int index, long c) { + throw new ReadOnlyBufferException(); + } + + public LongBuffer put (LongBuffer buf) { + throw new ReadOnlyBufferException(); + } + + public final LongBuffer put (long[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public LongBuffer slice () { + return new ReadOnlyLongArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyShortArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyShortArrayBuffer.java index 1a3bfd3a09a..7d9dbda5427 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyShortArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadOnlyShortArrayBuffer.java @@ -17,80 +17,74 @@ package java.nio; -/** - * ShortArrayBuffer, ReadWriteShortArrayBuffer and ReadOnlyShortArrayBuffer - * compose the implementation of array based short buffers. +/** ShortArrayBuffer, ReadWriteShortArrayBuffer and ReadOnlyShortArrayBuffer compose the implementation of array based short + * buffers. *

    - * ReadOnlyShortArrayBuffer extends ShortArrayBuffer with all the write methods - * throwing read only exception. + * ReadOnlyShortArrayBuffer extends ShortArrayBuffer with all the write methods throwing read only exception. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadOnlyShortArrayBuffer extends ShortArrayBuffer { - static ReadOnlyShortArrayBuffer copy(ShortArrayBuffer other, int markOfOther) { - ReadOnlyShortArrayBuffer buf = new ReadOnlyShortArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadOnlyShortArrayBuffer(int capacity, short[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public ShortBuffer asReadOnlyBuffer() { - return duplicate(); - } - - public ShortBuffer compact() { - throw new ReadOnlyBufferException(); - } - - public ShortBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return true; - } - - protected short[] protectedArray() { - throw new ReadOnlyBufferException(); - } - - protected int protectedArrayOffset() { - throw new ReadOnlyBufferException(); - } - - protected boolean protectedHasArray() { - return false; - } - - public ShortBuffer put(ShortBuffer buf) { - throw new ReadOnlyBufferException(); - } - - public ShortBuffer put(short c) { - throw new ReadOnlyBufferException(); - } - - public ShortBuffer put(int index, short c) { - throw new ReadOnlyBufferException(); - } - - public final ShortBuffer put(short[] src, int off, int len) { - throw new ReadOnlyBufferException(); - } - - public ShortBuffer slice() { - return new ReadOnlyShortArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadOnlyShortArrayBuffer copy (ShortArrayBuffer other, int markOfOther) { + ReadOnlyShortArrayBuffer buf = new ReadOnlyShortArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadOnlyShortArrayBuffer (int capacity, short[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public ShortBuffer asReadOnlyBuffer () { + return duplicate(); + } + + public ShortBuffer compact () { + throw new ReadOnlyBufferException(); + } + + public ShortBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return true; + } + + protected short[] protectedArray () { + throw new ReadOnlyBufferException(); + } + + protected int protectedArrayOffset () { + throw new ReadOnlyBufferException(); + } + + protected boolean protectedHasArray () { + return false; + } + + public ShortBuffer put (ShortBuffer buf) { + throw new ReadOnlyBufferException(); + } + + public ShortBuffer put (short c) { + throw new ReadOnlyBufferException(); + } + + public ShortBuffer put (int index, short c) { + throw new ReadOnlyBufferException(); + } + + public final ShortBuffer put (short[] src, int off, int len) { + throw new ReadOnlyBufferException(); + } + + public ShortBuffer slice () { + return new ReadOnlyShortArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteCharArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteCharArrayBuffer.java index 08f79b21540..3c1b55e4adc 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteCharArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteCharArrayBuffer.java @@ -17,105 +17,98 @@ package java.nio; -/** - * CharArrayBuffer, ReadWriteCharArrayBuffer and ReadOnlyCharArrayBuffer compose - * the implementation of array based char buffers. +/** CharArrayBuffer, ReadWriteCharArrayBuffer and ReadOnlyCharArrayBuffer compose the implementation of array based char buffers. *

    * ReadWriteCharArrayBuffer extends CharArrayBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadWriteCharArrayBuffer extends CharArrayBuffer { - static ReadWriteCharArrayBuffer copy(CharArrayBuffer other, int markOfOther) { - ReadWriteCharArrayBuffer buf = new ReadWriteCharArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadWriteCharArrayBuffer(char[] array) { - super(array); - } - - ReadWriteCharArrayBuffer(int capacity) { - super(capacity); - } - - ReadWriteCharArrayBuffer(int capacity, char[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public CharBuffer asReadOnlyBuffer() { - return ReadOnlyCharArrayBuffer.copy(this, mark); - } - - public CharBuffer compact() { - System.arraycopy(backingArray, position + offset, backingArray, offset, - remaining()); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public CharBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected char[] protectedArray() { - return backingArray; - } - - protected int protectedArrayOffset() { - return offset; - } - - protected boolean protectedHasArray() { - return true; - } - - public CharBuffer put(char c) { - if (position == limit) { - throw new BufferOverflowException(); - } - backingArray[offset + position++] = c; - return this; - } - - public CharBuffer put(int index, char c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - backingArray[offset + index] = c; - return this; - } - - public CharBuffer put(char[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)len + (long)off > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - System.arraycopy(src, off, backingArray, offset+position, len); - position += len; - return this; - } - - public CharBuffer slice() { - return new ReadWriteCharArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadWriteCharArrayBuffer copy (CharArrayBuffer other, int markOfOther) { + ReadWriteCharArrayBuffer buf = new ReadWriteCharArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadWriteCharArrayBuffer (char[] array) { + super(array); + } + + ReadWriteCharArrayBuffer (int capacity) { + super(capacity); + } + + ReadWriteCharArrayBuffer (int capacity, char[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public CharBuffer asReadOnlyBuffer () { + return ReadOnlyCharArrayBuffer.copy(this, mark); + } + + public CharBuffer compact () { + System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public CharBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected char[] protectedArray () { + return backingArray; + } + + protected int protectedArrayOffset () { + return offset; + } + + protected boolean protectedHasArray () { + return true; + } + + public CharBuffer put (char c) { + if (position == limit) { + throw new BufferOverflowException(); + } + backingArray[offset + position++] = c; + return this; + } + + public CharBuffer put (int index, char c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + backingArray[offset + index] = c; + return this; + } + + public CharBuffer put (char[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)len + (long)off > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + System.arraycopy(src, off, backingArray, offset + position, len); + position += len; + return this; + } + + public CharBuffer slice () { + return new ReadWriteCharArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteDoubleArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteDoubleArrayBuffer.java index 2933178e35c..336a001068e 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteDoubleArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteDoubleArrayBuffer.java @@ -17,109 +17,99 @@ package java.nio; -/** - * DoubleArrayBuffer, ReadWriteDoubleArrayBuffer and ReadOnlyDoubleArrayBuffer - * compose the implementation of array based double buffers. +/** DoubleArrayBuffer, ReadWriteDoubleArrayBuffer and ReadOnlyDoubleArrayBuffer compose the implementation of array based double + * buffers. *

    - * ReadWriteDoubleArrayBuffer extends DoubleArrayBuffer with all the write - * methods. + * ReadWriteDoubleArrayBuffer extends DoubleArrayBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadWriteDoubleArrayBuffer extends DoubleArrayBuffer { - static ReadWriteDoubleArrayBuffer copy(DoubleArrayBuffer other, - int markOfOther) { - ReadWriteDoubleArrayBuffer buf = new ReadWriteDoubleArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadWriteDoubleArrayBuffer(double[] array) { - super(array); - } - - ReadWriteDoubleArrayBuffer(int capacity) { - super(capacity); - } - - ReadWriteDoubleArrayBuffer(int capacity, double[] backingArray, - int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public DoubleBuffer asReadOnlyBuffer() { - return ReadOnlyDoubleArrayBuffer.copy(this, mark); - } - - public DoubleBuffer compact() { - System.arraycopy(backingArray, position + offset, backingArray, offset, - remaining()); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public DoubleBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected double[] protectedArray() { - return backingArray; - } - - protected int protectedArrayOffset() { - return offset; - } - - protected boolean protectedHasArray() { - return true; - } - - public DoubleBuffer put(double c) { - if (position == limit) { - throw new BufferOverflowException(); - } - backingArray[offset + position++] = c; - return this; - } - - public DoubleBuffer put(int index, double c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - backingArray[offset + index] = c; - return this; - } - - public DoubleBuffer put(double[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - System.arraycopy(src, off, backingArray, offset - + position, len); - position += len; - return this; - } - - public DoubleBuffer slice() { - return new ReadWriteDoubleArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadWriteDoubleArrayBuffer copy (DoubleArrayBuffer other, int markOfOther) { + ReadWriteDoubleArrayBuffer buf = new ReadWriteDoubleArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadWriteDoubleArrayBuffer (double[] array) { + super(array); + } + + ReadWriteDoubleArrayBuffer (int capacity) { + super(capacity); + } + + ReadWriteDoubleArrayBuffer (int capacity, double[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public DoubleBuffer asReadOnlyBuffer () { + return ReadOnlyDoubleArrayBuffer.copy(this, mark); + } + + public DoubleBuffer compact () { + System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public DoubleBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected double[] protectedArray () { + return backingArray; + } + + protected int protectedArrayOffset () { + return offset; + } + + protected boolean protectedHasArray () { + return true; + } + + public DoubleBuffer put (double c) { + if (position == limit) { + throw new BufferOverflowException(); + } + backingArray[offset + position++] = c; + return this; + } + + public DoubleBuffer put (int index, double c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + backingArray[offset + index] = c; + return this; + } + + public DoubleBuffer put (double[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + System.arraycopy(src, off, backingArray, offset + position, len); + position += len; + return this; + } + + public DoubleBuffer slice () { + return new ReadWriteDoubleArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteFloatArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteFloatArrayBuffer.java index 49b0b11bb07..506976c6c7e 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteFloatArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteFloatArrayBuffer.java @@ -17,109 +17,99 @@ package java.nio; -/** - * FloatArrayBuffer, ReadWriteFloatArrayBuffer and ReadOnlyFloatArrayBuffer - * compose the implementation of array based float buffers. +/** FloatArrayBuffer, ReadWriteFloatArrayBuffer and ReadOnlyFloatArrayBuffer compose the implementation of array based float + * buffers. *

    - * ReadWriteFloatArrayBuffer extends FloatArrayBuffer with all the write - * methods. + * ReadWriteFloatArrayBuffer extends FloatArrayBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadWriteFloatArrayBuffer extends FloatArrayBuffer { - static ReadWriteFloatArrayBuffer copy(FloatArrayBuffer other, - int markOfOther) { - ReadWriteFloatArrayBuffer buf = new ReadWriteFloatArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadWriteFloatArrayBuffer(float[] array) { - super(array); - } - - ReadWriteFloatArrayBuffer(int capacity) { - super(capacity); - } - - ReadWriteFloatArrayBuffer(int capacity, float[] backingArray, - int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public FloatBuffer asReadOnlyBuffer() { - return ReadOnlyFloatArrayBuffer.copy(this, mark); - } - - public FloatBuffer compact() { - System.arraycopy(backingArray, position + offset, backingArray, offset, - remaining()); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public FloatBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected float[] protectedArray() { - return backingArray; - } - - protected int protectedArrayOffset() { - return offset; - } - - protected boolean protectedHasArray() { - return true; - } - - public FloatBuffer put(float c) { - if (position == limit) { - throw new BufferOverflowException(); - } - backingArray[offset + position++] = c; - return this; - } - - public FloatBuffer put(int index, float c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - backingArray[offset + index] = c; - return this; - } - - public FloatBuffer put(float[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - System.arraycopy(src, off, backingArray, offset - + position, len); - position += len; - return this; - } - - public FloatBuffer slice() { - return new ReadWriteFloatArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadWriteFloatArrayBuffer copy (FloatArrayBuffer other, int markOfOther) { + ReadWriteFloatArrayBuffer buf = new ReadWriteFloatArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadWriteFloatArrayBuffer (float[] array) { + super(array); + } + + ReadWriteFloatArrayBuffer (int capacity) { + super(capacity); + } + + ReadWriteFloatArrayBuffer (int capacity, float[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public FloatBuffer asReadOnlyBuffer () { + return ReadOnlyFloatArrayBuffer.copy(this, mark); + } + + public FloatBuffer compact () { + System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public FloatBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected float[] protectedArray () { + return backingArray; + } + + protected int protectedArrayOffset () { + return offset; + } + + protected boolean protectedHasArray () { + return true; + } + + public FloatBuffer put (float c) { + if (position == limit) { + throw new BufferOverflowException(); + } + backingArray[offset + position++] = c; + return this; + } + + public FloatBuffer put (int index, float c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + backingArray[offset + index] = c; + return this; + } + + public FloatBuffer put (float[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + System.arraycopy(src, off, backingArray, offset + position, len); + position += len; + return this; + } + + public FloatBuffer slice () { + return new ReadWriteFloatArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteHeapByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteHeapByteBuffer.java index cc5696e1cfc..5f58e38c217 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteHeapByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteHeapByteBuffer.java @@ -18,187 +18,179 @@ import com.google.gwt.corp.compatibility.Numbers; -/** - * HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose - * the implementation of array based byte buffers. +/** HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose the implementation of array based byte buffers. *

    * ReadWriteHeapByteBuffer extends HeapByteBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadWriteHeapByteBuffer extends HeapByteBuffer { - static ReadWriteHeapByteBuffer copy(HeapByteBuffer other, int markOfOther) { - ReadWriteHeapByteBuffer buf = new ReadWriteHeapByteBuffer( - other.backingArray, other.capacity(), other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - buf.order(other.order()); - return buf; - } - - ReadWriteHeapByteBuffer(byte[] backingArray) { - super(backingArray); - } - - ReadWriteHeapByteBuffer(int capacity) { - super(capacity); - } - - ReadWriteHeapByteBuffer(byte[] backingArray, int capacity, int arrayOffset) { - super(backingArray, capacity, arrayOffset); - } - - public ByteBuffer asReadOnlyBuffer() { - return ReadOnlyHeapByteBuffer.copy(this, mark); - } - - public ByteBuffer compact() { - System.arraycopy(backingArray, position + offset, backingArray, offset, - remaining()); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public ByteBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected byte[] protectedArray() { - return backingArray; - } - - protected int protectedArrayOffset() { - return offset; - } - - protected boolean protectedHasArray() { - return true; - } - - public ByteBuffer put(byte b) { - if (position == limit) { - throw new BufferOverflowException(); - } - backingArray[offset + position++] = b; - return this; - } - - public ByteBuffer put(int index, byte b) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - backingArray[offset + index] = b; - return this; - } - - /* - * Override ByteBuffer.put(byte[], int, int) to improve performance. - * - * (non-Javadoc) - * - * @see java.nio.ByteBuffer#put(byte[], int, int) - */ - public ByteBuffer put(byte[] src, int off, int len) { - if (off < 0 || len < 0 || (long)off + (long)len > src.length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - if (isReadOnly()) { - throw new ReadOnlyBufferException(); - } - System.arraycopy(src, off, backingArray, offset - + position, len); - position += len; - return this; - } - - public ByteBuffer putDouble(double value) { - return putLong(Numbers.doubleToRawLongBits(value)); - } - - public ByteBuffer putDouble(int index, double value) { - return putLong(index, Numbers.doubleToRawLongBits(value)); - } - - public ByteBuffer putFloat(float value) { - return putInt(Numbers.floatToIntBits(value)); - } - - public ByteBuffer putFloat(int index, float value) { - return putInt(index, Numbers.floatToIntBits(value)); - } - - public ByteBuffer putInt(int value) { - int newPosition = position + 4; - if (newPosition > limit) { - throw new BufferOverflowException(); - } - store(position, value); - position = newPosition; - return this; - } - - public ByteBuffer putInt(int index, int value) { - if (index < 0 || (long)index + 4 > limit) { - throw new IndexOutOfBoundsException(); - } - store(index, value); - return this; - } - - public ByteBuffer putLong(int index, long value) { - if (index < 0 || (long)index + 8 > limit) { - throw new IndexOutOfBoundsException(); - } - store(index, value); - return this; - } - - public ByteBuffer putLong(long value) { - int newPosition = position + 8; - if (newPosition > limit) { - throw new BufferOverflowException(); - } - store(position, value); - position = newPosition; - return this; - } - - public ByteBuffer putShort(int index, short value) { - if (index < 0 || (long)index + 2 > limit) { - throw new IndexOutOfBoundsException(); - } - store(index, value); - return this; - } - - public ByteBuffer putShort(short value) { - int newPosition = position + 2; - if (newPosition > limit) { - throw new BufferOverflowException(); - } - store(position, value); - position = newPosition; - return this; - } - - public ByteBuffer slice() { - ReadWriteHeapByteBuffer slice = new ReadWriteHeapByteBuffer( - backingArray, remaining(), offset + position); - slice.order = order; - return slice; - } + static ReadWriteHeapByteBuffer copy (HeapByteBuffer other, int markOfOther) { + ReadWriteHeapByteBuffer buf = new ReadWriteHeapByteBuffer(other.backingArray, other.capacity(), other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + buf.order(other.order()); + return buf; + } + + ReadWriteHeapByteBuffer (byte[] backingArray) { + super(backingArray); + } + + ReadWriteHeapByteBuffer (int capacity) { + super(capacity); + } + + ReadWriteHeapByteBuffer (byte[] backingArray, int capacity, int arrayOffset) { + super(backingArray, capacity, arrayOffset); + } + + public ByteBuffer asReadOnlyBuffer () { + return ReadOnlyHeapByteBuffer.copy(this, mark); + } + + public ByteBuffer compact () { + System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public ByteBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected byte[] protectedArray () { + return backingArray; + } + + protected int protectedArrayOffset () { + return offset; + } + + protected boolean protectedHasArray () { + return true; + } + + public ByteBuffer put (byte b) { + if (position == limit) { + throw new BufferOverflowException(); + } + backingArray[offset + position++] = b; + return this; + } + + public ByteBuffer put (int index, byte b) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + backingArray[offset + index] = b; + return this; + } + + /* + * Override ByteBuffer.put(byte[], int, int) to improve performance. + * + * (non-Javadoc) + * + * @see java.nio.ByteBuffer#put(byte[], int, int) + */ + public ByteBuffer put (byte[] src, int off, int len) { + if (off < 0 || len < 0 || (long)off + (long)len > src.length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + if (isReadOnly()) { + throw new ReadOnlyBufferException(); + } + System.arraycopy(src, off, backingArray, offset + position, len); + position += len; + return this; + } + + public ByteBuffer putDouble (double value) { + return putLong(Numbers.doubleToRawLongBits(value)); + } + + public ByteBuffer putDouble (int index, double value) { + return putLong(index, Numbers.doubleToRawLongBits(value)); + } + + public ByteBuffer putFloat (float value) { + return putInt(Numbers.floatToIntBits(value)); + } + + public ByteBuffer putFloat (int index, float value) { + return putInt(index, Numbers.floatToIntBits(value)); + } + + public ByteBuffer putInt (int value) { + int newPosition = position + 4; + if (newPosition > limit) { + throw new BufferOverflowException(); + } + store(position, value); + position = newPosition; + return this; + } + + public ByteBuffer putInt (int index, int value) { + if (index < 0 || (long)index + 4 > limit) { + throw new IndexOutOfBoundsException(); + } + store(index, value); + return this; + } + + public ByteBuffer putLong (int index, long value) { + if (index < 0 || (long)index + 8 > limit) { + throw new IndexOutOfBoundsException(); + } + store(index, value); + return this; + } + + public ByteBuffer putLong (long value) { + int newPosition = position + 8; + if (newPosition > limit) { + throw new BufferOverflowException(); + } + store(position, value); + position = newPosition; + return this; + } + + public ByteBuffer putShort (int index, short value) { + if (index < 0 || (long)index + 2 > limit) { + throw new IndexOutOfBoundsException(); + } + store(index, value); + return this; + } + + public ByteBuffer putShort (short value) { + int newPosition = position + 2; + if (newPosition > limit) { + throw new BufferOverflowException(); + } + store(position, value); + position = newPosition; + return this; + } + + public ByteBuffer slice () { + ReadWriteHeapByteBuffer slice = new ReadWriteHeapByteBuffer(backingArray, remaining(), offset + position); + slice.order = order; + return slice; + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteIntArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteIntArrayBuffer.java index 005e45b4dd4..34592717e56 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteIntArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteIntArrayBuffer.java @@ -17,106 +17,98 @@ package java.nio; -/** - * IntArrayBuffer, ReadWriteIntArrayBuffer and ReadOnlyIntArrayBuffer compose - * the implementation of array based int buffers. +/** IntArrayBuffer, ReadWriteIntArrayBuffer and ReadOnlyIntArrayBuffer compose the implementation of array based int buffers. *

    * ReadWriteIntArrayBuffer extends IntArrayBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadWriteIntArrayBuffer extends IntArrayBuffer { - static ReadWriteIntArrayBuffer copy(IntArrayBuffer other, int markOfOther) { - ReadWriteIntArrayBuffer buf = new ReadWriteIntArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadWriteIntArrayBuffer(int[] array) { - super(array); - } - - ReadWriteIntArrayBuffer(int capacity) { - super(capacity); - } - - ReadWriteIntArrayBuffer(int capacity, int[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public IntBuffer asReadOnlyBuffer() { - return ReadOnlyIntArrayBuffer.copy(this, mark); - } - - public IntBuffer compact() { - System.arraycopy(backingArray, position + offset, backingArray, offset, - remaining()); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public IntBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected int[] protectedArray() { - return backingArray; - } - - protected int protectedArrayOffset() { - return offset; - } - - protected boolean protectedHasArray() { - return true; - } - - public IntBuffer put(int c) { - if (position == limit) { - throw new BufferOverflowException(); - } - backingArray[offset + position++] = c; - return this; - } - - public IntBuffer put(int index, int c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - backingArray[offset + index] = c; - return this; - } - - public IntBuffer put(int[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - System.arraycopy(src, off, backingArray, offset - + position, len); - position += len; - return this; - } - - public IntBuffer slice() { - return new ReadWriteIntArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadWriteIntArrayBuffer copy (IntArrayBuffer other, int markOfOther) { + ReadWriteIntArrayBuffer buf = new ReadWriteIntArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadWriteIntArrayBuffer (int[] array) { + super(array); + } + + ReadWriteIntArrayBuffer (int capacity) { + super(capacity); + } + + ReadWriteIntArrayBuffer (int capacity, int[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public IntBuffer asReadOnlyBuffer () { + return ReadOnlyIntArrayBuffer.copy(this, mark); + } + + public IntBuffer compact () { + System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public IntBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected int[] protectedArray () { + return backingArray; + } + + protected int protectedArrayOffset () { + return offset; + } + + protected boolean protectedHasArray () { + return true; + } + + public IntBuffer put (int c) { + if (position == limit) { + throw new BufferOverflowException(); + } + backingArray[offset + position++] = c; + return this; + } + + public IntBuffer put (int index, int c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + backingArray[offset + index] = c; + return this; + } + + public IntBuffer put (int[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + System.arraycopy(src, off, backingArray, offset + position, len); + position += len; + return this; + } + + public IntBuffer slice () { + return new ReadWriteIntArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteLongArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteLongArrayBuffer.java index ff2c5886daf..bff78528e9c 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteLongArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteLongArrayBuffer.java @@ -17,106 +17,98 @@ package java.nio; -/** - * LongArrayBuffer, ReadWriteLongArrayBuffer and ReadOnlyLongArrayBuffer compose - * the implementation of array based long buffers. +/** LongArrayBuffer, ReadWriteLongArrayBuffer and ReadOnlyLongArrayBuffer compose the implementation of array based long buffers. *

    * ReadWriteLongArrayBuffer extends LongArrayBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadWriteLongArrayBuffer extends LongArrayBuffer { - static ReadWriteLongArrayBuffer copy(LongArrayBuffer other, int markOfOther) { - ReadWriteLongArrayBuffer buf = new ReadWriteLongArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadWriteLongArrayBuffer(long[] array) { - super(array); - } - - ReadWriteLongArrayBuffer(int capacity) { - super(capacity); - } - - ReadWriteLongArrayBuffer(int capacity, long[] backingArray, int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public LongBuffer asReadOnlyBuffer() { - return ReadOnlyLongArrayBuffer.copy(this, mark); - } - - public LongBuffer compact() { - System.arraycopy(backingArray, position + offset, backingArray, offset, - remaining()); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public LongBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected long[] protectedArray() { - return backingArray; - } - - protected int protectedArrayOffset() { - return offset; - } - - protected boolean protectedHasArray() { - return true; - } - - public LongBuffer put(long c) { - if (position == limit) { - throw new BufferOverflowException(); - } - backingArray[offset + position++] = c; - return this; - } - - public LongBuffer put(int index, long c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - backingArray[offset + index] = c; - return this; - } - - public LongBuffer put(long[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - System.arraycopy(src, off, backingArray, offset - + position, len); - position += len; - return this; - } - - public LongBuffer slice() { - return new ReadWriteLongArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadWriteLongArrayBuffer copy (LongArrayBuffer other, int markOfOther) { + ReadWriteLongArrayBuffer buf = new ReadWriteLongArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadWriteLongArrayBuffer (long[] array) { + super(array); + } + + ReadWriteLongArrayBuffer (int capacity) { + super(capacity); + } + + ReadWriteLongArrayBuffer (int capacity, long[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public LongBuffer asReadOnlyBuffer () { + return ReadOnlyLongArrayBuffer.copy(this, mark); + } + + public LongBuffer compact () { + System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public LongBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected long[] protectedArray () { + return backingArray; + } + + protected int protectedArrayOffset () { + return offset; + } + + protected boolean protectedHasArray () { + return true; + } + + public LongBuffer put (long c) { + if (position == limit) { + throw new BufferOverflowException(); + } + backingArray[offset + position++] = c; + return this; + } + + public LongBuffer put (int index, long c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + backingArray[offset + index] = c; + return this; + } + + public LongBuffer put (long[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + System.arraycopy(src, off, backingArray, offset + position, len); + position += len; + return this; + } + + public LongBuffer slice () { + return new ReadWriteLongArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteShortArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteShortArrayBuffer.java index 193bdb314cf..7c32bcceec1 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteShortArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ReadWriteShortArrayBuffer.java @@ -17,108 +17,99 @@ package java.nio; -/** - * ShortArrayBuffer, ReadWriteShortArrayBuffer and ReadOnlyShortArrayBuffer - * compose the implementation of array based short buffers. +/** ShortArrayBuffer, ReadWriteShortArrayBuffer and ReadOnlyShortArrayBuffer compose the implementation of array based short + * buffers. *

    - * ReadWriteShortArrayBuffer extends ShortArrayBuffer with all the write - * methods. + * ReadWriteShortArrayBuffer extends ShortArrayBuffer with all the write methods. *

    *

    * This class is marked final for runtime performance. - *

    - * - */ + *

    */ final class ReadWriteShortArrayBuffer extends ShortArrayBuffer { - static ReadWriteShortArrayBuffer copy(ShortArrayBuffer other, - int markOfOther) { - ReadWriteShortArrayBuffer buf = new ReadWriteShortArrayBuffer(other - .capacity(), other.backingArray, other.offset); - buf.limit = other.limit(); - buf.position = other.position(); - buf.mark = markOfOther; - return buf; - } - - ReadWriteShortArrayBuffer(short[] array) { - super(array); - } - - ReadWriteShortArrayBuffer(int capacity) { - super(capacity); - } - - ReadWriteShortArrayBuffer(int capacity, short[] backingArray, - int arrayOffset) { - super(capacity, backingArray, arrayOffset); - } - - public ShortBuffer asReadOnlyBuffer() { - return ReadOnlyShortArrayBuffer.copy(this, mark); - } - - public ShortBuffer compact() { - System.arraycopy(backingArray, position + offset, backingArray, offset, - remaining()); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - public ShortBuffer duplicate() { - return copy(this, mark); - } - - public boolean isReadOnly() { - return false; - } - - protected short[] protectedArray() { - return backingArray; - } - - protected int protectedArrayOffset() { - return offset; - } - - protected boolean protectedHasArray() { - return true; - } - - public ShortBuffer put(short c) { - if (position == limit) { - throw new BufferOverflowException(); - } - backingArray[offset + position++] = c; - return this; - } - - public ShortBuffer put(int index, short c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - backingArray[offset + index] = c; - return this; - } - - public ShortBuffer put(short[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferOverflowException(); - } - System.arraycopy(src, off, backingArray, offset+position, len); - position += len; - return this; - } - - public ShortBuffer slice() { - return new ReadWriteShortArrayBuffer(remaining(), backingArray, offset - + position); - } + static ReadWriteShortArrayBuffer copy (ShortArrayBuffer other, int markOfOther) { + ReadWriteShortArrayBuffer buf = new ReadWriteShortArrayBuffer(other.capacity(), other.backingArray, other.offset); + buf.limit = other.limit(); + buf.position = other.position(); + buf.mark = markOfOther; + return buf; + } + + ReadWriteShortArrayBuffer (short[] array) { + super(array); + } + + ReadWriteShortArrayBuffer (int capacity) { + super(capacity); + } + + ReadWriteShortArrayBuffer (int capacity, short[] backingArray, int arrayOffset) { + super(capacity, backingArray, arrayOffset); + } + + public ShortBuffer asReadOnlyBuffer () { + return ReadOnlyShortArrayBuffer.copy(this, mark); + } + + public ShortBuffer compact () { + System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + public ShortBuffer duplicate () { + return copy(this, mark); + } + + public boolean isReadOnly () { + return false; + } + + protected short[] protectedArray () { + return backingArray; + } + + protected int protectedArrayOffset () { + return offset; + } + + protected boolean protectedHasArray () { + return true; + } + + public ShortBuffer put (short c) { + if (position == limit) { + throw new BufferOverflowException(); + } + backingArray[offset + position++] = c; + return this; + } + + public ShortBuffer put (int index, short c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + backingArray[offset + index] = c; + return this; + } + + public ShortBuffer put (short[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferOverflowException(); + } + System.arraycopy(src, off, backingArray, offset + position, len); + position += len; + return this; + } + + public ShortBuffer slice () { + return new ReadWriteShortArrayBuffer(remaining(), backingArray, offset + position); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortArrayBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortArrayBuffer.java index 54f8adb45d1..fce335dfecd 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortArrayBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortArrayBuffer.java @@ -17,72 +17,67 @@ package java.nio; -/** - * ShortArrayBuffer, ReadWriteShortArrayBuffer and ReadOnlyShortArrayBuffer - * compose the implementation of array based short buffers. +/** ShortArrayBuffer, ReadWriteShortArrayBuffer and ReadOnlyShortArrayBuffer compose the implementation of array based short + * buffers. *

    - * ShortArrayBuffer implements all the shared readonly methods and is extended - * by the other two classes. + * ShortArrayBuffer implements all the shared readonly methods and is extended by the other two classes. *

    *

    * All methods are marked final for runtime performance. - *

    - * - */ + *

    */ abstract class ShortArrayBuffer extends ShortBuffer { - protected final short[] backingArray; + protected final short[] backingArray; + + protected final int offset; - protected final int offset; + ShortArrayBuffer (short[] array) { + this(array.length, array, 0); + } - ShortArrayBuffer(short[] array) { - this(array.length, array, 0); - } + ShortArrayBuffer (int capacity) { + this(capacity, new short[capacity], 0); + } - ShortArrayBuffer(int capacity) { - this(capacity, new short[capacity], 0); - } + ShortArrayBuffer (int capacity, short[] backingArray, int offset) { + super(capacity); + this.backingArray = backingArray; + this.offset = offset; + } - ShortArrayBuffer(int capacity, short[] backingArray, int offset) { - super(capacity); - this.backingArray = backingArray; - this.offset = offset; - } + public final short get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return backingArray[offset + position++]; + } - public final short get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return backingArray[offset + position++]; - } + public final short get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return backingArray[offset + index]; + } - public final short get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return backingArray[offset + index]; - } + public final ShortBuffer get (short[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + System.arraycopy(backingArray, offset + position, dest, off, len); + position += len; + return this; + } - public final ShortBuffer get(short[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - System.arraycopy(backingArray, offset + position, dest, - off, len); - position += len; - return this; - } - - public final boolean isDirect() { - return false; - } + public final boolean isDirect () { + return false; + } - public final ByteOrder order() { - return ByteOrder.nativeOrder(); - } + public final ByteOrder order () { + return ByteOrder.nativeOrder(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortBuffer.java index 200af2f6c14..6ab2eda7bdc 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortBuffer.java @@ -17,560 +17,412 @@ package java.nio; -/** - * A buffer of shorts. +/** A buffer of shorts. *

    * A short buffer can be created in either of the following ways: *

    *
      - *
    • {@link #allocate(int) Allocate} a new short array and create a buffer - * based on it;
    • - *
    • {@link #wrap(short[]) Wrap} an existing short array to create a new - * buffer;
    • - *
    • Use {@link java.nio.ByteBuffer#asShortBuffer() ByteBuffer.asShortBuffer} - * to create a short buffer based on a byte buffer.
    • + *
    • {@link #allocate(int) Allocate} a new short array and create a buffer based on it;
    • + *
    • {@link #wrap(short[]) Wrap} an existing short array to create a new buffer;
    • + *
    • Use {@link java.nio.ByteBuffer#asShortBuffer() ByteBuffer.asShortBuffer} to create a short buffer based on a byte buffer.
    • *
    * - * @since Android 1.0 - */ + * @since Android 1.0 */ public abstract class ShortBuffer extends Buffer implements Comparable { - /** - * Creates a short buffer based on a newly allocated short array. - * - * @param capacity - * the capacity of the new buffer. - * @return the created short buffer. - * @throws IllegalArgumentException - * if {@code capacity} is less than zero. - * @since Android 1.0 - */ - public static ShortBuffer allocate(int capacity) { - if (capacity < 0) { - throw new IllegalArgumentException(); - } - return BufferFactory.newShortBuffer(capacity); - } - - /** - * Creates a new short buffer by wrapping the given short array. - *

    - * Calling this method has the same effect as - * {@code wrap(array, 0, array.length)}. - *

    - * - * @param array - * the short array which the new buffer will be based on. - * @return the created short buffer. - * @since Android 1.0 - */ - public static ShortBuffer wrap(short[] array) { - return wrap(array, 0, array.length); - } - - /** - * Creates a new short buffer by wrapping the given short array. - *

    - * The new buffer's position will be {@code start}, limit will be - * {@code start + len}, capacity will be the length of the array. - *

    - * - * @param array - * the short array which the new buffer will be based on. - * @param start - * the start index, must not be negative and not greater than - * {@code array.length}. - * @param len - * the length, must not be negative and not greater than - * {@code array.length - start}. - * @return the created short buffer. - * @exception IndexOutOfBoundsException - * if either {@code start} or {@code len} is invalid. - * @since Android 1.0 - */ - public static ShortBuffer wrap(short[] array, int start, int len) { - if (array == null) { - throw new NullPointerException(); - } - if (start< 0 || len < 0 || (long)start + (long)len > array.length) { - throw new IndexOutOfBoundsException(); - } - - ShortBuffer buf = BufferFactory.newShortBuffer(array); - buf.position = start; - buf.limit = start + len; - - return buf; - } - - /** - * Constructs a {@code ShortBuffer} with given capacity. - * - * @param capacity - * The capacity of the buffer - */ - ShortBuffer(int capacity) { - super(capacity); - } - - /** - * Returns the short array which this buffer is based on, if there is one. - * - * @return the short array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final short[] array() { - return protectedArray(); - } - - /** - * Returns the offset of the short array which this buffer is based on, if - * there is one. - *

    - * The offset is the index of the array corresponding to the zero position - * of the buffer. - *

    - * - * @return the offset of the short array which this buffer is based on. - * @exception ReadOnlyBufferException - * if this buffer is based on an array, but it is read-only. - * @exception UnsupportedOperationException - * if this buffer is not based on an array. - * @since Android 1.0 - */ - public final int arrayOffset() { - return protectedArrayOffset(); - } - - /** - * Returns a read-only buffer that shares its content with this buffer. - *

    - * The returned buffer is guaranteed to be a new instance, even if this - * buffer is read-only itself. The new buffer's position, limit, capacity - * and mark are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means this - * buffer's change of content will be visible to the new buffer. The two - * buffer's position, limit and mark are independent. - *

    - * - * @return a read-only version of this buffer. - * @since Android 1.0 - */ - public abstract ShortBuffer asReadOnlyBuffer(); - - /** - * Compacts this short buffer. - *

    - * The remaining shorts will be moved to the head of the buffer, starting - * from position zero. Then the position is set to {@code remaining()}; the - * limit is set to capacity; the mark is cleared. - *

    - * - * @return this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ShortBuffer compact(); - - /** - * Compare the remaining shorts of this buffer to another short buffer's - * remaining shorts. - * - * @param otherBuffer - * another short buffer. - * @return a negative value if this is less than {@code otherBuffer}; 0 if - * this equals to {@code otherBuffer}; a positive value if this is - * greater than {@code otherBuffer}. - * @exception ClassCastException - * if {@code otherBuffer} is not a short buffer. - * @since Android 1.0 - */ - public int compareTo(ShortBuffer otherBuffer) { - int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() - : otherBuffer.remaining(); - int thisPos = position; - int otherPos = otherBuffer.position; - short thisByte, otherByte; - while (compareRemaining > 0) { - thisByte = get(thisPos); - otherByte = otherBuffer.get(otherPos); - if (thisByte != otherByte) { - return thisByte < otherByte ? -1 : 1; - } - thisPos++; - otherPos++; - compareRemaining--; - } - return remaining() - otherBuffer.remaining(); - } - - /** - * Returns a duplicated buffer that shares its content with this buffer. - *

    - * The duplicated buffer's position, limit, capacity and mark are the same - * as this buffer. The duplicated buffer's read-only property and byte order - * are the same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a duplicated buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract ShortBuffer duplicate(); - - /** - * Checks whether this short buffer is equal to another object. - *

    - * If {@code other} is not a short buffer then {@code false} is returned. - * Two short buffers are equal if and only if their remaining shorts are - * exactly the same. Position, limit, capacity and mark are not considered. - *

    - * - * @param other - * the object to compare with this short buffer. - * @return {@code true} if this short buffer is equal to {@code other}, - * {@code false} otherwise. - * @since Android 1.0 - */ - public boolean equals(Object other) { - if (!(other instanceof ShortBuffer)) { - return false; - } - ShortBuffer otherBuffer = (ShortBuffer) other; - - if (remaining() != otherBuffer.remaining()) { - return false; - } - - int myPosition = position; - int otherPosition = otherBuffer.position; - boolean equalSoFar = true; - while (equalSoFar && (myPosition < limit)) { - equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); - } - - return equalSoFar; - } - - /** - * Returns the short at the current position and increases the position by - * 1. - * - * @return the short at the current position. - * @exception BufferUnderflowException - * if the position is equal or greater than limit. - * @since Android 1.0 - */ - public abstract short get(); - - /** - * Reads shorts from the current position into the specified short array and - * increases the position by the number of shorts read. - *

    - * Calling this method has the same effect as - * {@code get(dest, 0, dest.length)}. - *

    - * - * @param dest - * the destination short array. - * @return this buffer. - * @exception BufferUnderflowException - * if {@code dest.length} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public ShortBuffer get(short[] dest) { - return get(dest, 0, dest.length); - } - - /** - * Reads shorts from the current position into the specified short array, - * starting from the specified offset, and increases the position by the - * number of shorts read. - * - * @param dest - * the target short array. - * @param off - * the offset of the short array, must not be negative and not - * greater than {@code dest.length}. - * @param len - * the number of shorts to read, must be no less than zero and - * not greater than {@code dest.length - off}. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception BufferUnderflowException - * if {@code len} is greater than {@code remaining()}. - * @since Android 1.0 - */ - public ShortBuffer get(short[] dest, int off, int len) { - int length = dest.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - if (len > remaining()) { - throw new BufferUnderflowException(); - } - for (int i = off; i < off + len; i++) { - dest[i] = get(); - } - return this; - } - - /** - * Returns the short at the specified index; the position is not changed. - * - * @param index - * the index, must not be negative and less than limit. - * @return a short at the specified index. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @since Android 1.0 - */ - public abstract short get(int index); - - /** - * Indicates whether this buffer is based on a short array and is - * read/write. - * - * @return {@code true} if this buffer is based on a short array and - * provides read/write access, {@code false} otherwise. - * @since Android 1.0 - */ - public final boolean hasArray() { - return protectedHasArray(); - } - - /** - * Calculates this buffer's hash code from the remaining chars. The - * position, limit, capacity and mark don't affect the hash code. - * - * @return the hash code calculated from the remaining shorts. - * @since Android 1.0 - */ - public int hashCode() { - int myPosition = position; - int hash = 0; - while (myPosition < limit) { - hash = hash + get(myPosition++); - } - return hash; - } - - /** - * Indicates whether this buffer is direct. A direct buffer will try its - * best to take advantage of native memory APIs and it may not stay in the - * Java heap, so it is not affected by garbage collection. - *

    - * A short buffer is direct if it is based on a byte buffer and the byte - * buffer is direct. - *

    - * - * @return {@code true} if this buffer is direct, {@code false} otherwise. - * @since Android 1.0 - */ - public abstract boolean isDirect(); - - /** - * Returns the byte order used by this buffer when converting shorts from/to - * bytes. - *

    - * If this buffer is not based on a byte buffer, then always return the - * platform's native byte order. - *

    - * - * @return the byte order used by this buffer when converting shorts from/to - * bytes. - * @since Android 1.0 - */ - public abstract ByteOrder order(); - - /** - * Child class implements this method to realize {@code array()}. - * - * @return see {@code array()} - */ - abstract short[] protectedArray(); - - /** - * Child class implements this method to realize {@code arrayOffset()}. - * - * @return see {@code arrayOffset()} - */ - abstract int protectedArrayOffset(); - - /** - * Child class implements this method to realize {@code hasArray()}. - * - * @return see {@code hasArray()} - */ - abstract boolean protectedHasArray(); - - /** - * Writes the given short to the current position and increases the position - * by 1. - * - * @param s - * the short to write. - * @return this buffer. - * @exception BufferOverflowException - * if position is equal or greater than limit. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ShortBuffer put(short s); - - /** - * Writes shorts from the given short array to the current position and - * increases the position by the number of shorts written. - *

    - * Calling this method has the same effect as - * {@code put(src, 0, src.length)}. - *

    - * - * @param src - * the source short array. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code src.length}. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public final ShortBuffer put(short[] src) { - return put(src, 0, src.length); - } - - /** - * Writes shorts from the given short array, starting from the specified - * offset, to the current position and increases the position by the number - * of shorts written. - * - * @param src - * the source short array. - * @param off - * the offset of short array, must not be negative and not - * greater than {@code src.length}. - * @param len - * the number of shorts to write, must be no less than zero and - * not greater than {@code src.length - off}. - * @return this buffer. - * @exception BufferOverflowException - * if {@code remaining()} is less than {@code len}. - * @exception IndexOutOfBoundsException - * if either {@code off} or {@code len} is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public ShortBuffer put(short[] src, int off, int len) { - int length = src.length; - if (off < 0 || len < 0 || (long)off + (long)len > length) { - throw new IndexOutOfBoundsException(); - } - - if (len > remaining()) { - throw new BufferOverflowException(); - } - for (int i = off; i < off + len; i++) { - put(src[i]); - } - return this; - } - - /** - * Writes all the remaining shorts of the {@code src} short buffer to this - * buffer's current position, and increases both buffers' position by the - * number of shorts copied. - * - * @param src - * the source short buffer. - * @return this buffer. - * @exception BufferOverflowException - * if {@code src.remaining()} is greater than this buffer's - * {@code remaining()}. - * @exception IllegalArgumentException - * if {@code src} is this buffer. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public ShortBuffer put(ShortBuffer src) { - if (src == this) { - throw new IllegalArgumentException(); - } - if (src.remaining() > remaining()) { - throw new BufferOverflowException(); - } - short[] contents = new short[src.remaining()]; - src.get(contents); - put(contents); - return this; - } - - /** - * Writes a short to the specified index of this buffer; the position is not - * changed. - * - * @param index - * the index, must not be negative and less than the limit. - * @param s - * the short to write. - * @return this buffer. - * @exception IndexOutOfBoundsException - * if index is invalid. - * @exception ReadOnlyBufferException - * if no changes may be made to the contents of this buffer. - * @since Android 1.0 - */ - public abstract ShortBuffer put(int index, short s); - - /** - * Returns a sliced buffer that shares its content with this buffer. - *

    - * The sliced buffer's capacity will be this buffer's {@code remaining()}, - * and its zero position will correspond to this buffer's current position. - * The new buffer's position will be 0, limit will be its capacity, and its - * mark is cleared. The new buffer's read-only property and byte order are - * same as this buffer's. - *

    - *

    - * The new buffer shares its content with this buffer, which means either - * buffer's change of content will be visible to the other. The two buffer's - * position, limit and mark are independent. - *

    - * - * @return a sliced buffer that shares its content with this buffer. - * @since Android 1.0 - */ - public abstract ShortBuffer slice(); - - /** - * Returns a string representing the state of this short buffer. - * - * @return a string representing the state of this short buffer. - * @since Android 1.0 - */ - public String toString() { - StringBuffer buf = new StringBuffer(); - buf.append(getClass().getName()); - buf.append(", status: capacity="); //$NON-NLS-1$ - buf.append(capacity()); - buf.append(" position="); //$NON-NLS-1$ - buf.append(position()); - buf.append(" limit="); //$NON-NLS-1$ - buf.append(limit()); - return buf.toString(); - } + /** Creates a short buffer based on a newly allocated short array. + * + * @param capacity the capacity of the new buffer. + * @return the created short buffer. + * @throws IllegalArgumentException if {@code capacity} is less than zero. + * @since Android 1.0 */ + public static ShortBuffer allocate (int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException(); + } + return BufferFactory.newShortBuffer(capacity); + } + + /** Creates a new short buffer by wrapping the given short array. + *

    + * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. + *

    + * + * @param array the short array which the new buffer will be based on. + * @return the created short buffer. + * @since Android 1.0 */ + public static ShortBuffer wrap (short[] array) { + return wrap(array, 0, array.length); + } + + /** Creates a new short buffer by wrapping the given short array. + *

    + * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the + * array. + *

    + * + * @param array the short array which the new buffer will be based on. + * @param start the start index, must not be negative and not greater than {@code array.length}. + * @param len the length, must not be negative and not greater than {@code array.length - start}. + * @return the created short buffer. + * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. + * @since Android 1.0 */ + public static ShortBuffer wrap (short[] array, int start, int len) { + if (array == null) { + throw new NullPointerException(); + } + if (start < 0 || len < 0 || (long)start + (long)len > array.length) { + throw new IndexOutOfBoundsException(); + } + + ShortBuffer buf = BufferFactory.newShortBuffer(array); + buf.position = start; + buf.limit = start + len; + + return buf; + } + + /** Constructs a {@code ShortBuffer} with given capacity. + * + * @param capacity The capacity of the buffer */ + ShortBuffer (int capacity) { + super(capacity); + } + + /** Returns the short array which this buffer is based on, if there is one. + * + * @return the short array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final short[] array () { + return protectedArray(); + } + + /** Returns the offset of the short array which this buffer is based on, if there is one. + *

    + * The offset is the index of the array corresponding to the zero position of the buffer. + *

    + * + * @return the offset of the short array which this buffer is based on. + * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. + * @exception UnsupportedOperationException if this buffer is not based on an array. + * @since Android 1.0 */ + public final int arrayOffset () { + return protectedArrayOffset(); + } + + /** Returns a read-only buffer that shares its content with this buffer. + *

    + * The returned buffer is guaranteed to be a new instance, even if this buffer is read-only itself. The new buffer's position, + * limit, capacity and mark are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means this buffer's change of content will be visible to the new + * buffer. The two buffer's position, limit and mark are independent. + *

    + * + * @return a read-only version of this buffer. + * @since Android 1.0 */ + public abstract ShortBuffer asReadOnlyBuffer (); + + /** Compacts this short buffer. + *

    + * The remaining shorts will be moved to the head of the buffer, starting from position zero. Then the position is set to + * {@code remaining()}; the limit is set to capacity; the mark is cleared. + *

    + * + * @return this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ShortBuffer compact (); + + /** Compare the remaining shorts of this buffer to another short buffer's remaining shorts. + * + * @param otherBuffer another short buffer. + * @return a negative value if this is less than {@code otherBuffer}; 0 if this equals to {@code otherBuffer}; a positive value + * if this is greater than {@code otherBuffer}. + * @exception ClassCastException if {@code otherBuffer} is not a short buffer. + * @since Android 1.0 */ + public int compareTo (ShortBuffer otherBuffer) { + int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); + int thisPos = position; + int otherPos = otherBuffer.position; + short thisByte, otherByte; + while (compareRemaining > 0) { + thisByte = get(thisPos); + otherByte = otherBuffer.get(otherPos); + if (thisByte != otherByte) { + return thisByte < otherByte ? -1 : 1; + } + thisPos++; + otherPos++; + compareRemaining--; + } + return remaining() - otherBuffer.remaining(); + } + + /** Returns a duplicated buffer that shares its content with this buffer. + *

    + * The duplicated buffer's position, limit, capacity and mark are the same as this buffer. The duplicated buffer's read-only + * property and byte order are the same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a duplicated buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract ShortBuffer duplicate (); + + /** Checks whether this short buffer is equal to another object. + *

    + * If {@code other} is not a short buffer then {@code false} is returned. Two short buffers are equal if and only if their + * remaining shorts are exactly the same. Position, limit, capacity and mark are not considered. + *

    + * + * @param other the object to compare with this short buffer. + * @return {@code true} if this short buffer is equal to {@code other}, {@code false} otherwise. + * @since Android 1.0 */ + public boolean equals (Object other) { + if (!(other instanceof ShortBuffer)) { + return false; + } + ShortBuffer otherBuffer = (ShortBuffer)other; + + if (remaining() != otherBuffer.remaining()) { + return false; + } + + int myPosition = position; + int otherPosition = otherBuffer.position; + boolean equalSoFar = true; + while (equalSoFar && (myPosition < limit)) { + equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); + } + + return equalSoFar; + } + + /** Returns the short at the current position and increases the position by 1. + * + * @return the short at the current position. + * @exception BufferUnderflowException if the position is equal or greater than limit. + * @since Android 1.0 */ + public abstract short get (); + + /** Reads shorts from the current position into the specified short array and increases the position by the number of shorts + * read. + *

    + * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. + *

    + * + * @param dest the destination short array. + * @return this buffer. + * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. + * @since Android 1.0 */ + public ShortBuffer get (short[] dest) { + return get(dest, 0, dest.length); + } + + /** Reads shorts from the current position into the specified short array, starting from the specified offset, and increases the + * position by the number of shorts read. + * + * @param dest the target short array. + * @param off the offset of the short array, must not be negative and not greater than {@code dest.length}. + * @param len the number of shorts to read, must be no less than zero and not greater than {@code dest.length - off}. + * @return this buffer. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. + * @since Android 1.0 */ + public ShortBuffer get (short[] dest, int off, int len) { + int length = dest.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + if (len > remaining()) { + throw new BufferUnderflowException(); + } + for (int i = off; i < off + len; i++) { + dest[i] = get(); + } + return this; + } + + /** Returns the short at the specified index; the position is not changed. + * + * @param index the index, must not be negative and less than limit. + * @return a short at the specified index. + * @exception IndexOutOfBoundsException if index is invalid. + * @since Android 1.0 */ + public abstract short get (int index); + + /** Indicates whether this buffer is based on a short array and is read/write. + * + * @return {@code true} if this buffer is based on a short array and provides read/write access, {@code false} otherwise. + * @since Android 1.0 */ + public final boolean hasArray () { + return protectedHasArray(); + } + + /** Calculates this buffer's hash code from the remaining chars. The position, limit, capacity and mark don't affect the hash + * code. + * + * @return the hash code calculated from the remaining shorts. + * @since Android 1.0 */ + public int hashCode () { + int myPosition = position; + int hash = 0; + while (myPosition < limit) { + hash = hash + get(myPosition++); + } + return hash; + } + + /** Indicates whether this buffer is direct. A direct buffer will try its best to take advantage of native memory APIs and it + * may not stay in the Java heap, so it is not affected by garbage collection. + *

    + * A short buffer is direct if it is based on a byte buffer and the byte buffer is direct. + *

    + * + * @return {@code true} if this buffer is direct, {@code false} otherwise. + * @since Android 1.0 */ + public abstract boolean isDirect (); + + /** Returns the byte order used by this buffer when converting shorts from/to bytes. + *

    + * If this buffer is not based on a byte buffer, then always return the platform's native byte order. + *

    + * + * @return the byte order used by this buffer when converting shorts from/to bytes. + * @since Android 1.0 */ + public abstract ByteOrder order (); + + /** Child class implements this method to realize {@code array()}. + * + * @return see {@code array()} */ + abstract short[] protectedArray (); + + /** Child class implements this method to realize {@code arrayOffset()}. + * + * @return see {@code arrayOffset()} */ + abstract int protectedArrayOffset (); + + /** Child class implements this method to realize {@code hasArray()}. + * + * @return see {@code hasArray()} */ + abstract boolean protectedHasArray (); + + /** Writes the given short to the current position and increases the position by 1. + * + * @param s the short to write. + * @return this buffer. + * @exception BufferOverflowException if position is equal or greater than limit. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ShortBuffer put (short s); + + /** Writes shorts from the given short array to the current position and increases the position by the number of shorts written. + *

    + * Calling this method has the same effect as {@code put(src, 0, src.length)}. + *

    + * + * @param src the source short array. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public final ShortBuffer put (short[] src) { + return put(src, 0, src.length); + } + + /** Writes shorts from the given short array, starting from the specified offset, to the current position and increases the + * position by the number of shorts written. + * + * @param src the source short array. + * @param off the offset of short array, must not be negative and not greater than {@code src.length}. + * @param len the number of shorts to write, must be no less than zero and not greater than {@code src.length - off}. + * @return this buffer. + * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. + * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public ShortBuffer put (short[] src, int off, int len) { + int length = src.length; + if (off < 0 || len < 0 || (long)off + (long)len > length) { + throw new IndexOutOfBoundsException(); + } + + if (len > remaining()) { + throw new BufferOverflowException(); + } + for (int i = off; i < off + len; i++) { + put(src[i]); + } + return this; + } + + /** Writes all the remaining shorts of the {@code src} short buffer to this buffer's current position, and increases both + * buffers' position by the number of shorts copied. + * + * @param src the source short buffer. + * @return this buffer. + * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. + * @exception IllegalArgumentException if {@code src} is this buffer. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public ShortBuffer put (ShortBuffer src) { + if (src == this) { + throw new IllegalArgumentException(); + } + if (src.remaining() > remaining()) { + throw new BufferOverflowException(); + } + short[] contents = new short[src.remaining()]; + src.get(contents); + put(contents); + return this; + } + + /** Writes a short to the specified index of this buffer; the position is not changed. + * + * @param index the index, must not be negative and less than the limit. + * @param s the short to write. + * @return this buffer. + * @exception IndexOutOfBoundsException if index is invalid. + * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. + * @since Android 1.0 */ + public abstract ShortBuffer put (int index, short s); + + /** Returns a sliced buffer that shares its content with this buffer. + *

    + * The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero position will correspond to this + * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new + * buffer's read-only property and byte order are same as this buffer's. + *

    + *

    + * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the + * other. The two buffer's position, limit and mark are independent. + *

    + * + * @return a sliced buffer that shares its content with this buffer. + * @since Android 1.0 */ + public abstract ShortBuffer slice (); + + /** Returns a string representing the state of this short buffer. + * + * @return a string representing the state of this short buffer. + * @since Android 1.0 */ + public String toString () { + StringBuffer buf = new StringBuffer(); + buf.append(getClass().getName()); + buf.append(", status: capacity="); //$NON-NLS-1$ + buf.append(capacity()); + buf.append(" position="); //$NON-NLS-1$ + buf.append(position()); + buf.append(" limit="); //$NON-NLS-1$ + buf.append(limit()); + return buf.toString(); + } } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortToByteBufferAdapter.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortToByteBufferAdapter.java index 325d7eaec90..868072cddd4 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortToByteBufferAdapter.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/ShortToByteBufferAdapter.java @@ -16,194 +16,189 @@ package java.nio; - //import org.apache.harmony.nio.internal.DirectBuffer; //import org.apache.harmony.luni.platform.PlatformAddress; -/** - * This class wraps a byte buffer to be a short buffer. +/** This class wraps a byte buffer to be a short buffer. *

    * Implementation notice: *

      - *
    • After a byte buffer instance is wrapped, it becomes privately owned by - * the adapter. It must NOT be accessed outside the adapter any more.
    • - *
    • The byte buffer's position and limit are NOT linked with the adapter. - * The adapter extends Buffer, thus has its own position and limit.
    • + *
    • After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the + * adapter any more.
    • + *
    • The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position + * and limit.
    • *
    - *

    - */ + *

    */ final class ShortToByteBufferAdapter extends ShortBuffer implements ByteBufferWrapper { -//implements DirectBuffer { - - static ShortBuffer wrap(ByteBuffer byteBuffer) { - return new ShortToByteBufferAdapter(byteBuffer.slice()); - } - - private final ByteBuffer byteBuffer; - - ShortToByteBufferAdapter(ByteBuffer byteBuffer) { - super((byteBuffer.capacity() >> 1)); - this.byteBuffer = byteBuffer; - this.byteBuffer.clear(); - } - -// public int getByteCapacity() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getByteCapacity(); -// } -// assert false : byteBuffer; -// return -1; -// } +// implements DirectBuffer { + + static ShortBuffer wrap (ByteBuffer byteBuffer) { + return new ShortToByteBufferAdapter(byteBuffer.slice()); + } + + private final ByteBuffer byteBuffer; + + ShortToByteBufferAdapter (ByteBuffer byteBuffer) { + super((byteBuffer.capacity() >> 1)); + this.byteBuffer = byteBuffer; + this.byteBuffer.clear(); + } + +// public int getByteCapacity() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getByteCapacity(); +// } +// assert false : byteBuffer; +// return -1; +// } // -// public PlatformAddress getEffectiveAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getEffectiveAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getEffectiveAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public PlatformAddress getBaseAddress() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).getBaseAddress(); -// } -// assert false : byteBuffer; -// return null; -// } +// public PlatformAddress getBaseAddress() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).getBaseAddress(); +// } +// assert false : byteBuffer; +// return null; +// } // -// public boolean isAddressValid() { -// if (byteBuffer instanceof DirectBuffer) { -// return ((DirectBuffer) byteBuffer).isAddressValid(); -// } -// assert false : byteBuffer; -// return false; -// } +// public boolean isAddressValid() { +// if (byteBuffer instanceof DirectBuffer) { +// return ((DirectBuffer) byteBuffer).isAddressValid(); +// } +// assert false : byteBuffer; +// return false; +// } // -// public void addressValidityCheck() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).addressValidityCheck(); -// } else { -// assert false : byteBuffer; -// } -// } +// public void addressValidityCheck() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).addressValidityCheck(); +// } else { +// assert false : byteBuffer; +// } +// } // -// public void free() { -// if (byteBuffer instanceof DirectBuffer) { -// ((DirectBuffer) byteBuffer).free(); -// } else { -// assert false : byteBuffer; -// } -// } - - @Override - public ShortBuffer asReadOnlyBuffer() { - ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer - .asReadOnlyBuffer()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public ShortBuffer compact() { - if (byteBuffer.isReadOnly()) { - throw new ReadOnlyBufferException(); - } - byteBuffer.limit(limit << 1); - byteBuffer.position(position << 1); - byteBuffer.compact(); - byteBuffer.clear(); - position = limit - position; - limit = capacity; - mark = UNSET_MARK; - return this; - } - - @Override - public ShortBuffer duplicate() { - ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer - .duplicate()); - buf.limit = limit; - buf.position = position; - buf.mark = mark; - return buf; - } - - @Override - public short get() { - if (position == limit) { - throw new BufferUnderflowException(); - } - return byteBuffer.getShort(position++ << 1); - } - - @Override - public short get(int index) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - return byteBuffer.getShort(index << 1); - } - - @Override - public boolean isDirect() { - return byteBuffer.isDirect(); - } - - @Override - public boolean isReadOnly() { - return byteBuffer.isReadOnly(); - } - - @Override - public ByteOrder order() { - return byteBuffer.order(); - } - - @Override - protected short[] protectedArray() { - throw new UnsupportedOperationException(); - } - - @Override - protected int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - @Override - protected boolean protectedHasArray() { - return false; - } - - @Override - public ShortBuffer put(short c) { - if (position == limit) { - throw new BufferOverflowException(); - } - byteBuffer.putShort(position++ << 1, c); - return this; - } - - @Override - public ShortBuffer put(int index, short c) { - if (index < 0 || index >= limit) { - throw new IndexOutOfBoundsException(); - } - byteBuffer.putShort(index << 1, c); - return this; - } - - @Override - public ShortBuffer slice() { - byteBuffer.limit(limit << 1); - byteBuffer.position(position << 1); - ShortBuffer result = new ShortToByteBufferAdapter(byteBuffer.slice()); - byteBuffer.clear(); - return result; - } - - public ByteBuffer getByteBuffer() { +// public void free() { +// if (byteBuffer instanceof DirectBuffer) { +// ((DirectBuffer) byteBuffer).free(); +// } else { +// assert false : byteBuffer; +// } +// } + + @Override + public ShortBuffer asReadOnlyBuffer () { + ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer.asReadOnlyBuffer()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public ShortBuffer compact () { + if (byteBuffer.isReadOnly()) { + throw new ReadOnlyBufferException(); + } + byteBuffer.limit(limit << 1); + byteBuffer.position(position << 1); + byteBuffer.compact(); + byteBuffer.clear(); + position = limit - position; + limit = capacity; + mark = UNSET_MARK; + return this; + } + + @Override + public ShortBuffer duplicate () { + ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer.duplicate()); + buf.limit = limit; + buf.position = position; + buf.mark = mark; + return buf; + } + + @Override + public short get () { + if (position == limit) { + throw new BufferUnderflowException(); + } + return byteBuffer.getShort(position++ << 1); + } + + @Override + public short get (int index) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + return byteBuffer.getShort(index << 1); + } + + @Override + public boolean isDirect () { + return byteBuffer.isDirect(); + } + + @Override + public boolean isReadOnly () { + return byteBuffer.isReadOnly(); + } + + @Override + public ByteOrder order () { + return byteBuffer.order(); + } + + @Override + protected short[] protectedArray () { + throw new UnsupportedOperationException(); + } + + @Override + protected int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean protectedHasArray () { + return false; + } + + @Override + public ShortBuffer put (short c) { + if (position == limit) { + throw new BufferOverflowException(); + } + byteBuffer.putShort(position++ << 1, c); + return this; + } + + @Override + public ShortBuffer put (int index, short c) { + if (index < 0 || index >= limit) { + throw new IndexOutOfBoundsException(); + } + byteBuffer.putShort(index << 1, c); + return this; + } + + @Override + public ShortBuffer slice () { + byteBuffer.limit(limit << 1); + byteBuffer.position(position << 1); + ShortBuffer result = new ShortToByteBufferAdapter(byteBuffer.slice()); + byteBuffer.clear(); + return result; + } + + public ByteBuffer getByteBuffer () { return byteBuffer; } diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/StringByteBuffer.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/StringByteBuffer.java index f342cae24e0..a5a4885946c 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/StringByteBuffer.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/StringByteBuffer.java @@ -1,202 +1,203 @@ + package java.nio; import com.google.gwt.corp.compatibility.Numbers; class StringByteBuffer extends BaseByteBuffer { - private String s; - - StringByteBuffer(String s) { - super(s.length()); - this.s = s; - order(ByteOrder.LITTLE_ENDIAN); - } - - StringByteBuffer(String s, int position, int limit) { - this(s); - this.position = position; - this.limit = limit; - } - - public ByteBuffer asReadOnlyBuffer() { - return this; - } - - byte[] protectedArray() { - throw new UnsupportedOperationException(); - } - - int protectedArrayOffset() { - throw new UnsupportedOperationException(); - } - - boolean protectedHasArray() { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer compact() { - return this; - } - - @Override - public ByteBuffer duplicate() { - return this; - } - - @Override - public byte get() { - return get(position++); - } - - @Override - public byte get(int index) { - return get(s, index); - } - - public final double getDouble() { - return Numbers.longBitsToDouble(getLong()); - } - - public final double getDouble(int index) { - return Numbers.longBitsToDouble(getLong(index)); - } - - public final float getFloat() { - return Numbers.intBitsToFloat(getInt()); - } - - public final float getFloat(int index) { - return Numbers.intBitsToFloat(getInt(index)); - } - - public final int getInt() { - int newPosition = position + 4; - int result = loadInt(position); - position = newPosition; - return result; - } - - public final int getInt(int index) { - return loadInt(index); - } - - public final long getLong() { - throw new UnsupportedOperationException(); - } - - public final long getLong(int index) { - throw new UnsupportedOperationException(); - } - - public final short getShort() { - int newPosition = position + 2; - short result = loadShort(position); - position = newPosition; - return result; - } - - public final short getShort(int index) { - return loadShort(index); - } - - @Override - public boolean isDirect() { - return false; - } - - @Override - public ByteBuffer put(byte b) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer put(int index, byte b) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putDouble(double value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putDouble(int index, double value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putFloat(float value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putFloat(int index, float value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putInt(int value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putInt(int index, int value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putLong(long value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putLong(int index, long value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putShort(short value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer putShort(int index, short value) { - throw new UnsupportedOperationException(); - } - - @Override - public ByteBuffer slice() { - // TODO(jgw): I don't think this is right, but might work for our purposes. - StringByteBuffer slice = new StringByteBuffer(s, position, limit); - slice.order = order; - return slice; - } - - @Override - public boolean isReadOnly() { - return true; - } - - private native byte get(String s, int i) /*-{ - var x = s.charCodeAt(i) & 0xff; - if (x > 127) x -= 256; - return x; - }-*/; - - protected final int loadInt(int baseOffset) { - int bytes = 0; - for (int i = 3; i >= 0; i--) { - bytes = bytes << 8; - bytes = bytes | (get(baseOffset + i) & 0xFF); - } - return bytes; - } - - protected final short loadShort(int baseOffset) { - short bytes = 0; - bytes = (short) (get(baseOffset + 1) << 8); - bytes |= (get(baseOffset) & 0xFF); - return bytes; - } + private String s; + + StringByteBuffer (String s) { + super(s.length()); + this.s = s; + order(ByteOrder.LITTLE_ENDIAN); + } + + StringByteBuffer (String s, int position, int limit) { + this(s); + this.position = position; + this.limit = limit; + } + + public ByteBuffer asReadOnlyBuffer () { + return this; + } + + byte[] protectedArray () { + throw new UnsupportedOperationException(); + } + + int protectedArrayOffset () { + throw new UnsupportedOperationException(); + } + + boolean protectedHasArray () { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer compact () { + return this; + } + + @Override + public ByteBuffer duplicate () { + return this; + } + + @Override + public byte get () { + return get(position++); + } + + @Override + public byte get (int index) { + return get(s, index); + } + + public final double getDouble () { + return Numbers.longBitsToDouble(getLong()); + } + + public final double getDouble (int index) { + return Numbers.longBitsToDouble(getLong(index)); + } + + public final float getFloat () { + return Numbers.intBitsToFloat(getInt()); + } + + public final float getFloat (int index) { + return Numbers.intBitsToFloat(getInt(index)); + } + + public final int getInt () { + int newPosition = position + 4; + int result = loadInt(position); + position = newPosition; + return result; + } + + public final int getInt (int index) { + return loadInt(index); + } + + public final long getLong () { + throw new UnsupportedOperationException(); + } + + public final long getLong (int index) { + throw new UnsupportedOperationException(); + } + + public final short getShort () { + int newPosition = position + 2; + short result = loadShort(position); + position = newPosition; + return result; + } + + public final short getShort (int index) { + return loadShort(index); + } + + @Override + public boolean isDirect () { + return false; + } + + @Override + public ByteBuffer put (byte b) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer put (int index, byte b) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putDouble (double value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putDouble (int index, double value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putFloat (float value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putFloat (int index, float value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putInt (int value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putInt (int index, int value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putLong (long value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putLong (int index, long value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putShort (short value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer putShort (int index, short value) { + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer slice () { + // TODO(jgw): I don't think this is right, but might work for our purposes. + StringByteBuffer slice = new StringByteBuffer(s, position, limit); + slice.order = order; + return slice; + } + + @Override + public boolean isReadOnly () { + return true; + } + + private native byte get (String s, int i) /*-{ + var x = s.charCodeAt(i) & 0xff; + if (x > 127) x -= 256; + return x; + }-*/; + + protected final int loadInt (int baseOffset) { + int bytes = 0; + for (int i = 3; i >= 0; i--) { + bytes = bytes << 8; + bytes = bytes | (get(baseOffset + i) & 0xFF); + } + return bytes; + } + + protected final short loadShort (int baseOffset) { + short bytes = 0; + bytes = (short)(get(baseOffset + 1) << 8); + bytes |= (get(baseOffset) & 0xFF); + return bytes; + } } diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioDevice.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioDevice.java index 9f1ad3478ce..30c57f046f3 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioDevice.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioDevice.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.openal; import javax.sound.sampled.AudioFormat; @@ -22,9 +23,7 @@ import com.badlogic.gdx.audio.AudioDevice; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * @author mzechner - */ +/** @author mzechner */ public class JavaSoundAudioDevice implements AudioDevice { private SourceDataLine line; private final boolean isMono; @@ -58,7 +57,7 @@ public void writeSamples (short[] samples, int offset, int numSamples) { 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); + bytes[j + 1] = (byte)(value >> 8); } int writtenBytes = line.write(bytes, 0, numSamples * 2); @@ -83,7 +82,8 @@ public void writeSamples (float[] samples, int offset, int numSamples) { writtenBytes += line.write(bytes, writtenBytes, numSamples * 2 - writtenBytes); } - @Override public int getLatency () { + @Override + public int getLatency () { return 0; } } diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioRecorder.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioRecorder.java index 0fb088bf775..20b29382ba4 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioRecorder.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/JavaSoundAudioRecorder.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.openal; import javax.sound.sampled.AudioFormat; @@ -23,9 +24,7 @@ import com.badlogic.gdx.audio.AudioRecorder; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * @author mzechner - */ +/** @author mzechner */ public class JavaSoundAudioRecorder implements AudioRecorder { private TargetDataLine line; private byte[] buffer = new byte[1024 * 4]; diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Mp3.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Mp3.java index acfe066e556..40aaf0041cf 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Mp3.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Mp3.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.openal; import java.io.ByteArrayOutputStream; @@ -26,9 +27,7 @@ import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * @author Nathan Sweet - */ +/** @author Nathan Sweet */ public class Mp3 { static public class Music extends OpenALMusic { // Note: This uses a slightly modified version of JLayer. @@ -43,12 +42,12 @@ public Music (OpenALAudio audio, FileHandle file) { decoder = new MP3Decoder(); try { Header header = bitstream.readFrame(); - if (header == null) throw new GdxRuntimeException("empty ogg"); + if (header == null) throw new GdxRuntimeException("empty ogg"); int channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2; outputBuffer = new OutputBuffer(channels, false); decoder.setOutputBuffer(outputBuffer); - setup(channels, header.getSampleRate()); - } catch(BitstreamException e) { + setup(channels, header.getSampleRate()); + } catch (BitstreamException e) { throw new GdxRuntimeException("error while preloading mp3", e); } } diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Ogg.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Ogg.java index 1d82cc122e1..fca46199812 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Ogg.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Ogg.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.openal; import java.io.ByteArrayOutputStream; import com.badlogic.gdx.files.FileHandle; -/** - * @author Nathan Sweet - */ +/** @author Nathan Sweet */ public class Ogg { static public class Music extends OpenALMusic { private OggInputStream input; diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OggInputStream.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OggInputStream.java index 2a42fccb2e7..30c135de2bd 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OggInputStream.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OggInputStream.java @@ -40,10 +40,8 @@ import com.jcraft.jorbis.DspState; import com.jcraft.jorbis.Info; -/** - * An input stream to read Ogg Vorbis. - * @author kevin - */ +/** An input stream to read Ogg Vorbis. + * @author kevin */ public class OggInputStream extends InputStream { /** The conversion buffer size */ private int convsize = 4096 * 4; @@ -90,11 +88,9 @@ public class OggInputStream extends InputStream { /** The total number of bytes */ private int total; - /** - * Create a new stream to decode OGG data + /** Create a new stream to decode OGG data * - * @param input The input stream from which to read the OGG file - */ + * @param input The input stream from which to read the OGG file */ public OggInputStream (InputStream input) { this.input = input; try { @@ -106,11 +102,9 @@ public OggInputStream (InputStream input) { init(); } - /** - * Get the number of bytes on the stream + /** Get the number of bytes on the stream * - * @return The number of the bytes on the stream - */ + * @return The number of the bytes on the stream */ public int getLength () { return total; } @@ -123,33 +117,25 @@ public int getSampleRate () { return oggInfo.rate; } - /** - * Initialise the streams and thread involved in the streaming of OGG data - */ + /** Initialise the streams and thread involved in the streaming of OGG data */ private void init () { initVorbis(); readPCM(); } - /** - * @see java.io.InputStream#available() - */ + /** @see java.io.InputStream#available() */ public int available () { return endOfStream ? 0 : 1; } - /** - * Initialise the vorbis decoding - */ + /** Initialise the vorbis decoding */ private void initVorbis () { syncState.init(); } - /** - * Get a page and packet from that page + /** Get a page and packet from that page * - * @return True if there was a page available - */ + * @return True if there was a page available */ private boolean getPageAndPacket () { // grab some data at the head of the stream. We want the first page // (which is guaranteed to be small and only contain the Vorbis @@ -274,9 +260,7 @@ private boolean getPageAndPacket () { return true; } - /** - * Decode the OGG file as shown in the jogg/jorbis examples - */ + /** Decode the OGG file as shown in the jogg/jorbis examples */ private void readPCM () { boolean wrote = false; diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java index ffde054388e..77e333bc1d7 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALAudio.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.openal; import java.nio.FloatBuffer; @@ -29,13 +30,10 @@ import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.IntArray; import com.badlogic.gdx.utils.ObjectMap; -import com.badlogic.gdx.utils.Pool; import static org.lwjgl.openal.AL10.*; -/** - * @author Nathan Sweet - */ +/** @author Nathan Sweet */ public class OpenALAudio implements Audio { private IntArray idleSources, allSources; private ObjectMap> extensionToSoundClass = new ObjectMap(); diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALSound.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALSound.java index dffce53e7d1..5d75b16b6ce 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALSound.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/OpenALSound.java @@ -13,20 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.openal; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import org.lwjgl.openal.AL11; - import com.badlogic.gdx.audio.Sound; import static org.lwjgl.openal.AL10.*; -/** - * @author Nathan Sweet - */ +/** @author Nathan Sweet */ public class OpenALSound implements Sound { private int bufferID = -1; private final OpenALAudio audio; diff --git a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Wav.java b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Wav.java index ee6e602f9ac..2c0101b8bf6 100644 --- a/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Wav.java +++ b/backends/gdx-openal/src/com/badlogic/gdx/backends/openal/Wav.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.backends.openal; import java.io.ByteArrayOutputStream; diff --git a/demos/cuboc/cuboc-android/src/com/badlogic/cuboc/Cuboc.java b/demos/cuboc/cuboc-android/src/com/badlogic/cuboc/Cuboc.java index 18f18f752a5..dc504b8b263 100644 --- a/demos/cuboc/cuboc-android/src/com/badlogic/cuboc/Cuboc.java +++ b/demos/cuboc/cuboc-android/src/com/badlogic/cuboc/Cuboc.java @@ -1,3 +1,4 @@ + package com.badlogic.cuboc; import android.os.Bundle; @@ -7,14 +8,14 @@ import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; public class Cuboc extends AndroidApplication { - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); - config.useAccelerometer = false; - config.useCompass = false; - config.useWakelock = true; - initialize(new Cubocy(), config); - } -} \ No newline at end of file + /** Called when the activity is first created. */ + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); + config.useAccelerometer = false; + config.useCompass = false; + config.useWakelock = true; + initialize(new Cubocy(), config); + } +} diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Bob.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Bob.java index 8c0948535ab..4a44fe94bb7 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Bob.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Bob.java @@ -12,7 +12,7 @@ public class Bob { static final int JUMP = 2; static final int SPAWN = 3; static final int DYING = 4; - static final int DEAD = 5; + static final int DEAD = 5; static final int LEFT = -1; static final int RIGHT = 1; static final float ACCELERATION = 20f; @@ -32,7 +32,7 @@ public class Bob { Map map; boolean grounded = false; - public Bob (Map map, float x, float y) { + public Bob (Map map, float x, float y) { this.map = map; pos.x = x; pos.y = y; @@ -47,52 +47,50 @@ public Bob (Map map, float x, float y) { public void update (float deltaTime) { processKeys(); - accel.y = -GRAVITY; + accel.y = -GRAVITY; accel.mul(deltaTime); vel.add(accel.x, accel.y); - if(accel.x == 0) vel.x *= DAMP; + if (accel.x == 0) vel.x *= DAMP; if (vel.x > MAX_VEL) vel.x = MAX_VEL; - if (vel.x < -MAX_VEL) vel.x = -MAX_VEL; - vel.mul(deltaTime); - tryMove(); + if (vel.x < -MAX_VEL) vel.x = -MAX_VEL; + vel.mul(deltaTime); + tryMove(); vel.mul(1.0f / deltaTime); - - if(state == SPAWN) { - if(stateTime > 0.4f) { + + if (state == SPAWN) { + if (stateTime > 0.4f) { state = IDLE; - } + } } - - if(state == DYING) { - if(stateTime > 0.4f) { + + if (state == DYING) { + if (stateTime > 0.4f) { state = DEAD; - } - } - - stateTime += deltaTime; + } + } + + stateTime += deltaTime; } private void processKeys () { - if(map.cube.state == Cube.CONTROLLED || state == SPAWN || state == DYING) return; - + if (map.cube.state == Cube.CONTROLLED || state == SPAWN || state == DYING) return; + float x0 = (Gdx.input.getX(0) / (float)Gdx.graphics.getWidth()) * 480; float x1 = (Gdx.input.getX(1) / (float)Gdx.graphics.getWidth()) * 480; float y0 = 320 - (Gdx.input.getY(0) / (float)Gdx.graphics.getHeight()) * 320; float y1 = 320 - (Gdx.input.getY(1) / (float)Gdx.graphics.getHeight()) * 320; - - boolean leftButton = (Gdx.input.isTouched(0) && x0 < 70) || - (Gdx.input.isTouched(1) && x1 < 70); - boolean rightButton = (Gdx.input.isTouched(0) && x0 > 70 && x0 < 134) || - (Gdx.input.isTouched(1) && x1 > 70 && x1 < 134); - boolean jumpButton = (Gdx.input.isTouched(0) && x0 > 416 && x0 < 480 && y0 < 64) || - (Gdx.input.isTouched(1) && x1 > 416 && x1 < 480 && y0 < 64); - - if ((Gdx.input.isKeyPressed(Keys.W) || jumpButton)&& state != JUMP) { + + boolean leftButton = (Gdx.input.isTouched(0) && x0 < 70) || (Gdx.input.isTouched(1) && x1 < 70); + boolean rightButton = (Gdx.input.isTouched(0) && x0 > 70 && x0 < 134) || (Gdx.input.isTouched(1) && x1 > 70 && x1 < 134); + boolean jumpButton = (Gdx.input.isTouched(0) && x0 > 416 && x0 < 480 && y0 < 64) + || (Gdx.input.isTouched(1) && x1 > 416 && x1 < 480 && y0 < 64); + + if ((Gdx.input.isKeyPressed(Keys.W) || jumpButton) && state != JUMP) { state = JUMP; - vel.y = JUMP_VELOCITY; + vel.y = JUMP_VELOCITY; grounded = false; } - + if (Gdx.input.isKeyPressed(Keys.A) || leftButton) { if (state != JUMP) state = RUN; dir = LEFT; @@ -107,40 +105,42 @@ private void processKeys () { } } - Rectangle[] r = { new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle() }; + Rectangle[] r = {new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle()}; - private void tryMove () { + private void tryMove () { bounds.x += vel.x; fetchCollidableRects(); - for(int i = 0; i < r.length; i++) { + for (int i = 0; i < r.length; i++) { Rectangle rect = r[i]; - if(bounds.overlaps(rect)) { - if(vel.x < 0) bounds.x = rect.x + rect.width + 0.01f; - else bounds.x = rect.x - bounds.width - 0.01f; + if (bounds.overlaps(rect)) { + if (vel.x < 0) + bounds.x = rect.x + rect.width + 0.01f; + else + bounds.x = rect.x - bounds.width - 0.01f; vel.x = 0; } - } - - bounds.y += vel.y; + } + + bounds.y += vel.y; fetchCollidableRects(); - for(int i = 0; i < r.length; i++) { + for (int i = 0; i < r.length; i++) { Rectangle rect = r[i]; - if(bounds.overlaps(rect)) { - if(vel.y < 0) { - bounds.y = rect.y + rect.height + 0.01f; + if (bounds.overlaps(rect)) { + if (vel.y < 0) { + bounds.y = rect.y + rect.height + 0.01f; grounded = true; - if(state != DYING && state != SPAWN) state = Math.abs(accel.x) > 0.1f?RUN:IDLE; - } - else bounds.y = rect.y - bounds.height - 0.01f; + if (state != DYING && state != SPAWN) state = Math.abs(accel.x) > 0.1f ? RUN : IDLE; + } else + bounds.y = rect.y - bounds.height - 0.01f; vel.y = 0; } - } - + } + pos.x = bounds.x - 0.2f; - pos.y = bounds.y; + pos.y = bounds.y; } - - private void fetchCollidableRects() { + + private void fetchCollidableRects () { int p1x = (int)bounds.x; int p1y = (int)Math.floor(bounds.y); int p2x = (int)(bounds.x + bounds.width); @@ -156,11 +156,11 @@ private void fetchCollidableRects() { int tile3 = tiles[p3x][map.tiles[0].length - 1 - p3y]; int tile4 = tiles[p4x][map.tiles[0].length - 1 - p4y]; - if(state != DYING && (map.isDeadly(tile1) || map.isDeadly(tile2) || map.isDeadly(tile3) || map.isDeadly(tile4))) { - state = DYING; - stateTime = 0; + if (state != DYING && (map.isDeadly(tile1) || map.isDeadly(tile2) || map.isDeadly(tile3) || map.isDeadly(tile4))) { + state = DYING; + stateTime = 0; } - + if (tile1 == Map.TILE) r[0].set(p1x, p1y, 1, 1); else @@ -177,14 +177,13 @@ private void fetchCollidableRects() { r[3].set(p4x, p4y, 1, 1); else r[3].set(-1, -1, 0, 0); - - if(map.cube.state == Cube.FIXED) { + + if (map.cube.state == Cube.FIXED) { r[4].x = map.cube.bounds.x; r[4].y = map.cube.bounds.y; r[4].width = map.cube.bounds.width; - r[4].height = map.cube.bounds.height; - } - else - r[4].set(-1, -1, 0, 0); + r[4].height = map.cube.bounds.height; + } else + r[4].set(-1, -1, 0, 0); } } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cube.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cube.java index e214336e9f7..e64b4626ed9 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cube.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cube.java @@ -1,8 +1,6 @@ -package com.badlogic.cubocy; -import org.lwjgl.opengl.Display; +package com.badlogic.cubocy; -import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.math.Rectangle; @@ -15,8 +13,8 @@ public class Cube { static final int DEAD = 3; static final float ACCELERATION = 20; static final float MAX_VELOCITY = 4; - static final float DAMP = 0.80f; - + static final float DAMP = 0.80f; + Map map; Vector2 pos = new Vector2(); Vector2 accel = new Vector2(); @@ -24,11 +22,11 @@ public class Cube { Rectangle bounds = new Rectangle(); int state = FOLLOW; float stateTime = 0; - Rectangle controllButtonRect = new Rectangle(480-64, 320-64, 64, 64); - Rectangle followButtonRect = new Rectangle(480-64, 320-138, 64, 64); + Rectangle controllButtonRect = new Rectangle(480 - 64, 320 - 64, 64, 64); + Rectangle followButtonRect = new Rectangle(480 - 64, 320 - 138, 64, 64); Rectangle dpadRect = new Rectangle(0, 0, 128, 128); - - public Cube(Map map, float x, float y) { + + public Cube (Map map, float x, float y) { this.map = map; this.pos.x = x; this.pos.y = y; @@ -36,110 +34,111 @@ public Cube(Map map, float x, float y) { this.bounds.y = pos.y + 0.2f; this.bounds.width = this.bounds.height = 1.0f; } - + Vector2 target = new Vector2(); - public void update(float deltaTime) { + + public void update (float deltaTime) { processKeys(); - - if(state == FOLLOW) { + + if (state == FOLLOW) { target.set(map.bob.pos); - if(map.bob.dir == Bob.RIGHT) target.x--; - if(map.bob.dir == Bob.LEFT) target.x++; + if (map.bob.dir == Bob.RIGHT) target.x--; + if (map.bob.dir == Bob.LEFT) target.x++; target.y += 0.2f; - + vel.set(target).sub(pos).mul(Math.min(4, pos.dst(target)) * deltaTime); - if(vel.len() > MAX_VELOCITY) vel.nor().mul(MAX_VELOCITY); + if (vel.len() > MAX_VELOCITY) vel.nor().mul(MAX_VELOCITY); tryMove(); } - - if(state == CONTROLLED) { + + if (state == CONTROLLED) { accel.mul(deltaTime); vel.add(accel.x, accel.y); - if(accel.x == 0) vel.x *= DAMP; - if(accel.y == 0) vel.y *= DAMP; + if (accel.x == 0) vel.x *= DAMP; + if (accel.y == 0) vel.y *= DAMP; if (vel.x > MAX_VELOCITY) vel.x = MAX_VELOCITY; if (vel.x < -MAX_VELOCITY) vel.x = -MAX_VELOCITY; if (vel.y > MAX_VELOCITY) vel.y = MAX_VELOCITY; if (vel.y < -MAX_VELOCITY) vel.y = -MAX_VELOCITY; - vel.mul(deltaTime); - tryMove(); + vel.mul(deltaTime); + tryMove(); vel.mul(1.0f / deltaTime); } - - if(state == FIXED) { -// if(stateTime > 5.0f) { -// stateTime = 0; -// state = FOLLOW; -// } + + if (state == FIXED) { +// if(stateTime > 5.0f) { +// stateTime = 0; +// state = FOLLOW; +// } } - + stateTime += deltaTime; } - + private void processKeys () { float x0 = (Gdx.input.getX(0) / (float)Gdx.graphics.getWidth()) * 480; float x1 = (Gdx.input.getX(1) / (float)Gdx.graphics.getWidth()) * 480; float y0 = 320 - (Gdx.input.getY(0) / (float)Gdx.graphics.getHeight()) * 320; float y1 = 320 - (Gdx.input.getY(1) / (float)Gdx.graphics.getHeight()) * 320; - boolean controlButton = (Gdx.input.isTouched(0) && controllButtonRect.contains(x0, y0)) || - (Gdx.input.isTouched(1) && controllButtonRect.contains(x1, y1)); - boolean followButton = (Gdx.input.isTouched(0) && followButtonRect.contains(x0, y0)) || - (Gdx.input.isTouched(1) && followButtonRect.contains(x1, y1)); - - if((Gdx.input.isKeyPressed(Keys.SPACE) || controlButton) && state == FOLLOW && stateTime > 0.5f) { + boolean controlButton = (Gdx.input.isTouched(0) && controllButtonRect.contains(x0, y0)) + || (Gdx.input.isTouched(1) && controllButtonRect.contains(x1, y1)); + boolean followButton = (Gdx.input.isTouched(0) && followButtonRect.contains(x0, y0)) + || (Gdx.input.isTouched(1) && followButtonRect.contains(x1, y1)); + + if ((Gdx.input.isKeyPressed(Keys.SPACE) || controlButton) && state == FOLLOW && stateTime > 0.5f) { stateTime = 0; state = CONTROLLED; return; - } - - if((Gdx.input.isKeyPressed(Keys.SPACE) || controlButton) && state == CONTROLLED && stateTime > 0.5f) { + } + + if ((Gdx.input.isKeyPressed(Keys.SPACE) || controlButton) && state == CONTROLLED && stateTime > 0.5f) { stateTime = 0; state = FIXED; return; } - - if((Gdx.input.isKeyPressed(Keys.SPACE) || controlButton) && state == FIXED && stateTime > 0.5f) { + + if ((Gdx.input.isKeyPressed(Keys.SPACE) || controlButton) && state == FIXED && stateTime > 0.5f) { stateTime = 0; state = CONTROLLED; return; - } - - if((Gdx.input.isKeyPressed(Keys.F) || followButton) && stateTime > 0.5f) { + } + + if ((Gdx.input.isKeyPressed(Keys.F) || followButton) && stateTime > 0.5f) { stateTime = 0; state = FOLLOW; return; - } - + } + boolean touch0 = Gdx.input.isTouched(0); boolean touch1 = Gdx.input.isTouched(1); boolean left = (touch0 && x0 < 60) || (touch1 && x1 < 60); boolean right = (touch0 && (x0 > 80 && x0 < 128)) || (touch1 && (x1 > 80 && x1 < 128)); boolean down = (touch0 && (y0 < 60)) || (touch1 && (y1 < 60)); - boolean up = (touch0 && (y0 > 80 && x0 < 128)) || (touch1 && (y1 > 80 && y1 < 128)); - - if(state == CONTROLLED) { - if (Gdx.input.isKeyPressed(Keys.A)) { + boolean up = (touch0 && (y0 > 80 && x0 < 128)) || (touch1 && (y1 > 80 && y1 < 128)); + + if (state == CONTROLLED) { + if (Gdx.input.isKeyPressed(Keys.A)) { accel.x = -ACCELERATION; - } else if (Gdx.input.isKeyPressed(Keys.D) || right ) { + } else if (Gdx.input.isKeyPressed(Keys.D) || right) { accel.x = ACCELERATION; - } else { + } else { accel.x = 0; } - - if (Gdx.input.isKeyPressed(Keys.W) || up) { + + if (Gdx.input.isKeyPressed(Keys.W) || up) { accel.y = ACCELERATION; - } else if (Gdx.input.isKeyPressed(Keys.S) || down) { + } else if (Gdx.input.isKeyPressed(Keys.S) || down) { accel.y = -ACCELERATION; - } else { + } else { accel.y = 0; } - - if(touch0) { - if(dpadRect.contains(x0, y0)) { + + if (touch0) { + if (dpadRect.contains(x0, y0)) { float x = (x0 - 64) / 64; float y = (y0 - 64) / 64; - float len = (float)Math.sqrt(x*x + y*y); - if(len != 0) { + float len = (float)Math.sqrt(x * x + y * y); + if (len != 0) { x /= len; y /= len; } else { @@ -152,40 +151,44 @@ private void processKeys () { accel.x = 0; accel.y = 0; } - } + } } } - - Rectangle[] r = { new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle() }; - private void tryMove () { + Rectangle[] r = {new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle()}; + + private void tryMove () { bounds.x += vel.x; fetchCollidableRects(); - for(int i = 0; i < r.length; i++) { + for (int i = 0; i < r.length; i++) { Rectangle rect = r[i]; - if(bounds.overlaps(rect)) { - if(vel.x < 0) bounds.x = rect.x + rect.width + 0.01f; - else bounds.x = rect.x - bounds.width - 0.01f; + if (bounds.overlaps(rect)) { + if (vel.x < 0) + bounds.x = rect.x + rect.width + 0.01f; + else + bounds.x = rect.x - bounds.width - 0.01f; vel.x = 0; } - } - - bounds.y += vel.y; + } + + bounds.y += vel.y; fetchCollidableRects(); - for(int i = 0; i < r.length; i++) { + for (int i = 0; i < r.length; i++) { Rectangle rect = r[i]; - if(bounds.overlaps(rect)) { - if(vel.y < 0) { bounds.y = rect.y + rect.height + 0.01f; } - else bounds.y = rect.y - bounds.height - 0.01f; + if (bounds.overlaps(rect)) { + if (vel.y < 0) { + bounds.y = rect.y + rect.height + 0.01f; + } else + bounds.y = rect.y - bounds.height - 0.01f; vel.y = 0; } - } - + } + pos.x = bounds.x - 0.2f; - pos.y = bounds.y - 0.2f; + pos.y = bounds.y - 0.2f; } - - private void fetchCollidableRects() { + + private void fetchCollidableRects () { int p1x = (int)bounds.x; int p1y = (int)Math.floor(bounds.y); int p2x = (int)(bounds.x + bounds.width); @@ -218,9 +221,9 @@ private void fetchCollidableRects() { else r[3].set(-1, -1, 0, 0); } - - public void setControlled() { - if(state == FOLLOW) { + + public void setControlled () { + if (state == FOLLOW) { state = CONTROLLED; stateTime = 0; } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cubocy.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cubocy.java index bbb06953b47..d2245f3c823 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cubocy.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Cubocy.java @@ -1,17 +1,17 @@ + package com.badlogic.cubocy; import com.badlogic.cubocy.screens.GameScreen; import com.badlogic.gdx.Game; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; -import com.badlogic.gdx.input.RemoteInput; -public class Cubocy extends Game { - public static void main(String[] argv) { +public class Cubocy extends Game { + public static void main (String[] argv) { new LwjglApplication(new Cubocy(), "Cubocy", 480, 320, false); } - @Override public void create () { + @Override + public void create () { setScreen(new GameScreen(this)); } } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Dispenser.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Dispenser.java index adad814ffa5..0e9e14801f0 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Dispenser.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Dispenser.java @@ -1,12 +1,13 @@ + package com.badlogic.cubocy; import com.badlogic.gdx.math.Rectangle; -public class Dispenser { +public class Dispenser { Rectangle bounds = new Rectangle(); boolean active = false; - - public Dispenser(float x, float y) { + + public Dispenser (float x, float y) { bounds.x = x; bounds.y = y; bounds.width = bounds.height = 1; diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/EndDoor.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/EndDoor.java index edd21365238..0c11a77af0a 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/EndDoor.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/EndDoor.java @@ -1,11 +1,12 @@ + package com.badlogic.cubocy; import com.badlogic.gdx.math.Rectangle; public class EndDoor { public Rectangle bounds = new Rectangle(); - - public EndDoor(float x, float y) { + + public EndDoor (float x, float y) { this.bounds.x = x; this.bounds.y = y; this.bounds.width = this.bounds.height = 1; diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Laser.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Laser.java index 90807c37bb6..b54fb491bd7 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Laser.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Laser.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy; import com.badlogic.gdx.math.Rectangle; @@ -8,143 +9,144 @@ public class Laser { static final int BACKWARD = -1; static final float FORWARD_VEL = 10; static final float BACKWARD_VEL = 4; - + int state = FORWARD; - - Map map; + + Map map; Vector2 pos = new Vector2(); Vector2 endPoint = new Vector2(); Vector2 cappedEndPoint = new Vector2(); - float angle = 0; - - public Laser(Map map, float x, float y) { + float angle = 0; + + public Laser (Map map, float x, float y) { this.map = map; pos.x = x; pos.y = y; } - - public void init() { + + public void init () { int ix = (int)pos.x; int iy = map.tiles[0].length - 1 - (int)pos.y; - - int left = map.tiles[ix-1][iy]; - int right = map.tiles[ix+1][iy]; + + int left = map.tiles[ix - 1][iy]; + int right = map.tiles[ix + 1][iy]; int top = map.tiles[ix][iy - 1]; int bottom = map.tiles[ix][iy + 1]; - - if(left == Map.TILE) { + + if (left == Map.TILE) { angle = -90; - for(int x = ix; x < map.tiles.length; x++) { - if(map.tiles[x][iy] == Map.TILE) { + for (int x = ix; x < map.tiles.length; x++) { + if (map.tiles[x][iy] == Map.TILE) { endPoint.set(x, pos.y); break; } } } - if(right == Map.TILE) { + if (right == Map.TILE) { angle = 90; - for(int x = ix; x >= 0; x--) { - if(map.tiles[x][iy] == Map.TILE) { + for (int x = ix; x >= 0; x--) { + if (map.tiles[x][iy] == Map.TILE) { endPoint.set(x, pos.y); break; } } } - if(top == Map.TILE) { + if (top == Map.TILE) { angle = 180; - for(int y = iy; y < map.tiles[0].length; y++) { - if(map.tiles[ix][y] == Map.TILE) { + for (int y = iy; y < map.tiles[0].length; y++) { + if (map.tiles[ix][y] == Map.TILE) { endPoint.set(pos.x, map.tiles[0].length - y - 1); break; } } } - if(bottom == Map.TILE) { + if (bottom == Map.TILE) { angle = 0; - for(int y = iy; y >= 0; y--) { - if(map.tiles[ix][y] == Map.TILE) { + for (int y = iy; y >= 0; y--) { + if (map.tiles[ix][y] == Map.TILE) { endPoint.set(pos.x, map.tiles[0].length - y - 1); break; } } } - } - + } + Vector2 startPoint = new Vector2(); - public void update() { + + public void update () { startPoint.set(pos).add(0.5f, 0.5f); cappedEndPoint.set(endPoint).add(0.5f, 0.5f); - + Rectangle cbounds = map.cube.bounds; Rectangle bbounds = map.bob.bounds; - + boolean kill = false; - - if(angle == -90) { - if(startPoint.x < cbounds.x && endPoint.x > cbounds.x) { - if(cbounds.y < startPoint.y && cbounds.y + cbounds.height > startPoint.y) { + + if (angle == -90) { + if (startPoint.x < cbounds.x && endPoint.x > cbounds.x) { + if (cbounds.y < startPoint.y && cbounds.y + cbounds.height > startPoint.y) { cappedEndPoint.x = cbounds.x; - } + } } } - if(angle == 90) { - if(startPoint.x > cbounds.x && endPoint.x < cbounds.x) { - if(cbounds.y < startPoint.y && cbounds.y + cbounds.height > startPoint.y) { + if (angle == 90) { + if (startPoint.x > cbounds.x && endPoint.x < cbounds.x) { + if (cbounds.y < startPoint.y && cbounds.y + cbounds.height > startPoint.y) { cappedEndPoint.x = cbounds.x + cbounds.width; - } + } } } - - if(angle == 0) { - if(startPoint.y < cbounds.y && endPoint.y > cbounds.y) { - if(cbounds.x < startPoint.x && cbounds.x + cbounds.width > startPoint.x) { + + if (angle == 0) { + if (startPoint.y < cbounds.y && endPoint.y > cbounds.y) { + if (cbounds.x < startPoint.x && cbounds.x + cbounds.width > startPoint.x) { cappedEndPoint.y = cbounds.y; } } } - - if(angle == 180) { - if(startPoint.y > cbounds.y && endPoint.y < cbounds.y ) { - if(cbounds.x < startPoint.x && cbounds.x + cbounds.width > startPoint.x) { + + if (angle == 180) { + if (startPoint.y > cbounds.y && endPoint.y < cbounds.y) { + if (cbounds.x < startPoint.x && cbounds.x + cbounds.width > startPoint.x) { cappedEndPoint.y = cbounds.y + cbounds.height; - } + } } } - - if(angle == -90) { - if(startPoint.x < bbounds.x) { - if(bbounds.y < startPoint.y && bbounds.y + bbounds.height > startPoint.y) { - if(cappedEndPoint.x > bbounds.x) kill = true; - } + + if (angle == -90) { + if (startPoint.x < bbounds.x) { + if (bbounds.y < startPoint.y && bbounds.y + bbounds.height > startPoint.y) { + if (cappedEndPoint.x > bbounds.x) kill = true; + } } } - if(angle == 90) { - if(startPoint.x > bbounds.x) { - if(bbounds.y < startPoint.y && bbounds.y + bbounds.height > startPoint.y) { - if(cappedEndPoint.x < bbounds.x + bbounds.width) kill = true; - } + if (angle == 90) { + if (startPoint.x > bbounds.x) { + if (bbounds.y < startPoint.y && bbounds.y + bbounds.height > startPoint.y) { + if (cappedEndPoint.x < bbounds.x + bbounds.width) kill = true; + } } } - - if(angle == 0) { - if(pos.y < bbounds.y) { - if(bbounds.x < startPoint.x && bbounds.x + bbounds.width > startPoint.x) { - if(cappedEndPoint.y > bbounds.y) kill = true; + + if (angle == 0) { + if (pos.y < bbounds.y) { + if (bbounds.x < startPoint.x && bbounds.x + bbounds.width > startPoint.x) { + if (cappedEndPoint.y > bbounds.y) kill = true; } } } - - if(angle == 180) { - if(pos.y > bbounds.y) { - if(bbounds.x < startPoint.x && bbounds.x + bbounds.width > startPoint.x) { - if(cappedEndPoint.y < bbounds.y + bbounds.height) kill = true; - } + + if (angle == 180) { + if (pos.y > bbounds.y) { + if (bbounds.x < startPoint.x && bbounds.x + bbounds.width > startPoint.x) { + if (cappedEndPoint.y < bbounds.y + bbounds.height) kill = true; + } } } - - if(kill && map.bob.state != Bob.DYING) { + + if (kill && map.bob.state != Bob.DYING) { map.bob.state = Bob.DYING; map.bob.stateTime = 0; } - } + } } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Map.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Map.java index ff82b0a261f..f00e956d595 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Map.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Map.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy; import com.badlogic.gdx.Gdx; @@ -14,8 +15,8 @@ public class Map { static int ROCKET = 0x0000ff; static int MOVING_SPIKES = 0xffff00; static int LASER = 0x00ffff; - - int[][] tiles; + + int[][] tiles; public Bob bob; Cube cube; Array dispensers = new Array(); @@ -24,14 +25,14 @@ public class Map { Array movingSpikes = new Array(); Array lasers = new Array(); public EndDoor endDoor; - - public Map() { + + public Map () { Pixmap pixmap = new Pixmap(Gdx.files.internal("data/levels.png")); - tiles = new int[pixmap.getWidth()][pixmap.getHeight()]; - for(int y = 0; y < pixmap.getHeight(); y++) { - for(int x = 0; x < pixmap.getWidth(); x++) { + tiles = new int[pixmap.getWidth()][pixmap.getHeight()]; + for (int y = 0; y < pixmap.getHeight(); y++) { + for (int x = 0; x < pixmap.getWidth(); x++) { int pix = pixmap.getPixel(x, y) >>> 8; - if(pix == START) { + if (pix == START) { Dispenser dispenser = new Dispenser(x, pixmap.getHeight() - 1 - y); dispensers.add(dispenser); activeDispenser = dispenser; @@ -39,61 +40,56 @@ public Map() { bob.state = Bob.SPAWN; cube = new Cube(this, activeDispenser.bounds.x, activeDispenser.bounds.y); cube.state = Cube.DEAD; - } else - if(pix == DISPENSER) { + } else if (pix == DISPENSER) { Dispenser dispenser = new Dispenser(x, pixmap.getHeight() - 1 - y); - dispensers.add(dispenser); - } else - if(pix == ROCKET) { + dispensers.add(dispenser); + } else if (pix == ROCKET) { Rocket rocket = new Rocket(this, x, pixmap.getHeight() - 1 - y); rockets.add(rocket); - } else - if(pix == MOVING_SPIKES) { - movingSpikes.add(new MovingSpikes(this, x, pixmap.getHeight() - 1 - y)); - } else - if(pix == LASER) { + } else if (pix == MOVING_SPIKES) { + movingSpikes.add(new MovingSpikes(this, x, pixmap.getHeight() - 1 - y)); + } else if (pix == LASER) { lasers.add(new Laser(this, x, pixmap.getHeight() - 1 - y)); - } else - if(pix == END) { + } else if (pix == END) { endDoor = new EndDoor(x, pixmap.getHeight() - 1 - y); } else { tiles[x][y] = pix; } } - } - - for(int i = 0; i < movingSpikes.size; i++) { + } + + for (int i = 0; i < movingSpikes.size; i++) { movingSpikes.get(i).init(); } - for(int i = 0; i < lasers.size; i++) { + for (int i = 0; i < lasers.size; i++) { lasers.get(i).init(); } } - - public void update(float deltaTime) { + + public void update (float deltaTime) { bob.update(deltaTime); - if(bob.state == Bob.DEAD) bob = new Bob(this, activeDispenser.bounds.x, activeDispenser.bounds.y); + if (bob.state == Bob.DEAD) bob = new Bob(this, activeDispenser.bounds.x, activeDispenser.bounds.y); cube.update(deltaTime); - if(cube.state == Cube.DEAD) cube = new Cube(this, bob.bounds.x, bob.bounds.y); - for(int i = 0; i < dispensers.size; i++) { - if(bob.bounds.overlaps(dispensers.get(i).bounds)) { + if (cube.state == Cube.DEAD) cube = new Cube(this, bob.bounds.x, bob.bounds.y); + for (int i = 0; i < dispensers.size; i++) { + if (bob.bounds.overlaps(dispensers.get(i).bounds)) { activeDispenser = dispensers.get(i); } } - for(int i = 0; i < rockets.size; i++) { + for (int i = 0; i < rockets.size; i++) { Rocket rocket = rockets.get(i); rocket.update(deltaTime); } - for(int i = 0; i < movingSpikes.size; i++) { + for (int i = 0; i < movingSpikes.size; i++) { MovingSpikes spikes = movingSpikes.get(i); spikes.update(deltaTime); } - for(int i = 0; i < lasers.size; i++) { + for (int i = 0; i < lasers.size; i++) { lasers.get(i).update(); } - } - - public boolean isDeadly(int tileId) { - return tileId == SPIKES; + } + + public boolean isDeadly (int tileId) { + return tileId == SPIKES; } } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/MapRenderer.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/MapRenderer.java index 48a6a782a17..055d6b26958 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/MapRenderer.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/MapRenderer.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy; import com.badlogic.gdx.Gdx; @@ -12,21 +13,21 @@ import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer10; import com.badlogic.gdx.math.Vector3; -public class MapRenderer { +public class MapRenderer { Map map; - OrthographicCamera cam; + OrthographicCamera cam; SpriteCache cache; SpriteBatch batch = new SpriteBatch(10000); - ImmediateModeRenderer10 renderer = new ImmediateModeRenderer10(2000*2); + ImmediateModeRenderer10 renderer = new ImmediateModeRenderer10(2000 * 2); int[][] blocks; - TextureRegion tile; + TextureRegion tile; Animation bobLeft; Animation bobRight; Animation bobJumpLeft; Animation bobJumpRight; Animation bobIdleLeft; Animation bobIdleRight; - Animation bobDead; + Animation bobDead; Animation zap; TextureRegion cube; Animation cubeFixed; @@ -42,47 +43,47 @@ public class MapRenderer { TextureRegion movingSpikes; TextureRegion laser; FPSLogger fps = new FPSLogger(); - - public MapRenderer(Map map) { + + public MapRenderer (Map map) { this.map = map; this.cam = new OrthographicCamera(24, 16); this.cam.position.set(map.bob.pos.x, map.bob.pos.y, 0); this.cache = new SpriteCache(this.map.tiles.length * this.map.tiles[0].length, false); - this.blocks = new int[(int)Math.ceil(this.map.tiles.length / 24.0f)] - [(int)Math.ceil(this.map.tiles[0].length / 16.0f)]; - - createAnimations(); - createBlocks(); + this.blocks = new int[(int)Math.ceil(this.map.tiles.length / 24.0f)][(int)Math.ceil(this.map.tiles[0].length / 16.0f)]; + + createAnimations(); + createBlocks(); } - - private void createBlocks() { + + private void createBlocks () { int width = map.tiles.length; int height = map.tiles[0].length; - for(int blockY = 0; blockY < blocks[0].length; blockY++) { - for(int blockX = 0; blockX < blocks.length; blockX++) { + for (int blockY = 0; blockY < blocks[0].length; blockY++) { + for (int blockX = 0; blockX < blocks.length; blockX++) { cache.beginCache(); - for(int y = blockY * 16; y < blockY * 16 + 16; y++) { - for(int x = blockX * 24; x < blockX * 24 + 24; x++) { - if(x > width) continue; - if(y > height) continue; + for (int y = blockY * 16; y < blockY * 16 + 16; y++) { + for (int x = blockX * 24; x < blockX * 24 + 24; x++) { + if (x > width) continue; + if (y > height) continue; int posX = x; int posY = height - y - 1; - if(map.tiles[x][y] == Map.TILE) cache.add(tile, posX, posY, 1, 1); - if(map.tiles[x][y] == Map.SPIKES) cache.add(spikes, posX, posY, 1, 1); + if (map.tiles[x][y] == Map.TILE) cache.add(tile, posX, posY, 1, 1); + if (map.tiles[x][y] == Map.SPIKES) cache.add(spikes, posX, posY, 1, 1); } } - blocks[blockX][blockY] = cache.endCache(); - } + blocks[blockX][blockY] = cache.endCache(); + } } System.out.println("blocks created"); } - - private void createAnimations() { + + private void createAnimations () { this.tile = new TextureRegion(new Texture(Gdx.files.internal("data/tile.png")), 0, 0, 20, 20); Texture bobTexture = new Texture(Gdx.files.internal("data/bob.png")); TextureRegion[] split = new TextureRegion(bobTexture).split(20, 20)[0]; - TextureRegion[] mirror = new TextureRegion(bobTexture).split(20,20)[0]; - for(TextureRegion region: mirror) region.flip(true, false); + TextureRegion[] mirror = new TextureRegion(bobTexture).split(20, 20)[0]; + for (TextureRegion region : mirror) + region.flip(true, false); spikes = split[5]; bobRight = new Animation(0.1f, split[0], split[1]); bobLeft = new Animation(0.1f, mirror[0], mirror[1]); @@ -104,29 +105,30 @@ private void createAnimations() { rocketPad = split[4]; split = new TextureRegion(bobTexture).split(20, 20)[4]; rocketExplosion = new Animation(0.1f, split[0], split[1], split[2], split[3], split[4], split[4]); - split = new TextureRegion(bobTexture).split(20,20)[5]; + split = new TextureRegion(bobTexture).split(20, 20)[5]; endDoor = split[2]; movingSpikes = split[0]; laser = split[1]; } - + float stateTime = 0; Vector3 lerpTarget = new Vector3(); - public void render(float deltaTime) { - if(map.cube.state != Cube.CONTROLLED) + + public void render (float deltaTime) { + if (map.cube.state != Cube.CONTROLLED) cam.position.lerp(lerpTarget.set(map.bob.pos.x, map.bob.pos.y, 0), 2f * deltaTime); else cam.position.lerp(lerpTarget.set(map.cube.pos.x, map.cube.pos.y, 0), 2f * deltaTime); - cam.update(); - + cam.update(); + renderLaserBeams(); - + cache.setProjectionMatrix(cam.combined); Gdx.gl.glDisable(GL10.GL_BLEND); - cache.begin(); + cache.begin(); int b = 0; - for(int blockY = 0; blockY < 4; blockY++) { - for(int blockX = 0; blockX < 6; blockX++) { + for (int blockY = 0; blockY < 4; blockY++) { + for (int blockX = 0; blockX < 6; blockX++) { cache.draw(blocks[blockX][blockY]); b++; } @@ -137,86 +139,96 @@ public void render(float deltaTime) { batch.setProjectionMatrix(cam.combined); batch.begin(); renderDispensers(); - if(map.endDoor != null) batch.draw(endDoor, map.endDoor.bounds.x, map.endDoor.bounds.y, 1, 1); + if (map.endDoor != null) batch.draw(endDoor, map.endDoor.bounds.x, map.endDoor.bounds.y, 1, 1); renderLasers(); renderMovingSpikes(); renderBob(); - renderCube(); + renderCube(); renderRockets(); batch.end(); - renderLaserBeams(); - + renderLaserBeams(); + fps.log(); - } + } - private void renderBob() { + private void renderBob () { Animation anim = null; boolean loop = true; - if(map.bob.state == Bob.RUN) { - if(map.bob.dir == Bob.LEFT) anim = bobLeft; else anim = bobRight; - } - if(map.bob.state == Bob.IDLE) { - if(map.bob.dir == Bob.LEFT) anim = bobIdleLeft; else anim = bobIdleRight; - } - if(map.bob.state == Bob.JUMP) { - if(map.bob.dir == Bob.LEFT) anim = bobJumpLeft; else anim = bobJumpRight; - } - if(map.bob.state == Bob.SPAWN) { + if (map.bob.state == Bob.RUN) { + if (map.bob.dir == Bob.LEFT) + anim = bobLeft; + else + anim = bobRight; + } + if (map.bob.state == Bob.IDLE) { + if (map.bob.dir == Bob.LEFT) + anim = bobIdleLeft; + else + anim = bobIdleRight; + } + if (map.bob.state == Bob.JUMP) { + if (map.bob.dir == Bob.LEFT) + anim = bobJumpLeft; + else + anim = bobJumpRight; + } + if (map.bob.state == Bob.SPAWN) { anim = spawn; loop = false; } - if(map.bob.state == Bob.DYING) { + if (map.bob.state == Bob.DYING) { anim = dying; loop = false; } batch.draw(anim.getKeyFrame(map.bob.stateTime, loop), map.bob.pos.x, map.bob.pos.y, 1, 1); } - - private void renderCube() { - if(map.cube.state == Cube.FOLLOW) batch.draw(cube, map.cube.pos.x, map.cube.pos.y, 1.5f, 1.5f); - if(map.cube.state == Cube.FIXED) batch.draw(cubeFixed.getKeyFrame(map.cube.stateTime, false), map.cube.pos.x, map.cube.pos.y, 1.5f, 1.5f); - if(map.cube.state == Cube.CONTROLLED) batch.draw(cubeControlled, map.cube.pos.x, map.cube.pos.y, 1.5f, 1.5f); + + private void renderCube () { + if (map.cube.state == Cube.FOLLOW) batch.draw(cube, map.cube.pos.x, map.cube.pos.y, 1.5f, 1.5f); + if (map.cube.state == Cube.FIXED) + batch.draw(cubeFixed.getKeyFrame(map.cube.stateTime, false), map.cube.pos.x, map.cube.pos.y, 1.5f, 1.5f); + if (map.cube.state == Cube.CONTROLLED) batch.draw(cubeControlled, map.cube.pos.x, map.cube.pos.y, 1.5f, 1.5f); } - - private void renderRockets() { - for(int i = 0; i < map.rockets.size; i++) { + + private void renderRockets () { + for (int i = 0; i < map.rockets.size; i++) { Rocket rocket = map.rockets.get(i); - if(rocket.state == Rocket.FLYING) { - TextureRegion frame = this.rocket.getKeyFrame(rocket.stateTime, true); + if (rocket.state == Rocket.FLYING) { + TextureRegion frame = this.rocket.getKeyFrame(rocket.stateTime, true); batch.draw(frame, rocket.pos.x, rocket.pos.y, 0.5f, 0.5f, 1, 1, 1, 1, rocket.vel.angle()); } else { TextureRegion frame = this.rocketExplosion.getKeyFrame(rocket.stateTime, false); batch.draw(frame, rocket.pos.x, rocket.pos.y, 1, 1); } batch.draw(rocketPad, rocket.startPos.x, rocket.startPos.y, 1, 1); - } + } } - - private void renderDispensers() { - for(int i = 0; i < map.dispensers.size; i++) { + + private void renderDispensers () { + for (int i = 0; i < map.dispensers.size; i++) { Dispenser dispenser = map.dispensers.get(i); batch.draw(this.dispenser, dispenser.bounds.x, dispenser.bounds.y, 1, 1); - } + } } - - private void renderMovingSpikes() { - for(int i = 0; i < map.movingSpikes.size; i++) { + + private void renderMovingSpikes () { + for (int i = 0; i < map.movingSpikes.size; i++) { MovingSpikes spikes = map.movingSpikes.get(i); batch.draw(movingSpikes, spikes.pos.x, spikes.pos.y, 0.5f, 0.5f, 1, 1, 1, 1, spikes.angle); } } - - private void renderLasers() { - for(int i = 0; i < map.lasers.size; i++) { + + private void renderLasers () { + for (int i = 0; i < map.lasers.size; i++) { Laser laser = map.lasers.get(i); batch.draw(this.laser, laser.pos.x, laser.pos.y, 0.5f, 0.5f, 1, 1, 1, 1, laser.angle); } } - + private void renderLaserBeams () { cam.apply(Gdx.gl10); renderer.begin(GL10.GL_LINES); - for(int i = 0; i < map.lasers.size; i++) { + for (int i = 0; i < map.lasers.size; i++) { Laser laser = map.lasers.get(i); float sx = laser.startPoint.x, sy = laser.startPoint.y; float ex = laser.cappedEndPoint.x, ey = laser.cappedEndPoint.y; @@ -234,4 +246,4 @@ public void dispose () { tile.getTexture().dispose(); cube.getTexture().dispose(); } -} \ No newline at end of file +} diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/MovingSpikes.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/MovingSpikes.java index 6c2511798ed..9e391c0ea86 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/MovingSpikes.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/MovingSpikes.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy; import com.badlogic.gdx.math.Rectangle; @@ -8,9 +9,9 @@ public class MovingSpikes { static final int BACKWARD = -1; static final float FORWARD_VEL = 10; static final float BACKWARD_VEL = 4; - + int state = FORWARD; - + Map map; Rectangle bounds = new Rectangle(); Vector2 vel = new Vector2(); @@ -20,60 +21,75 @@ public class MovingSpikes { int fy = 0; int bx = 0; int by = 0; - - - public MovingSpikes(Map map, float x, float y) { + + public MovingSpikes (Map map, float x, float y) { this.map = map; pos.x = x; pos.y = y; bounds.x = x; bounds.y = y; - bounds.width = bounds.height = 1; + bounds.width = bounds.height = 1; } - - public void init() { + + public void init () { int ix = (int)pos.x; int iy = (int)pos.y; - - int left = map.tiles[ix-1][map.tiles[0].length - 1 - iy]; - int right = map.tiles[ix+1][map.tiles[0].length - 1 - iy]; + + int left = map.tiles[ix - 1][map.tiles[0].length - 1 - iy]; + int right = map.tiles[ix + 1][map.tiles[0].length - 1 - iy]; int top = map.tiles[ix][map.tiles[0].length - 1 - iy - 1]; int bottom = map.tiles[ix][map.tiles[0].length - 1 - iy + 1]; - - if(left == Map.TILE) { vel.x = FORWARD_VEL; angle = -90; fx = 1; } - if(right == Map.TILE) { vel.x = -FORWARD_VEL; angle = 90; bx = 1; } - if(top == Map.TILE) { vel.y = -FORWARD_VEL; angle = 180; by = -1;} - if(bottom == Map.TILE) { vel.y = FORWARD_VEL; angle = 0; fy = -1; } + + if (left == Map.TILE) { + vel.x = FORWARD_VEL; + angle = -90; + fx = 1; + } + if (right == Map.TILE) { + vel.x = -FORWARD_VEL; + angle = 90; + bx = 1; + } + if (top == Map.TILE) { + vel.y = -FORWARD_VEL; + angle = 180; + by = -1; + } + if (bottom == Map.TILE) { + vel.y = FORWARD_VEL; + angle = 0; + fy = -1; + } } - - public void update(float deltaTime) { + + public void update (float deltaTime) { pos.add(vel.x * deltaTime, vel.y * deltaTime); boolean change = false; - if(state == FORWARD) { + if (state == FORWARD) { change = map.tiles[(int)pos.x + fx][map.tiles[0].length - 1 - (int)pos.y + fy] == Map.TILE; } else { change = map.tiles[(int)pos.x + bx][map.tiles[0].length - 1 - (int)pos.y + by] == Map.TILE; } - if(change) { + if (change) { pos.x -= vel.x * deltaTime; pos.y -= vel.y * deltaTime; state = -state; vel.mul(-1); - if(state == FORWARD) vel.nor().mul(FORWARD_VEL); - if(state == BACKWARD) vel.nor().mul(BACKWARD_VEL); + if (state == FORWARD) vel.nor().mul(FORWARD_VEL); + if (state == BACKWARD) vel.nor().mul(BACKWARD_VEL); } - - bounds.x = pos.x; + + bounds.x = pos.x; bounds.y = pos.y; - - if(map.bob.bounds.overlaps(bounds)) { - if(map.bob.state != Bob.DYING) { + + if (map.bob.bounds.overlaps(bounds)) { + if (map.bob.state != Bob.DYING) { map.bob.state = Bob.DYING; map.bob.stateTime = 0; } } - - if(map.cube.bounds.overlaps(bounds)) { + + if (map.cube.bounds.overlaps(bounds)) { map.cube.state = Cube.DEAD; map.cube.stateTime = 0; } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/OnscreenControlRenderer.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/OnscreenControlRenderer.java index d99269f1b90..50fd84a022a 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/OnscreenControlRenderer.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/OnscreenControlRenderer.java @@ -1,7 +1,8 @@ + package com.badlogic.cubocy; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Application.ApplicationType; +import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; @@ -15,45 +16,45 @@ public class OnscreenControlRenderer { TextureRegion jump; TextureRegion cubeControl; TextureRegion cubeFollow; - - public OnscreenControlRenderer(Map map) { + + public OnscreenControlRenderer (Map map) { this.map = map; loadAssets(); } - - private void loadAssets() { + + private void loadAssets () { Texture texture = new Texture(Gdx.files.internal("data/controls.png")); TextureRegion[] buttons = TextureRegion.split(texture, 64, 64)[0]; left = buttons[0]; right = buttons[1]; jump = buttons[2]; cubeControl = buttons[3]; - cubeFollow = TextureRegion.split(texture, 64, 64)[1][2]; - dpad = new TextureRegion(texture, 0, 64, 128, 128); + cubeFollow = TextureRegion.split(texture, 64, 64)[1][2]; + dpad = new TextureRegion(texture, 0, 64, 128, 128); batch = new SpriteBatch(); batch.getProjectionMatrix().setToOrtho2D(0, 0, 480, 320); } - - public void render() { - if(Gdx.app.getType() != ApplicationType.Android) return; - if(map.cube.state != Cube.CONTROLLED) { + + public void render () { + if (Gdx.app.getType() != ApplicationType.Android) return; + if (map.cube.state != Cube.CONTROLLED) { batch.begin(); batch.draw(left, 0, 0); - batch.draw(right, 70, 0); - batch.draw(cubeControl, 480-64, 320-64); - batch.draw(cubeFollow, 480-64, 320-138); - batch.draw(jump, 480-64, 0); + batch.draw(right, 70, 0); + batch.draw(cubeControl, 480 - 64, 320 - 64); + batch.draw(cubeFollow, 480 - 64, 320 - 138); + batch.draw(jump, 480 - 64, 0); batch.end(); - } else { + } else { batch.begin(); batch.draw(dpad, 0, 0); - batch.draw(cubeFollow, 480-64, 320-138); - batch.draw(cubeControl, 480-64, 320-64); + batch.draw(cubeFollow, 480 - 64, 320 - 138); + batch.draw(cubeControl, 480 - 64, 320 - 64); batch.end(); } } - - public void dispose() { + + public void dispose () { dpad.getTexture().dispose(); batch.dispose(); } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Rocket.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Rocket.java index d883455a929..e9fee5f2210 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/Rocket.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/Rocket.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy; import com.badlogic.gdx.math.Rectangle; @@ -8,7 +9,7 @@ public class Rocket { static final int EXPLODING = 1; static final int DEAD = 2; static final float VELOCITY = 6; - + Map map; float stateTime = 0; int state = FLYING; @@ -16,8 +17,8 @@ public class Rocket { Vector2 pos = new Vector2(); Vector2 vel = new Vector2(); Rectangle bounds = new Rectangle(); - - public Rocket(Map map, float x, float y) { + + public Rocket (Map map, float x, float y) { this.map = map; this.startPos.set(x, y); this.pos.set(x, y); @@ -27,61 +28,61 @@ public Rocket(Map map, float x, float y) { this.bounds.height = 0.6f; this.vel.set(-VELOCITY, 0); } - - public void update(float deltaTime) { - if(state == FLYING) { -// if(pos.dst(map.bob.pos) < pos.dst(map.cube.pos)) vel.set(map.bob.pos); -// else vel.set(map.cube.pos); + + public void update (float deltaTime) { + if (state == FLYING) { +// if(pos.dst(map.bob.pos) < pos.dst(map.cube.pos)) vel.set(map.bob.pos); +// else vel.set(map.cube.pos); vel.set(map.bob.pos); vel.sub(pos).nor().mul(VELOCITY); pos.add(vel.x * deltaTime, vel.y * deltaTime); bounds.x = pos.x + 0.2f; - bounds.y = pos.y + 0.2f; - if(checkHit()) { + bounds.y = pos.y + 0.2f; + if (checkHit()) { state = EXPLODING; stateTime = 0; } } - - if(state == EXPLODING) { - if(stateTime > 0.6f) { + + if (state == EXPLODING) { + if (stateTime > 0.6f) { state = FLYING; stateTime = 0; pos.set(startPos); bounds.x = pos.x + 0.2f; bounds.y = pos.y + 0.2f; } - } - + } + stateTime += deltaTime; - } - - Rectangle[] r = { new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle() }; + } + + Rectangle[] r = {new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle()}; - private boolean checkHit () { + private boolean checkHit () { fetchCollidableRects(); - for(int i = 0; i < r.length; i++) { - if(bounds.overlaps(r[i])) { + for (int i = 0; i < r.length; i++) { + if (bounds.overlaps(r[i])) { return true; - } + } } - - if(bounds.overlaps(map.bob.bounds)) { - if(map.bob.state != Bob.DYING) { + + if (bounds.overlaps(map.bob.bounds)) { + if (map.bob.state != Bob.DYING) { map.bob.state = Bob.DYING; map.bob.stateTime = 0; } return true; } - - if(bounds.overlaps(map.cube.bounds)) { + + if (bounds.overlaps(map.cube.bounds)) { return true; } - + return false; } - - private void fetchCollidableRects() { + + private void fetchCollidableRects () { int p1x = (int)bounds.x; int p1y = (int)Math.floor(bounds.y); int p2x = (int)(bounds.x + bounds.width); diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/CubocScreen.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/CubocScreen.java index e21820500cc..2093ab36f0b 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/CubocScreen.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/CubocScreen.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy.screens; import com.badlogic.gdx.Game; @@ -5,29 +6,32 @@ public abstract class CubocScreen implements Screen { Game game; - - public CubocScreen(Game game) { + + public CubocScreen (Game game) { this.game = game; } - - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { // TODO Auto-generated method stub - + } - @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 dispose () { + @Override + public void dispose () { // TODO Auto-generated method stub - + } } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameOverScreen.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameOverScreen.java index c832ea4ba07..ccb6a7732c6 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameOverScreen.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameOverScreen.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy.screens; import com.badlogic.gdx.Game; @@ -12,32 +13,35 @@ public class GameOverScreen extends CubocScreen { TextureRegion intro; SpriteBatch batch; float time = 0; - - public GameOverScreen(Game game) { + + public GameOverScreen (Game game) { super(game); } - @Override public void show () { + @Override + public void show () { intro = new TextureRegion(new Texture(Gdx.files.internal("data/gameover.png")), 0, 0, 480, 320); batch = new SpriteBatch(); batch.getProjectionMatrix().setToOrtho2D(0, 0, 480, 320); } - - @Override public void render (float delta) { + + @Override + public void render (float delta) { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(intro, 0, 0); batch.end(); - + time += delta; - if(time > 1) { - if(Gdx.input.isKeyPressed(Keys.ANY_KEY) || Gdx.input.justTouched()) { + if (time > 1) { + if (Gdx.input.isKeyPressed(Keys.ANY_KEY) || Gdx.input.justTouched()) { game.setScreen(new MainMenu(game)); } } } - @Override public void hide () { + @Override + public void hide () { System.out.println("dispose intro"); batch.dispose(); intro.getTexture().dispose(); diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameScreen.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameScreen.java index dc37a13f96d..05d87108688 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameScreen.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/GameScreen.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy.screens; import com.badlogic.cubocy.Map; @@ -12,37 +13,40 @@ public class GameScreen extends CubocScreen { Map map; MapRenderer renderer; OnscreenControlRenderer controlRenderer; - - public GameScreen(Game game) { + + public GameScreen (Game game) { super(game); } - - @Override public void show () { + + @Override + public void show () { map = new Map(); renderer = new MapRenderer(map); controlRenderer = new OnscreenControlRenderer(map); } - - @Override public void render (float delta) { + + @Override + public void render (float delta) { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); - map.update(delta); + map.update(delta); Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1); - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); renderer.render(delta); controlRenderer.render(); - - if(map.bob.bounds.overlaps(map.endDoor.bounds)) { + + if (map.bob.bounds.overlaps(map.endDoor.bounds)) { game.setScreen(new GameOverScreen(game)); } - - if(Gdx.input.isKeyPressed(Keys.ESCAPE)) { + + if (Gdx.input.isKeyPressed(Keys.ESCAPE)) { game.setScreen(new MainMenu(game)); } } - - @Override public void hide () { + + @Override + public void hide () { System.out.println("dispose game screen"); renderer.dispose(); controlRenderer.dispose(); - } + } } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/IntroScreen.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/IntroScreen.java index 75c3e199105..371d31f7875 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/IntroScreen.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/IntroScreen.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy.screens; import com.badlogic.gdx.Game; @@ -12,35 +13,38 @@ public class IntroScreen extends CubocScreen { TextureRegion intro; SpriteBatch batch; float time = 0; - - public IntroScreen(Game game) { + + public IntroScreen (Game game) { super(game); } - @Override public void show () { + @Override + public void show () { intro = new TextureRegion(new Texture(Gdx.files.internal("data/intro.png")), 0, 0, 480, 320); batch = new SpriteBatch(); batch.getProjectionMatrix().setToOrtho2D(0, 0, 480, 320); } - - @Override public void render (float delta) { + + @Override + public void render (float delta) { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(intro, 0, 0); batch.end(); - + time += delta; - if(time > 1) { - if(Gdx.input.isKeyPressed(Keys.ANY_KEY) || Gdx.input.justTouched()) { + if (time > 1) { + if (Gdx.input.isKeyPressed(Keys.ANY_KEY) || Gdx.input.justTouched()) { game.setScreen(new GameScreen(game)); } } } - @Override public void hide () { + @Override + public void hide () { System.out.println("dispose intro"); batch.dispose(); intro.getTexture().dispose(); } - + } diff --git a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/MainMenu.java b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/MainMenu.java index c3cefeacbf8..89edcce490b 100644 --- a/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/MainMenu.java +++ b/demos/cuboc/cuboc/src/com/badlogic/cubocy/screens/MainMenu.java @@ -1,3 +1,4 @@ + package com.badlogic.cubocy.screens; import com.badlogic.gdx.Game; @@ -12,32 +13,35 @@ public class MainMenu extends CubocScreen { TextureRegion title; SpriteBatch batch; float time = 0; - - public MainMenu(Game game) { + + public MainMenu (Game game) { super(game); } - - @Override public void show () { + + @Override + public void show () { title = new TextureRegion(new Texture(Gdx.files.internal("data/title.png")), 0, 0, 480, 320); batch = new SpriteBatch(); batch.getProjectionMatrix().setToOrtho2D(0, 0, 480, 320); } - - @Override public void render (float delta) { + + @Override + public void render (float delta) { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(title, 0, 0); batch.end(); - + time += delta; - if(time > 1) { - if(Gdx.input.isKeyPressed(Keys.ANY_KEY) || Gdx.input.justTouched()) { + if (time > 1) { + if (Gdx.input.isKeyPressed(Keys.ANY_KEY) || Gdx.input.justTouched()) { game.setScreen(new IntroScreen(game)); } } } - @Override public void hide () { + @Override + public void hide () { System.out.println("dispose main menu"); batch.dispose(); title.getTexture().dispose(); diff --git a/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/HelloWorldAndroid.java b/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/HelloWorldAndroid.java index 406701b9088..570ec566116 100644 --- a/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/HelloWorldAndroid.java +++ b/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/HelloWorldAndroid.java @@ -34,8 +34,9 @@ import com.badlogic.gdx.helloworld.HelloWorld; public class HelloWorldAndroid extends AndroidApplication { - @Override public void onCreate (Bundle savedInstanceState) { + @Override + public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); - initialize(new HelloWorld(), false); + initialize(new HelloWorld(), false); } } 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 849eed1d4bb..7624e3c8966 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.helloworld; import com.badlogic.gdx.ApplicationListener; @@ -22,7 +23,6 @@ import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; -import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; public class HelloWorld implements ApplicationListener { @@ -32,66 +32,70 @@ public class HelloWorld implements ApplicationListener { Vector2 textPosition = new Vector2(100, 100); Vector2 textDirection = new Vector2(1, 1); - @Override public void create () { + @Override + public void create () { font = new BitmapFont(); font.setColor(Color.RED); texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); - spriteBatch = new SpriteBatch(); + spriteBatch = new SpriteBatch(); } - @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); - + // more fun but confusing :) - //textPosition.add(textDirection.tmp().mul(Gdx.graphics.getDeltaTime()).mul(60)); + // textPosition.add(textDirection.tmp().mul(Gdx.graphics.getDeltaTime()).mul(60)); textPosition.x += textDirection.x * Gdx.graphics.getDeltaTime() * 60; textPosition.y += textDirection.y * Gdx.graphics.getDeltaTime() * 60; - if (textPosition.x < 0 ) { + if (textPosition.x < 0) { textDirection.x = -textDirection.x; textPosition.x = 0; } - if(textPosition.x > Gdx.graphics.getWidth()) { + if (textPosition.x > Gdx.graphics.getWidth()) { textDirection.x = -textDirection.x; textPosition.x = Gdx.graphics.getWidth(); } if (textPosition.y < 0) { textDirection.y = -textDirection.y; - textPosition.y = 0; + textPosition.y = 0; } if (textPosition.y > Gdx.graphics.getHeight()) { textDirection.y = -textDirection.y; - textPosition.y = Gdx.graphics.getHeight(); + textPosition.y = Gdx.graphics.getHeight(); } spriteBatch.begin(); spriteBatch.setColor(Color.WHITE); - spriteBatch.draw(texture, - centerX - texture.getWidth() / 2, - centerY - texture.getHeight() / 2, - 0, 0, texture.getWidth(), texture.getHeight()); + spriteBatch.draw(texture, centerX - texture.getWidth() / 2, centerY - texture.getHeight() / 2, 0, 0, texture.getWidth(), + texture.getHeight()); font.draw(spriteBatch, "Hello World!", (int)textPosition.x, (int)textPosition.y); spriteBatch.end(); } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { spriteBatch.getProjectionMatrix().setToOrtho2D(0, 0, width, height); textPosition.set(0, 0); } - @Override public void pause () { + @Override + public void pause () { } - @Override public void resume () { + @Override + public void resume () { } - - @Override public void dispose () { + + @Override + public void dispose () { } - + } 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 013c41bc830..ce2ede929f3 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.helloworld; import com.badlogic.gdx.backends.jogl.JoglApplication; 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 b5e06e4a858..0fec2d95809 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 @@ -9,11 +9,12 @@ public class GdxInvadersAndroid extends AndroidApplication { /** Called when the activity is first created. */ - @Override public void onCreate (Bundle savedInstanceState) { + @Override + public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); - config.useWakelock = true; - initialize(new GdxInvaders(),config); + config.useWakelock = true; + initialize(new GdxInvaders(), config); } } 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 ade6a19a9b9..ccf99ada77a 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvaders.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvaders.java @@ -15,8 +15,8 @@ import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationListener; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Files.FileType; +import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdxinvaders.screens.GameLoop; import com.badlogic.gdxinvaders.screens.GameOver; @@ -30,11 +30,13 @@ public class GdxInvaders implements ApplicationListener { /** 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 @@ -65,11 +67,13 @@ public class GdxInvaders implements ApplicationListener { } } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } - @Override public void create () { + @Override + public void create () { if (!isInitialized) { screen = new MainMenu(Gdx.app); Music music = Gdx.audio.newMusic(Gdx.files.getFileHandle("data/8.12.mp3", FileType.Internal)); @@ -80,13 +84,13 @@ public class GdxInvaders implements ApplicationListener { } @Override - public void pause() { + public void pause () { // TODO Auto-generated method stub - + } @Override - public void resume() { + public void resume () { // TODO Auto-generated method stub System.out.println("resume"); } 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 2344f37a26d..6d9f30e03f8 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvadersDesktop.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/GdxInvadersDesktop.java @@ -15,13 +15,10 @@ import com.badlogic.gdx.backends.jogl.JoglApplication; -/** - * Entry point for desktop version of Gdx Invaders. Constructs a JoglApplication and registers the renderer. - * @author mzechner - * - */ +/** 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) { - new JoglApplication(new GdxInvaders(),"Gdx Invaders", 800, 480, false); + new JoglApplication(new GdxInvaders(), "Gdx Invaders", 800, 480, false); } } 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 d396b09aa1a..d584e078cdb 100644 --- a/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/Renderer.java +++ b/demos/invaders/gdx-invaders/src/com/badlogic/gdxinvaders/Renderer.java @@ -23,8 +23,8 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; -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.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; @@ -40,11 +40,8 @@ import com.badlogic.gdxinvaders.simulation.Shot; import com.badlogic.gdxinvaders.simulation.Simulation; -/** - * The renderer receives a simulation and renders it. - * @author mzechner - * - */ +/** The renderer receives a simulation and renders it. + * @author mzechner */ public class Renderer { /** sprite batch to draw text **/ private SpriteBatch spriteBatch; @@ -105,7 +102,7 @@ public Renderer (Application app) { in.close(); shipTexture = new Texture(Gdx.files.internal("data/ship.png"), Format.RGB565, true); - shipTexture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); + shipTexture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); invaderTexture = new Texture(Gdx.files.internal("data/invader.png"), Format.RGB565, true); invaderTexture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); backgroundTexture = new Texture(Gdx.files.internal("data/planet.jpg"), Format.RGB565, true); @@ -113,8 +110,8 @@ public Renderer (Application app) { explosionTexture = new Texture(Gdx.files.internal("data/explode.png"), Format.RGBA4444, true); explosionTexture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); - explosionMesh = new Mesh(true, 4 * 16, 0, new VertexAttribute(Usage.Position, 3, "a_position"), - new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoord")); + explosionMesh = new Mesh(true, 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; @@ -149,7 +146,7 @@ public Renderer (Application app) { explosionMesh.setVertices(vertices); font = new BitmapFont(Gdx.files.internal("data/font10.fnt"), Gdx.files.internal("data/font10.png"), false); - camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } catch (Exception ex) { ex.printStackTrace(); } @@ -197,7 +194,7 @@ public void render (Application app, Simulation simulation) { } spriteBatch.enableBlending(); spriteBatch.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); - font.draw(spriteBatch, status, 0, 320); + font.draw(spriteBatch, status, 0, 320); spriteBatch.end(); invaderAngle += app.getGraphics().getDeltaTime() * 90; @@ -219,9 +216,9 @@ private void renderBackground (GL10 gl) { private void setProjectionAndCamera (Graphics graphics, Ship ship, Application app) { camera.position.set(ship.position.x, 6, 2); - camera.direction.set(ship.position.x, 0, -4).sub(camera.position).nor(); + camera.direction.set(ship.position.x, 0, -4).sub(camera.position).nor(); camera.update(); - camera.apply(Gdx.gl10); + camera.apply(Gdx.gl10); } float[] direction = {1, 0.5f, 0, 0}; 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 102d21c3156..517d5ee2a2e 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 @@ -41,22 +41,26 @@ public GameLoop (Application app) { 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) { + @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) { + @Override + public void update (Application app) { simulation.update(app.getGraphics().getDeltaTime()); Input input = app.getInput(); @@ -71,11 +75,13 @@ public GameLoop (Application app) { if (input.isTouched() || input.isKeyPressed(Keys.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 5e41cd41665..bc0afc5ad66 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 @@ -14,26 +14,21 @@ package com.badlogic.gdxinvaders.screens; import com.badlogic.gdx.Application; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; 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.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.graphics.g2d.SpriteBatch; 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 - * - */ + * @author mzechner */ public class GameOver implements Screen { /** the SpriteBatch used to draw the background, logo and text **/ private final SpriteBatch spriteBatch; @@ -60,18 +55,21 @@ public GameOver (Application app) { font = new BitmapFont(Gdx.files.internal("data/font16.fnt"), Gdx.files.internal("data/font16.png"), false); } - @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) { + @Override + public void render (Application app) { app.getGraphics().getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); viewMatrix.setToOrtho2D(0, 0, 480, 320); @@ -82,15 +80,16 @@ public GameOver (Application app) { spriteBatch.setColor(Color.WHITE); spriteBatch.draw(background, 0, 0, 480, 320, 0, 0, 512, 512, false, false); spriteBatch.enableBlending(); - spriteBatch.draw(logo, 0, 320-128, 480, 128, 0, 256, 512, 256, false, false); + spriteBatch.draw(logo, 0, 320 - 128, 480, 128, 0, 256, 512, 256, false, false); String text = "It is the end my friend.\nTouch to continue!"; TextBounds bounds = font.getMultiLineBounds(text); spriteBatch.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); - font.drawMultiLine(spriteBatch, text, 0, 160 + bounds.height / 2, 480, HAlignment.CENTER); + font.drawMultiLine(spriteBatch, text, 0, 160 + bounds.height / 2, 480, HAlignment.CENTER); 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 4346752e8bc..bf49287da61 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 @@ -14,24 +14,19 @@ package com.badlogic.gdxinvaders.screens; import com.badlogic.gdx.Application; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; 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.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; 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 +/** 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 - * - */ + * @author mzechner */ public class MainMenu implements Screen { /** the SpriteBatch used to draw the background, logo and text **/ private final SpriteBatch spriteBatch; @@ -50,7 +45,7 @@ public class MainMenu implements Screen { public MainMenu (Application app) { spriteBatch = new SpriteBatch(); background = new Texture(Gdx.files.internal("data/planet.jpg")); - background.setFilter(TextureFilter.Linear, TextureFilter.Linear); + background.setFilter(TextureFilter.Linear, TextureFilter.Linear); logo = new Texture(Gdx.files.internal("data/title.png")); logo.setFilter(TextureFilter.Linear, TextureFilter.Linear); @@ -58,7 +53,8 @@ public MainMenu (Application app) { font = new BitmapFont(Gdx.files.internal("data/font16.fnt"), Gdx.files.internal("data/font16.png"), false); } - @Override public void render (Application app) { + @Override + public void render (Application app) { app.getGraphics().getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); viewMatrix.setToOrtho2D(0, 0, 480, 320); @@ -66,26 +62,29 @@ public MainMenu (Application app) { spriteBatch.setTransformMatrix(transformMatrix); spriteBatch.begin(); spriteBatch.disableBlending(); - spriteBatch.setColor(Color.WHITE); + spriteBatch.setColor(Color.WHITE); spriteBatch.draw(background, 0, 0, 480, 320, 0, 0, 512, 512, false, false); spriteBatch.enableBlending(); - spriteBatch.draw(logo, 0, 320-128, 480, 128, 0, 0, 512, 256, false, false); + spriteBatch.draw(logo, 0, 320 - 128, 480, 128, 0, 0, 512, 256, false, false); spriteBatch.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); String text = "Touch screen to start!"; - float width = font.getBounds(text).width; + float width = font.getBounds(text).width; font.draw(spriteBatch, text, 240 - width / 2, 128); spriteBatch.end(); } - @Override public void update (Application app) { + @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 2da1fc7b660..9455d137f5b 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 @@ -15,34 +15,23 @@ import com.badlogic.gdx.Application; -/** - * Interface for a game screen, e.g. main menu, game loop, game over screen and so on. - * @author mzechner - * - */ +/** Interface for a game screen, e.g. main menu, game loop, game over screen and so on. + * @author mzechner */ 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 - */ + * @param app the Application */ public void update (Application app); - /** - * Called when a screen should render itself - * @param app - */ + /** Called when a screen should render itself + * @param app */ public void render (Application app); - /** - * Called by GdxInvaders to check whether the screen is done. + /** Called by GdxInvaders to check whether the screen is done. * - * @return true when the screen is done, false otherwise - */ + * @return true when the screen is done, false otherwise */ public boolean isDone (); - /** - * Cleans up all resources of the screen, e.g. meshes, textures etc. - */ + /** Cleans up all resources of the screen, e.g. meshes, textures etc. */ public void dispose (); } diff --git a/demos/metagun/metagun-android/src/com/badlogic/metagun/MetagunAndroid.java b/demos/metagun/metagun-android/src/com/badlogic/metagun/MetagunAndroid.java index f800f340b81..3ed83a93e58 100644 --- a/demos/metagun/metagun-android/src/com/badlogic/metagun/MetagunAndroid.java +++ b/demos/metagun/metagun-android/src/com/badlogic/metagun/MetagunAndroid.java @@ -1,3 +1,4 @@ + package com.badlogic.metagun; import android.os.Bundle; @@ -6,10 +7,10 @@ import com.mojang.metagun.Metagun; public class MetagunAndroid extends AndroidApplication { - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - initialize(new Metagun(), false); - } -} \ No newline at end of file + /** Called when the activity is first created. */ + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + initialize(new Metagun(), false); + } +} diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Art.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Art.java index 9c8f240b478..5b6b7b5284d 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Art.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Art.java @@ -16,7 +16,7 @@ public class Art { public static Pixmap level; public static TextureRegion titleScreen; public static TextureRegion shot; - public static TextureRegion[][] buttons; + public static TextureRegion[][] buttons; public static TextureRegion winScreen1; public static TextureRegion winScreen2; @@ -35,7 +35,7 @@ public static void load () { winScreen1 = load("res/winscreen1.png", 320, 240); winScreen2 = load("res/winscreen2.png", 320, 240); } - + private static TextureRegion[][] split (String name, int width, int height) { return split(name, width, height, false); } @@ -61,30 +61,30 @@ public static TextureRegion load (String name, int width, int height) { return region; } -// private static BufferedImage scale (BufferedImage src, int scale) { -// int w = src.getWidth() * scale; -// int h = src.getHeight() * scale; -// BufferedImage res = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); -// Graphics g = res.getGraphics(); -// g.drawImage(src.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING), 0, 0, null); -// g.dispose(); -// return res; -// } +// private static BufferedImage scale (BufferedImage src, int scale) { +// int w = src.getWidth() * scale; +// int h = src.getHeight() * scale; +// BufferedImage res = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); +// Graphics g = res.getGraphics(); +// g.drawImage(src.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING), 0, 0, null); +// g.dispose(); +// return res; +// } // -// private static BufferedImage[][] mirrorsplit (BufferedImage src, int xs, int ys) { -// int xSlices = src.getWidth() / xs; -// int ySlices = src.getHeight() / ys; -// BufferedImage[][] res = new BufferedImage[xSlices][ySlices]; -// for (int x = 0; x < xSlices; x++) { -// for (int y = 0; y < ySlices; y++) { -// res[x][y] = new BufferedImage(xs, ys, BufferedImage.TYPE_INT_ARGB); -// Graphics g = res[x][y].getGraphics(); -// g.drawImage(src, xs, 0, 0, ys, x * xs, y * ys, (x + 1) * xs, (y + 1) * ys, null); -// g.dispose(); -// } -// } -// return res; -// } +// private static BufferedImage[][] mirrorsplit (BufferedImage src, int xs, int ys) { +// int xSlices = src.getWidth() / xs; +// int ySlices = src.getHeight() / ys; +// BufferedImage[][] res = new BufferedImage[xSlices][ySlices]; +// for (int x = 0; x < xSlices; x++) { +// for (int y = 0; y < ySlices; y++) { +// res[x][y] = new BufferedImage(xs, ys, BufferedImage.TYPE_INT_ARGB); +// Graphics g = res[x][y].getGraphics(); +// g.drawImage(src, xs, 0, 0, ys, x * xs, y * ys, (x + 1) * xs, (y + 1) * ys, null); +// g.dispose(); +// } +// } +// return res; +// } // private static BufferedImage[][] split(BufferedImage src, int xs, int ys) { // int xSlices = src.getWidth() / xs; diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Input.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Input.java index f22d5a616ba..7072656b9dd 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Input.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Input.java @@ -1,3 +1,4 @@ + package com.mojang.metagun; import com.badlogic.gdx.Application.ApplicationType; @@ -6,134 +7,138 @@ import com.badlogic.gdx.InputProcessor; public class Input implements InputProcessor { - public static final int UP = 0; - public static final int DOWN = 1; - public static final int LEFT = 2; - public static final int RIGHT = 3; - - public static final int JUMP = 4; - public static final int SHOOT = 5; - - public static final int ESCAPE = 6; - - public boolean[] buttons = new boolean[64]; - public boolean[] oldButtons = new boolean[64]; - - public void set(int key, boolean down) { - int button = -1; - - if (key == Keys.DPAD_UP) button = UP; - if (key == Keys.DPAD_LEFT) button = LEFT; - if (key == Keys.DPAD_DOWN) button = DOWN; - if (key == Keys.DPAD_RIGHT) button = RIGHT; - - if (key == Keys.Y) button = JUMP; - if (key == Keys.Z) button = JUMP; - if (key == Keys.X) button = SHOOT; - if (key == Keys.C) button = JUMP; - if (key == Keys.A) button = JUMP; - if (key == Keys.S) button = SHOOT; - if (key == Keys.D) button = JUMP; - - if (key == Keys.ESCAPE || - key == Keys.MENU) button = ESCAPE; - - if (button >= 0) { - buttons[button] = down; - } - } - - public void tick() { - for (int i = 0; i < buttons.length; i++) { - oldButtons[i] = buttons[i]; - } - - if(Gdx.app.getType() == ApplicationType.Android) { - boolean left = false; - boolean right = false; - boolean z = false; - boolean s = false; - - for(int i = 0; i < 2; i++) { - int x = (int)((Gdx.input.getX(i) / (float)Gdx.graphics.getWidth()) * 320); - if(!Gdx.input.isTouched(i)) continue; - if(x < 32) { - set(Keys.DPAD_LEFT, true); - left |= true; - } - if(x > 32 && x < 90) { - set(Keys.DPAD_RIGHT, true); - right |= true; - } - if(x > 320-64 && x < 320-32) { - set(Keys.Z, true); - z |= true; - } - if(x > 320-32 && x < 320) { - set(Keys.X, true); - s |= true; - } - } - - if(left==false) set(Keys.DPAD_LEFT, false); - if(right==false) set(Keys.DPAD_RIGHT, false); - if(z==false) set(Keys.Z, false); - if(s==false) set(Keys.X, false); - } - } - - - public void releaseAllKeys() { - for (int i = 0; i < buttons.length; i++) { - if(i == UP || i == DOWN) continue; - buttons[i] = false; - } - } - - @Override public boolean keyDown (int keycode) { + public static final int UP = 0; + public static final int DOWN = 1; + public static final int LEFT = 2; + public static final int RIGHT = 3; + + public static final int JUMP = 4; + public static final int SHOOT = 5; + + public static final int ESCAPE = 6; + + public boolean[] buttons = new boolean[64]; + public boolean[] oldButtons = new boolean[64]; + + public void set (int key, boolean down) { + int button = -1; + + if (key == Keys.DPAD_UP) button = UP; + if (key == Keys.DPAD_LEFT) button = LEFT; + if (key == Keys.DPAD_DOWN) button = DOWN; + if (key == Keys.DPAD_RIGHT) button = RIGHT; + + if (key == Keys.Y) button = JUMP; + if (key == Keys.Z) button = JUMP; + if (key == Keys.X) button = SHOOT; + if (key == Keys.C) button = JUMP; + if (key == Keys.A) button = JUMP; + if (key == Keys.S) button = SHOOT; + if (key == Keys.D) button = JUMP; + + if (key == Keys.ESCAPE || key == Keys.MENU) button = ESCAPE; + + if (button >= 0) { + buttons[button] = down; + } + } + + public void tick () { + for (int i = 0; i < buttons.length; i++) { + oldButtons[i] = buttons[i]; + } + + if (Gdx.app.getType() == ApplicationType.Android) { + boolean left = false; + boolean right = false; + boolean z = false; + boolean s = false; + + for (int i = 0; i < 2; i++) { + int x = (int)((Gdx.input.getX(i) / (float)Gdx.graphics.getWidth()) * 320); + if (!Gdx.input.isTouched(i)) continue; + if (x < 32) { + set(Keys.DPAD_LEFT, true); + left |= true; + } + if (x > 32 && x < 90) { + set(Keys.DPAD_RIGHT, true); + right |= true; + } + if (x > 320 - 64 && x < 320 - 32) { + set(Keys.Z, true); + z |= true; + } + if (x > 320 - 32 && x < 320) { + set(Keys.X, true); + s |= true; + } + } + + if (left == false) set(Keys.DPAD_LEFT, false); + if (right == false) set(Keys.DPAD_RIGHT, false); + if (z == false) set(Keys.Z, false); + if (s == false) set(Keys.X, false); + } + } + + public void releaseAllKeys () { + for (int i = 0; i < buttons.length; i++) { + if (i == UP || i == DOWN) continue; + buttons[i] = false; + } + } + + @Override + public boolean keyDown (int keycode) { set(keycode, true); return false; } - @Override public boolean keyUp (int keycode) { + @Override + public boolean keyUp (int keycode) { set(keycode, false); 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, int button) { - return false; - } + @Override + public boolean touchDown (int x, int y, int pointer, int button) { + return false; + } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { x = (int)(x / (float)Gdx.graphics.getWidth() * 320); - if(x > 160 - 32 && x < 160) { + if (x > 160 - 32 && x < 160) { set(Keys.DPAD_UP, !buttons[UP]); - if(buttons[UP]) - buttons[DOWN] = false; + if (buttons[UP]) buttons[DOWN] = false; } - if(x > 160 && x < 160 + 32) { + if (x > 160 && x < 160 + 32) { set(Keys.DPAD_DOWN, !buttons[DOWN]); - if(buttons[DOWN]) - buttons[UP] = false; + if (buttons[DOWN]) buttons[UP] = false; } System.out.println("buttons: " + buttons[UP] + ", " + buttons[DOWN]); return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; - } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Metagun.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Metagun.java index cf6d50217e2..143a4b4fe91 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Metagun.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Metagun.java @@ -1,12 +1,9 @@ -package com.mojang.metagun; +package com.mojang.metagun; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; -import com.badlogic.gdx.graphics.g2d.BitmapFont; -import com.badlogic.gdx.graphics.g2d.SpriteBatch; -import com.mojang.metagun.screen.GameScreen; import com.mojang.metagun.screen.Screen; import com.mojang.metagun.screen.TitleScreen; @@ -22,54 +19,52 @@ public class Metagun implements ApplicationListener { private Input input = new Input(); private boolean started = false; private float accum = 0; - - public void create() { + + public void create () { Art.load(); Sound.load(); - Gdx.input.setInputProcessor(input); + Gdx.input.setInputProcessor(input); running = true; setScreen(new TitleScreen()); -// setScreen(new GameScreen()); +// setScreen(new GameScreen()); } - public void pause() { + public void pause () { running = false; } - public void resume() { + public void resume () { running = true; } - public void setScreen(Screen newScreen) { - if (screen != null) - screen.removed(); + public void setScreen (Screen newScreen) { + if (screen != null) screen.removed(); screen = newScreen; - if (screen != null) - screen.init(this); + if (screen != null) screen.init(this); } - public void render() { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); accum += Gdx.graphics.getDeltaTime(); - while(accum > 1.0f / 60.0f) { - screen.tick(input); + while (accum > 1.0f / 60.0f) { + screen.tick(input); input.tick(); accum -= 1.0f / 60.0f; } - screen.render(); -// batch.begin(); -// font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 30); -// batch.end(); + screen.render(); +// batch.begin(); +// font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 30); +// batch.end(); } - + @Override - public void resize(int width, int height) { + public void resize (int width, int height) { // TODO Auto-generated method stub } @Override - public void dispose() { + public void dispose () { // TODO Auto-generated method stub } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/MetagunDesktop.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/MetagunDesktop.java index e1313c3e7dc..03410906045 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/MetagunDesktop.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/MetagunDesktop.java @@ -1,9 +1,10 @@ + package com.mojang.metagun; import com.badlogic.gdx.backends.jogl.JoglApplication; public class MetagunDesktop { - public static void main(String[] argv) { + public static void main (String[] argv) { new JoglApplication(new Metagun(), "Metagun", 320, 240, false); } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Sound.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Sound.java index 27838da4d44..b51573e8097 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Sound.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Sound.java @@ -1,34 +1,35 @@ + package com.mojang.metagun; import com.badlogic.gdx.Gdx; public class Sound { - - public static com.badlogic.gdx.audio.Sound boom; - public static com.badlogic.gdx.audio.Sound hit; - public static com.badlogic.gdx.audio.Sound splat; - public static com.badlogic.gdx.audio.Sound launch; - public static com.badlogic.gdx.audio.Sound pew; - public static com.badlogic.gdx.audio.Sound oof; - public static com.badlogic.gdx.audio.Sound gethat; - public static com.badlogic.gdx.audio.Sound death; - public static com.badlogic.gdx.audio.Sound startgame; - public static com.badlogic.gdx.audio.Sound jump; - public static void load() { - boom = load("res/boom.wav"); - hit = load("res/hit.wav"); - splat = load("res/splat.wav"); - launch = load("res/launch.wav"); - pew = load("res/pew.wav"); - oof = load("res/oof.wav"); - gethat = load("res/gethat.wav"); - death = load("res/death.wav"); - startgame = load("res/startgame.wav"); - jump = load("res/jump.wav"); - } - - private static com.badlogic.gdx.audio.Sound load(String name) { - return Gdx.audio.newSound(Gdx.files.internal(name)); - } + public static com.badlogic.gdx.audio.Sound boom; + public static com.badlogic.gdx.audio.Sound hit; + public static com.badlogic.gdx.audio.Sound splat; + public static com.badlogic.gdx.audio.Sound launch; + public static com.badlogic.gdx.audio.Sound pew; + public static com.badlogic.gdx.audio.Sound oof; + public static com.badlogic.gdx.audio.Sound gethat; + public static com.badlogic.gdx.audio.Sound death; + public static com.badlogic.gdx.audio.Sound startgame; + public static com.badlogic.gdx.audio.Sound jump; + + public static void load () { + boom = load("res/boom.wav"); + hit = load("res/hit.wav"); + splat = load("res/splat.wav"); + launch = load("res/launch.wav"); + pew = load("res/pew.wav"); + oof = load("res/oof.wav"); + gethat = load("res/gethat.wav"); + death = load("res/death.wav"); + startgame = load("res/startgame.wav"); + jump = load("res/jump.wav"); + } + + private static com.badlogic.gdx.audio.Sound load (String name) { + return Gdx.audio.newSound(Gdx.files.internal(name)); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Stats.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Stats.java index 9292cb20149..ccf495f7289 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/Stats.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/Stats.java @@ -1,55 +1,56 @@ + package com.mojang.metagun; public class Stats { - public static Stats instance = new Stats(); - - public int deaths = 0; - public int shots = 0; - public int kills = 0; - public int jumps = 0; - public int time = 0; - public int hats = 0; - - public static void reset() { - Stats.instance = new Stats(); - } - - private Stats() { - } - - public int getSpeedScore() { - int seconds = time/60; - int speedScore = (60*10-seconds)*100; - if (speedScore<0) speedScore = 0; - return speedScore; - } - - public int getDeathScore() { - int deathScore = 10000-deaths*100; - if (deathScore<0) deathScore = 0; - return deathScore; - } - - public int getHatScore() { - int hatScore = hats*5000; - return hatScore; - } - - public int getShotScore() { - return shots/10; - } - - public int getFinalScore() { - return getSpeedScore()+getDeathScore()+getHatScore()+getShotScore(); - } - - public String getTimeString() { - int seconds = time/60; - int minutes = seconds/60; - seconds%=60; - String str = minutes+":"; - if (seconds<10) str+="0"; - str+=seconds; - return str; - } -} \ No newline at end of file + public static Stats instance = new Stats(); + + public int deaths = 0; + public int shots = 0; + public int kills = 0; + public int jumps = 0; + public int time = 0; + public int hats = 0; + + public static void reset () { + Stats.instance = new Stats(); + } + + private Stats () { + } + + public int getSpeedScore () { + int seconds = time / 60; + int speedScore = (60 * 10 - seconds) * 100; + if (speedScore < 0) speedScore = 0; + return speedScore; + } + + public int getDeathScore () { + int deathScore = 10000 - deaths * 100; + if (deathScore < 0) deathScore = 0; + return deathScore; + } + + public int getHatScore () { + int hatScore = hats * 5000; + return hatScore; + } + + public int getShotScore () { + return shots / 10; + } + + public int getFinalScore () { + return getSpeedScore() + getDeathScore() + getHatScore() + getShotScore(); + } + + public String getTimeString () { + int seconds = time / 60; + int minutes = seconds / 60; + seconds %= 60; + String str = minutes + ":"; + if (seconds < 10) str += "0"; + str += seconds; + return str; + } +} diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Boss.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Boss.java index 99250dbf246..ef81e8051be 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Boss.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Boss.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -6,91 +7,91 @@ import com.mojang.metagun.screen.Screen; public class Boss extends BossPart { - private static final int MAX_TEMPERATURE = 80 * 5; - private int temperature = 0; - public int slamTime = 0; - private double xo, yo; - public int time = 0; + private static final int MAX_TEMPERATURE = 80 * 5; + private int temperature = 0; + public int slamTime = 0; + private double xo, yo; + public int time = 0; - public Boss(int x, int y) { - this.x = x; - this.y = y; - w = 14; - h = 14; - bounce = 0; - } + public Boss (int x, int y) { + this.x = x; + this.y = y; + w = 14; + h = 14; + bounce = 0; + } - public void tick() { - if (dieIn > 0) { - if (--dieIn == 0) die(); - } - xa = x - xo; - ya = y - yo; - time++; - if (time % 60 == 0) { - for (int i = 0; i < 16; i++) { - double xxa = Math.sin(i * Math.PI * 2 / 16); - double yya = Math.cos(i * Math.PI * 2 / 16); - level.add(new Gunner(x + xxa * 4, y + yya * 4, xa * 0.2 + xxa, ya * 0.2 + yya - 1)); - } - } else if (time%60>20 && time%60<40 && time%4==0) { - double xd = (level.player.x + level.player.w / 2) - (x + w / 2); - double yd = (level.player.y + level.player.h / 2) - (y + h / 2); - double dd = Math.sqrt(xd * xd + yd * yd); - xd /= dd; - yd /= dd; - Sound.hit.play(); - level.add(new Bullet(this, x + 2, y + 2, xd, yd)); - } - xo = x; - yo = y; + public void tick () { + if (dieIn > 0) { + if (--dieIn == 0) die(); + } + xa = x - xo; + ya = y - yo; + time++; + if (time % 60 == 0) { + for (int i = 0; i < 16; i++) { + double xxa = Math.sin(i * Math.PI * 2 / 16); + double yya = Math.cos(i * Math.PI * 2 / 16); + level.add(new Gunner(x + xxa * 4, y + yya * 4, xa * 0.2 + xxa, ya * 0.2 + yya - 1)); + } + } else if (time % 60 > 20 && time % 60 < 40 && time % 4 == 0) { + double xd = (level.player.x + level.player.w / 2) - (x + w / 2); + double yd = (level.player.y + level.player.h / 2) - (y + h / 2); + double dd = Math.sqrt(xd * xd + yd * yd); + xd /= dd; + yd /= dd; + Sound.hit.play(); + level.add(new Bullet(this, x + 2, y + 2, xd, yd)); + } + xo = x; + yo = y; - java.util.List entities = level.getEntities((int) x + 4, (int) y + 4, w - 8, h - 4); - for (int i = 0; i < entities.size(); i++) { - entities.get(i).collideMonster(this); - } - } + java.util.List entities = level.getEntities((int)x + 4, (int)y + 4, w - 8, h - 4); + for (int i = 0; i < entities.size(); i++) { + entities.get(i).collideMonster(this); + } + } - public void render(Screen screen, Camera camera) { - int xp = (int) x - 2; - int yp = (int) y - 2; - screen.draw(Art.gremlins[3][1], xp, yp); - //FIXME -// g.setColor(Color.BLACK); -// yp += 2; -// xp -= 7; -// g.fillRect(xp + 5, yp - 8, 20, 3); -// g.setColor(Color.RED); -// g.fillRect(xp + 5, yp - 8, 20 - (20 * temperature / MAX_TEMPERATURE), 2); - } + public void render (Screen screen, Camera camera) { + int xp = (int)x - 2; + int yp = (int)y - 2; + screen.draw(Art.gremlins[3][1], xp, yp); + // FIXME +// g.setColor(Color.BLACK); +// yp += 2; +// xp -= 7; +// g.fillRect(xp + 5, yp - 8, 20, 3); +// g.setColor(Color.RED); +// g.fillRect(xp + 5, yp - 8, 20 - (20 * temperature / MAX_TEMPERATURE), 2); + } - public void hitSpikes() { - } + public void hitSpikes () { + } - private void die() { - Sound.death.play(); - for (int i = 0; i < 32; i++) { - level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); - } - Sound.boom.play(); - for (int i = 0; i < 32; i++) { - double dir = i * Math.PI * 2 / 8.0; - double xa = Math.sin(dir); - double ya = Math.cos(dir); - double dist = ((i / 8) + 1); - level.add(new Explosion(1, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); - } - remove(); - } + private void die () { + Sound.death.play(); + for (int i = 0; i < 32; i++) { + level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); + } + Sound.boom.play(); + for (int i = 0; i < 32; i++) { + double dir = i * Math.PI * 2 / 8.0; + double xa = Math.sin(dir); + double ya = Math.cos(dir); + double dist = ((i / 8) + 1); + level.add(new Explosion(1, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); + } + remove(); + } - public boolean shot(Bullet bullet) { - return true; - } + public boolean shot (Bullet bullet) { + return true; + } - public void explode(Explosion explosion) { - if (explosion.power > 0) { - die(); - } - } + public void explode (Explosion explosion) { + if (explosion.power > 0) { + die(); + } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossNeck.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossNeck.java index 308a03e7432..ea42ad4528d 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossNeck.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossNeck.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -5,79 +6,79 @@ import com.mojang.metagun.screen.Screen; public class BossNeck extends BossPart { - public int slamTime = 0; - public BossPart child; - public double baseRot = Math.PI * 1.25; - public double rot = 0, rota = 0; - public int time = 0; + public int slamTime = 0; + public BossPart child; + public double baseRot = Math.PI * 1.25; + public double rot = 0, rota = 0; + public int time = 0; - public BossNeck(int x, int y, BossPart child) { - this.child = child; - this.x = x; - this.y = y; - w = 12; - h = 12; - bounce = 0; - } + public BossNeck (int x, int y, BossPart child) { + this.child = child; + this.x = x; + this.y = y; + w = 12; + h = 12; + bounce = 0; + } - public void tick() { - if (dieIn>0) { - if (--dieIn==0) die(); - } - time++; + public void tick () { + if (dieIn > 0) { + if (--dieIn == 0) die(); + } + time++; - rot = Math.sin(time / 40.0) * Math.cos(time / 13.0) * 0.5; - rota *= 0.9; - rot *= 0.9; - double rr = baseRot + rot; - double xa = Math.sin(rr); - double ya = Math.cos(rr); - child.x = x + xa * 8; - child.y = y + ya * 8; - child.setRot(rr); + rot = Math.sin(time / 40.0) * Math.cos(time / 13.0) * 0.5; + rota *= 0.9; + rot *= 0.9; + double rr = baseRot + rot; + double xa = Math.sin(rr); + double ya = Math.cos(rr); + child.x = x + xa * 8; + child.y = y + ya * 8; + child.setRot(rr); - java.util.List entities = level.getEntities((int) x + 4, (int) y + 4, w - 8, h - 4); - for (int i = 0; i < entities.size(); i++) { - entities.get(i).collideMonster(this); - } - } + java.util.List entities = level.getEntities((int)x + 4, (int)y + 4, w - 8, h - 4); + for (int i = 0; i < entities.size(); i++) { + entities.get(i).collideMonster(this); + } + } - public void setRot(double rot) { - baseRot = rot; - } + public void setRot (double rot) { + baseRot = rot; + } - public void render(Screen screen, Camera camera) { - int xp = (int) x - 1; - int yp = (int) y - 1; - screen.draw(Art.gremlins[4][1], xp, yp); - } + public void render (Screen screen, Camera camera) { + int xp = (int)x - 1; + int yp = (int)y - 1; + screen.draw(Art.gremlins[4][1], xp, yp); + } - public void hitSpikes() { - die(); - } + public void hitSpikes () { + die(); + } - private void die() { - child.dieIn = 5; - for (int i = 0; i < 4; i++) { - level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); - } - for (int i = 0; i < 4; i++) { - double dir = i * Math.PI * 2 / 8.0; - double xa = Math.sin(dir); - double ya = Math.cos(dir); - double dist = ((i / 8) + 1); - level.add(new Explosion(1, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); - } - remove(); - } + private void die () { + child.dieIn = 5; + for (int i = 0; i < 4; i++) { + level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); + } + for (int i = 0; i < 4; i++) { + double dir = i * Math.PI * 2 / 8.0; + double xa = Math.sin(dir); + double ya = Math.cos(dir); + double dist = ((i / 8) + 1); + level.add(new Explosion(1, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); + } + remove(); + } - public boolean shot(Bullet bullet) { - return true; - } + public boolean shot (Bullet bullet) { + return true; + } - public void explode(Explosion explosion) { - if (explosion.power > 0) { - die(); - } - } + public void explode (Explosion explosion) { + if (explosion.power > 0) { + die(); + } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossPart.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossPart.java index 32c04dd1fc4..d0dee4597b1 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossPart.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/BossPart.java @@ -1,12 +1,12 @@ -package com.mojang.metagun.entity; +package com.mojang.metagun.entity; public abstract class BossPart extends Entity { - public int dieIn = 0; + public int dieIn = 0; - public void setRot(double rot) { - } + public void setRot (double rot) { + } - public void outOfBounds() { - } -} \ No newline at end of file + public void outOfBounds () { + } +} diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Bullet.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Bullet.java index f20095133ce..bda95907046 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Bullet.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Bullet.java @@ -1,82 +1,82 @@ -package com.mojang.metagun.entity; +package com.mojang.metagun.entity; import com.mojang.metagun.Art; -import com.mojang.metagun.level.*; +import com.mojang.metagun.level.Camera; import com.mojang.metagun.screen.Screen; public class Bullet extends Entity { - public Entity source; - public int noHitTime = 10; - private int tick = 0; + public Entity source; + public int noHitTime = 10; + private int tick = 0; - public Bullet(Entity source, double x, double y, double xa, double ya) { - this.source = source; - this.x = x; - this.y = y; - this.w = 1; - this.h = 1; - this.xa = xa + (random.nextDouble() - random.nextDouble()) * 0.1; - this.ya = ya + (random.nextDouble() - random.nextDouble()) * 0.1; + public Bullet (Entity source, double x, double y, double xa, double ya) { + this.source = source; + this.x = x; + this.y = y; + this.w = 1; + this.h = 1; + this.xa = xa + (random.nextDouble() - random.nextDouble()) * 0.1; + this.ya = ya + (random.nextDouble() - random.nextDouble()) * 0.1; - interactsWithWorld = true; - } + interactsWithWorld = true; + } - public void tick() { - tick++; - tryMove(xa, ya); + public void tick () { + tick++; + tryMove(xa, ya); - if (noHitTime > 0) { - noHitTime--; - return; - } - java.util.List entities = level.getEntities((int) x, (int) y, 1, 1); - for (int i = 0; i < entities.size(); i++) { - Entity e = entities.get(i); - if (source==e) continue; + if (noHitTime > 0) { + noHitTime--; + return; + } + java.util.List entities = level.getEntities((int)x, (int)y, 1, 1); + for (int i = 0; i < entities.size(); i++) { + Entity e = entities.get(i); + if (source == e) continue; - if (e.shot(this)) { - remove(); - } - } - } + if (e.shot(this)) { + remove(); + } + } + } - protected void hitWall(double xa, double ya) { - for (int i = 0; i < 3; i++) { - level.add(new Spark(x, y, 0, 0)); - } - remove(); - } + protected void hitWall (double xa, double ya) { + for (int i = 0; i < 3; i++) { + level.add(new Spark(x, y, 0, 0)); + } + remove(); + } - public void render(Screen g, Camera camera) { - // FIXME -// if (tick % 2 == 0) { -// g.setColor(Color.YELLOW); -// int x1 = (int) (x + w / 2 - xa * 3); -// int y1 = (int) (y + h / 2 - ya * 3); -// int x2 = (int) (x + w / 2); -// int y2 = (int) (y + h / 2); + public void render (Screen g, Camera camera) { + // FIXME +// if (tick % 2 == 0) { +// g.setColor(Color.YELLOW); +// int x1 = (int) (x + w / 2 - xa * 3); +// int y1 = (int) (y + h / 2 - ya * 3); +// int x2 = (int) (x + w / 2); +// int y2 = (int) (y + h / 2); // -// g.drawLine(x1, y1, x2, y2); -// g.setColor(Color.WHITE); +// g.drawLine(x1, y1, x2, y2); +// g.setColor(Color.WHITE); // -// x1 = (int) (x + w / 2 - xa); -// y1 = (int) (y + h / 2 - ya); -// x2 = (int) (x + w / 2 + xa); -// y2 = (int) (y + h / 2 + ya); +// x1 = (int) (x + w / 2 - xa); +// y1 = (int) (y + h / 2 - ya); +// x2 = (int) (x + w / 2 + xa); +// y2 = (int) (y + h / 2 + ya); // -// g.drawLine(x1, y1, x2, y2); -// } else { -// g.setColor(Color.YELLOW); -// int x1 = (int) (x + w / 2 - xa); -// int y1 = (int) (y + h / 2 - ya); -// int x2 = (int) (x + w / 2 + xa); -// int y2 = (int) (y + h / 2 + ya); +// g.drawLine(x1, y1, x2, y2); +// } else { +// g.setColor(Color.YELLOW); +// int x1 = (int) (x + w / 2 - xa); +// int y1 = (int) (y + h / 2 - ya); +// int x2 = (int) (x + w / 2 + xa); +// int y2 = (int) (y + h / 2 + ya); // -// g.drawLine(x1, y1, x2, y2); -// } +// g.drawLine(x1, y1, x2, y2); +// } - g.draw(Art.shot, (int)x, (int)y); - // g.fillRect(xp, yp, w, h); - } + g.draw(Art.shot, (int)x, (int)y); + // g.fillRect(xp, yp, w, h); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Entity.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Entity.java index 7d3b0d9dd4b..88a352cc60a 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Entity.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Entity.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import java.util.Random; @@ -7,91 +8,91 @@ import com.mojang.metagun.screen.Screen; public abstract class Entity { - protected boolean onGround = false; - protected static Random random = new Random(); - - public double xa, ya; - public double x, y; - protected double bounce = 0.05; - public int w = 10, h = 10; - - protected Level level; - public boolean removed = false; - public int xSlot, ySlot; - - public boolean interactsWithWorld = false; - - public void init(Level level) { - this.level = level; - } - - public void tryMove(double xa, double ya) { - onGround = false; - if (level.isFree(this, x + xa, y, w, h, xa, 0)) { - x += xa; - } else { - hitWall(xa, 0); - if (xa < 0) { - double xx = x / 10; - xa = -(xx - ((int) xx)) * 10; - } else { - double xx = (x + w) / 10; - xa = 10 - (xx - ((int) xx)) * 10; - } - if (level.isFree(this, x + xa, y, w, h, xa, 0)) { - x += xa; - } - this.xa *= -bounce; - } - if (level.isFree(this, x, y + ya, w, h, 0, ya)) { - y += ya; - } else { - if (ya > 0) onGround = true; - hitWall(0, ya); - if (ya < 0) { - double yy = y / 10; - ya = -(yy - ((int) yy)) * 10; - } else { - double yy = (y + h) / 10; - ya = 10 - (yy - ((int) yy)) * 10; - } - if (level.isFree(this, x, y + ya, w, h, 0, ya)) { - y += ya; - } - this.ya *= -bounce; - } - } - - protected void hitWall(double xa, double ya) { - } - - public void remove() { - removed = true; - } - - public void tick() { - } - - public abstract void render(Screen screen, Camera camera); - - public boolean shot(Bullet bullet) { - return false; - } - - public void hitSpikes() { - } - - public void shove(Gunner enemy) { - } - - public void outOfBounds() { - if (y < 0) return; - remove(); - } - - public void explode(Explosion explosion) { - } - - public void collideMonster(Entity e) { - } + protected boolean onGround = false; + protected static Random random = new Random(); + + public double xa, ya; + public double x, y; + protected double bounce = 0.05; + public int w = 10, h = 10; + + protected Level level; + public boolean removed = false; + public int xSlot, ySlot; + + public boolean interactsWithWorld = false; + + public void init (Level level) { + this.level = level; + } + + public void tryMove (double xa, double ya) { + onGround = false; + if (level.isFree(this, x + xa, y, w, h, xa, 0)) { + x += xa; + } else { + hitWall(xa, 0); + if (xa < 0) { + double xx = x / 10; + xa = -(xx - ((int)xx)) * 10; + } else { + double xx = (x + w) / 10; + xa = 10 - (xx - ((int)xx)) * 10; + } + if (level.isFree(this, x + xa, y, w, h, xa, 0)) { + x += xa; + } + this.xa *= -bounce; + } + if (level.isFree(this, x, y + ya, w, h, 0, ya)) { + y += ya; + } else { + if (ya > 0) onGround = true; + hitWall(0, ya); + if (ya < 0) { + double yy = y / 10; + ya = -(yy - ((int)yy)) * 10; + } else { + double yy = (y + h) / 10; + ya = 10 - (yy - ((int)yy)) * 10; + } + if (level.isFree(this, x, y + ya, w, h, 0, ya)) { + y += ya; + } + this.ya *= -bounce; + } + } + + protected void hitWall (double xa, double ya) { + } + + public void remove () { + removed = true; + } + + public void tick () { + } + + public abstract void render (Screen screen, Camera camera); + + public boolean shot (Bullet bullet) { + return false; + } + + public void hitSpikes () { + } + + public void shove (Gunner enemy) { + } + + public void outOfBounds () { + if (y < 0) return; + remove(); + } + + public void explode (Explosion explosion) { + } + + public void collideMonster (Entity e) { + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Explosion.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Explosion.java index 7ada851c05b..aa18aabdddc 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Explosion.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Explosion.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -6,59 +7,59 @@ import com.mojang.metagun.screen.Screen; public class Explosion extends Entity { - private int life, delay, color; - private int duration; - public int power; + private int life, delay, color; + private int duration; + public int power; - public Explosion(int power, int delay, double x, double y, double xa, double ya) { - this.power = power; - this.x = x; - this.y = y; - this.w = 1; - this.h = 1; - bounce = 0.2; - this.xa = (xa + (random.nextDouble() - random.nextDouble()) * 0.2); - this.ya = (ya + (random.nextDouble() - random.nextDouble()) * 0.2); + public Explosion (int power, int delay, double x, double y, double xa, double ya) { + this.power = power; + this.x = x; + this.y = y; + this.w = 1; + this.h = 1; + bounce = 0.2; + this.xa = (xa + (random.nextDouble() - random.nextDouble()) * 0.2); + this.ya = (ya + (random.nextDouble() - random.nextDouble()) * 0.2); - color = random.nextInt(3); + color = random.nextInt(3); - duration = random.nextInt(20) + 10; - life = 0; - } + duration = random.nextInt(20) + 10; + life = 0; + } - public void tick() { - if (delay > 0) { - delay--; - return; - } - if (life++ >= duration) remove(); - interactsWithWorld = (life > 10); - onGround = false; - // tryMove(xa, ya); - x += xa; - y += ya; + public void tick () { + if (delay > 0) { + delay--; + return; + } + if (life++ >= duration) remove(); + interactsWithWorld = (life > 10); + onGround = false; + // tryMove(xa, ya); + x += xa; + y += ya; - level.isFree(this, x, y, w, h, 0, 0); - xa *= 0.95; - ya *= 0.95; - ya -= Level.GRAVITY * 0.15; + level.isFree(this, x, y, w, h, 0, 0); + xa *= 0.95; + ya *= 0.95; + ya -= Level.GRAVITY * 0.15; - if (interactsWithWorld && life < duration*0.75) { - java.util.List entities = level.getEntities((int) x, (int) y, 1, 1); - for (int i = 0; i < entities.size(); i++) { - entities.get(i).explode(this); - } - } - } + if (interactsWithWorld && life < duration * 0.75) { + java.util.List entities = level.getEntities((int)x, (int)y, 1, 1); + for (int i = 0; i < entities.size(); i++) { + entities.get(i).explode(this); + } + } + } - protected void hitWall(double xa, double ya) { - this.xa *= 0.4; - this.ya *= 0.4; - } + protected void hitWall (double xa, double ya) { + this.xa *= 0.4; + this.ya *= 0.4; + } - public void render(Screen g, Camera camera) { - int xp = (int) x; - int yp = (int) y; - g.draw(Art.guys[(life - 1) * 8 / duration][4 + color], xp - 3, yp - 3); - } + public void render (Screen g, Camera camera) { + int xp = (int)x; + int yp = (int)y; + g.draw(Art.guys[(life - 1) * 8 / duration][4 + color], xp - 3, yp - 3); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gore.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gore.java index 728c19187c6..9eab5bf2982 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gore.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gore.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -6,38 +7,38 @@ import com.mojang.metagun.screen.Screen; public class Gore extends Entity { - private int life; - - public Gore(double x, double y, double xa, double ya) { - this.x = x; - this.y = y; - this.w = 1; - this.h = 1; - bounce = 0.2; - this.xa = (xa + (random.nextDouble() - random.nextDouble()) * 1)*0.2; - this.ya = (ya + (random.nextDouble() - random.nextDouble()) * 1)*0.2; - - life = random.nextInt(20) + 10; - } - - public void tick() { - if (life-- <= 0) remove(); - onGround = false; - tryMove(xa, ya); - - xa *= 0.999; - ya *= 0.999; - ya += Level.GRAVITY*0.15; - } - - protected void hitWall(double xa, double ya) { - this.xa *= 0.4; - this.ya *= 0.4; - } - - public void render(Screen g, Camera camera) { - int xp = (int) x; - int yp = (int) y; - g.draw(Art.guys[7][1], xp, yp); - } + private int life; + + public Gore (double x, double y, double xa, double ya) { + this.x = x; + this.y = y; + this.w = 1; + this.h = 1; + bounce = 0.2; + this.xa = (xa + (random.nextDouble() - random.nextDouble()) * 1) * 0.2; + this.ya = (ya + (random.nextDouble() - random.nextDouble()) * 1) * 0.2; + + life = random.nextInt(20) + 10; + } + + public void tick () { + if (life-- <= 0) remove(); + onGround = false; + tryMove(xa, ya); + + xa *= 0.999; + ya *= 0.999; + ya += Level.GRAVITY * 0.15; + } + + protected void hitWall (double xa, double ya) { + this.xa *= 0.4; + this.ya *= 0.4; + } + + public void render (Screen g, Camera camera) { + int xp = (int)x; + int yp = (int)y; + g.draw(Art.guys[7][1], xp, yp); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gremlin.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gremlin.java index 638ed958ba5..1ac2e3b0f00 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gremlin.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gremlin.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -7,114 +8,114 @@ import com.mojang.metagun.screen.Screen; public class Gremlin extends Entity { - private static final int MAX_TEMPERATURE = 80 * 5; - private int temperature = 0; - public int jumpDelay = 0; - private int power = 0; + private static final int MAX_TEMPERATURE = 80 * 5; + private int temperature = 0; + public int jumpDelay = 0; + private int power = 0; - public Gremlin(int power, int x, int y) { - this.power = power; - this.x = x; - this.y = y; - w = 30; - h = 30; - bounce = 0; - } + public Gremlin (int power, int x, int y) { + this.power = power; + this.x = x; + this.y = y; + w = 30; + h = 30; + bounce = 0; + } - public void tick() { - if (temperature > 0) { - temperature--; - for (int i = 0; i < 1; i++) { - if (random.nextInt(MAX_TEMPERATURE) <= temperature) { - double xd = (random.nextDouble() - random.nextDouble()) * 0.2; - double yd = (random.nextDouble() - random.nextDouble()) * 0.2; - level.add(new Spark(x + random.nextDouble() * w, y + random.nextDouble() * h, xa * 0.2 + xd, ya * 0.2 + yd)); - } - } - } - tryMove(xa, ya); - xa *= 0.4; - ya *= Level.FRICTION; - ya += Level.GRAVITY; + public void tick () { + if (temperature > 0) { + temperature--; + for (int i = 0; i < 1; i++) { + if (random.nextInt(MAX_TEMPERATURE) <= temperature) { + double xd = (random.nextDouble() - random.nextDouble()) * 0.2; + double yd = (random.nextDouble() - random.nextDouble()) * 0.2; + level.add(new Spark(x + random.nextDouble() * w, y + random.nextDouble() * h, xa * 0.2 + xd, ya * 0.2 + yd)); + } + } + } + tryMove(xa, ya); + xa *= 0.4; + ya *= Level.FRICTION; + ya += Level.GRAVITY; - if (onGround) { - if (power==1 && jumpDelay <= 19) { - if (jumpDelay % 2 == 0) { - if (jumpDelay % 4 == 0) { - Sound.hit.play(); - } - double dir = jumpDelay / 32.0f * Math.PI * 2+0.1; - double xa = Math.cos(dir); - double ya = -Math.sin(dir); - level.add(new Bullet(this, x + 15, y + 10, xa, ya)); - } - } - if (jumpDelay++ > 60) { - ya = -2; - jumpDelay = 0; - } - } + if (onGround) { + if (power == 1 && jumpDelay <= 19) { + if (jumpDelay % 2 == 0) { + if (jumpDelay % 4 == 0) { + Sound.hit.play(); + } + double dir = jumpDelay / 32.0f * Math.PI * 2 + 0.1; + double xa = Math.cos(dir); + double ya = -Math.sin(dir); + level.add(new Bullet(this, x + 15, y + 10, xa, ya)); + } + } + if (jumpDelay++ > 60) { + ya = -2; + jumpDelay = 0; + } + } - java.util.List entities = level.getEntities((int) x+4, (int) y+4, w-8, h-4); - for (int i = 0; i < entities.size(); i++) { - entities.get(i).collideMonster(this); - } - } + java.util.List entities = level.getEntities((int)x + 4, (int)y + 4, w - 8, h - 4); + for (int i = 0; i < entities.size(); i++) { + entities.get(i).collideMonster(this); + } + } - public void render(Screen g, Camera camera) { - int xp = (int) x; - int yp = (int) y; - if (onGround) { - g.draw(Art.gremlins[0][power], xp, yp); - } else { - g.draw(Art.gremlins[ya > 0 ? 2 : 1][power], xp, yp); - } - // FIXME -// g.setColor(Color.BLACK); -// g.fillRect(xp + 5, yp - 8, 20, 3); -// g.setColor(Color.RED); -// g.fillRect(xp + 5, yp - 8, 20 - (20 * temperature / MAX_TEMPERATURE), 2); - } + public void render (Screen g, Camera camera) { + int xp = (int)x; + int yp = (int)y; + if (onGround) { + g.draw(Art.gremlins[0][power], xp, yp); + } else { + g.draw(Art.gremlins[ya > 0 ? 2 : 1][power], xp, yp); + } + // FIXME +// g.setColor(Color.BLACK); +// g.fillRect(xp + 5, yp - 8, 20, 3); +// g.setColor(Color.RED); +// g.fillRect(xp + 5, yp - 8, 20 - (20 * temperature / MAX_TEMPERATURE), 2); + } - public void hitSpikes() { - die(); - } + public void hitSpikes () { + die(); + } - private void die() { - Sound.death.play(); - for (int i = 0; i < 16; i++) { - level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); - } - Sound.boom.play(); - for (int i = 0; i < 32; i++) { - double dir = i * Math.PI * 2 / 8.0; - double xa = Math.sin(dir); - double ya = Math.cos(dir); - double dist = ((i / 8) + 1); - level.add(new Explosion(0, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); - } - remove(); - } + private void die () { + Sound.death.play(); + for (int i = 0; i < 16; i++) { + level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); + } + Sound.boom.play(); + for (int i = 0; i < 32; i++) { + double dir = i * Math.PI * 2 / 8.0; + double xa = Math.sin(dir); + double ya = Math.cos(dir); + double dist = ((i / 8) + 1); + level.add(new Explosion(0, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); + } + remove(); + } - public boolean shot(Bullet bullet) { - Sound.pew.play(); - for (int i = 0; i < 4; i++) { - double xd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.xa * 3; - double yd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.ya * 3; - level.add(new Gore(bullet.x, bullet.y, xa + xd, ya + yd)); - } - Sound.oof.play(); - temperature += 80; - if (temperature >= MAX_TEMPERATURE) { - die(); - } else { - level.add(new PlayerGore(bullet.x, bullet.y)); - } + public boolean shot (Bullet bullet) { + Sound.pew.play(); + for (int i = 0; i < 4; i++) { + double xd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.xa * 3; + double yd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.ya * 3; + level.add(new Gore(bullet.x, bullet.y, xa + xd, ya + yd)); + } + Sound.oof.play(); + temperature += 80; + if (temperature >= MAX_TEMPERATURE) { + die(); + } else { + level.add(new PlayerGore(bullet.x, bullet.y)); + } - return true; - } + return true; + } - public void explode(Explosion explosion) { - die(); - } + public void explode (Explosion explosion) { + die(); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gunner.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gunner.java index 48921756a1d..b2953c3ddca 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gunner.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Gunner.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -7,152 +8,150 @@ import com.mojang.metagun.screen.Screen; public class Gunner extends Entity { - public static final int CHARGE_DURATION = 100; - public int chargeTime = 0; - private int sliding = 0; - - public Gunner(double x, double y, double xa, double ya) { - this.x = x; - this.y = y; - this.w = 6; - this.h = 6; - bounce = -0.1; - this.xa = xa + (random.nextDouble() - random.nextDouble()) * 0.5; - this.ya = ya + (random.nextDouble() - random.nextDouble()) * 0.5; - } - - public void tick() { - onGround = false; - tryMove(xa, ya); - - if ((onGround || sliding != 0) && xa * xa < 0.01) { - if (chargeTime++ >= CHARGE_DURATION) { - chargeTime = 0; - double xd = (level.player.x + level.player.w / 2) - (x + w / 2); - double yd = (level.player.y + level.player.h / 2) - (y + h / 2); - double dd = Math.sqrt(xd * xd + yd * yd); - xd /= dd; - yd /= dd; - Sound.hit.play(); - level.add(new Bullet(this, x + 2, y + 2, xd, yd)); - } - } - xa *= Level.FRICTION; - ya *= Level.FRICTION; - ya += Level.GRAVITY; - } - - protected void hitWall(double xa, double ya) { - sliding = 0; - if (xa != 0) { - if (xa > 0) { - this.xa = 1; - sliding = 1; - } - if (xa < 0) { - this.xa = -1; - sliding = -1; - } - } - this.xa *= 0.4; - this.ya *= 0.4; - } - - - public void render(Screen g, Camera camera) { - // g.setColor(Color.red); - int xp = (int) x; - int yp = (int) y; - // g.fillRect(xp, yp, w, h); - - int xFrame = 0; - int yFrame = 0; - if (onGround) { - double xd = (level.player.x + level.player.w / 2) - (x + w / 2); - double yd = (level.player.y + level.player.h / 2) - (y + h / 2); - double dd = Math.sqrt(xd * xd + yd * yd); - xd /= dd; - yd /= dd; - xFrame = 3; - yFrame = 2; - double s = 0.3; - if (xd > s) xFrame++; - if (xd < -s) xFrame--; - if (yd > s) yFrame++; - if (yd < -s) yFrame--; - } else if (sliding != 0) { - double xd = (level.player.x + level.player.w / 2) - (x + w / 2); - double yd = (level.player.y + level.player.h / 2) - (y + h / 2); - double dd = Math.sqrt(xd * xd + yd * yd); - xd /= dd; - yd /= dd; - xFrame = 0; - yFrame = 2; - if (sliding > 0) xFrame = 1; - double s = 0.3; - if (yd > s) yFrame++; - if (yd < -s) yFrame--; - } else { - xFrame = (int) (1 - Math.floor(ya * 0.1)); - if (xFrame < 0) xFrame = 0; - if (xFrame > 2) xFrame = 2; - yFrame = 0; - } - - - g.draw(Art.guys[xFrame][yFrame], xp, yp); - - java.util.List entities = level.getEntities((int) x, (int) y, 1, 1); - for (int i = 0; i < entities.size(); i++) { - entities.get(i).shove(this); - } - } - - public boolean shot(Bullet bullet) { - die(); - return true; - } - - public void hitSpikes() { - die(); - } - - protected void die() { - Sound.splat.play(); - level.add(new HeadGore(x+2, y)); - for (int i=0; i<10; i++) { - double xd = (random.nextDouble()-random.nextDouble())*4; - double yd = (random.nextDouble()-random.nextDouble())*4; - - level.add(new Gore(x+2+random.nextDouble(), y+random.nextDouble()*6, xa+xd, ya+yd)); - } - remove(); - } - - public void shove(Gunner enemy) { - - double xd = enemy.x-x; - if (xd<0) { - xd = -0.01; - } else if (xd>0) { - xd = 0.01; - } else { - if (random.nextBoolean()) { - xd = -0.01; - } else { - xd = 0.01; - } - } - - enemy.xa+=xd; - xa-=xd; - } - - public void explode(Explosion explosion) { - die(); - } - - public void collideMonster(Entity e) { - die(); - } + public static final int CHARGE_DURATION = 100; + public int chargeTime = 0; + private int sliding = 0; + + public Gunner (double x, double y, double xa, double ya) { + this.x = x; + this.y = y; + this.w = 6; + this.h = 6; + bounce = -0.1; + this.xa = xa + (random.nextDouble() - random.nextDouble()) * 0.5; + this.ya = ya + (random.nextDouble() - random.nextDouble()) * 0.5; + } + + public void tick () { + onGround = false; + tryMove(xa, ya); + + if ((onGround || sliding != 0) && xa * xa < 0.01) { + if (chargeTime++ >= CHARGE_DURATION) { + chargeTime = 0; + double xd = (level.player.x + level.player.w / 2) - (x + w / 2); + double yd = (level.player.y + level.player.h / 2) - (y + h / 2); + double dd = Math.sqrt(xd * xd + yd * yd); + xd /= dd; + yd /= dd; + Sound.hit.play(); + level.add(new Bullet(this, x + 2, y + 2, xd, yd)); + } + } + xa *= Level.FRICTION; + ya *= Level.FRICTION; + ya += Level.GRAVITY; + } + + protected void hitWall (double xa, double ya) { + sliding = 0; + if (xa != 0) { + if (xa > 0) { + this.xa = 1; + sliding = 1; + } + if (xa < 0) { + this.xa = -1; + sliding = -1; + } + } + this.xa *= 0.4; + this.ya *= 0.4; + } + + public void render (Screen g, Camera camera) { + // g.setColor(Color.red); + int xp = (int)x; + int yp = (int)y; + // g.fillRect(xp, yp, w, h); + + int xFrame = 0; + int yFrame = 0; + if (onGround) { + double xd = (level.player.x + level.player.w / 2) - (x + w / 2); + double yd = (level.player.y + level.player.h / 2) - (y + h / 2); + double dd = Math.sqrt(xd * xd + yd * yd); + xd /= dd; + yd /= dd; + xFrame = 3; + yFrame = 2; + double s = 0.3; + if (xd > s) xFrame++; + if (xd < -s) xFrame--; + if (yd > s) yFrame++; + if (yd < -s) yFrame--; + } else if (sliding != 0) { + double xd = (level.player.x + level.player.w / 2) - (x + w / 2); + double yd = (level.player.y + level.player.h / 2) - (y + h / 2); + double dd = Math.sqrt(xd * xd + yd * yd); + xd /= dd; + yd /= dd; + xFrame = 0; + yFrame = 2; + if (sliding > 0) xFrame = 1; + double s = 0.3; + if (yd > s) yFrame++; + if (yd < -s) yFrame--; + } else { + xFrame = (int)(1 - Math.floor(ya * 0.1)); + if (xFrame < 0) xFrame = 0; + if (xFrame > 2) xFrame = 2; + yFrame = 0; + } + + g.draw(Art.guys[xFrame][yFrame], xp, yp); + + java.util.List entities = level.getEntities((int)x, (int)y, 1, 1); + for (int i = 0; i < entities.size(); i++) { + entities.get(i).shove(this); + } + } + + public boolean shot (Bullet bullet) { + die(); + return true; + } + + public void hitSpikes () { + die(); + } + + protected void die () { + Sound.splat.play(); + level.add(new HeadGore(x + 2, y)); + for (int i = 0; i < 10; i++) { + double xd = (random.nextDouble() - random.nextDouble()) * 4; + double yd = (random.nextDouble() - random.nextDouble()) * 4; + + level.add(new Gore(x + 2 + random.nextDouble(), y + random.nextDouble() * 6, xa + xd, ya + yd)); + } + remove(); + } + + public void shove (Gunner enemy) { + + double xd = enemy.x - x; + if (xd < 0) { + xd = -0.01; + } else if (xd > 0) { + xd = 0.01; + } else { + if (random.nextBoolean()) { + xd = -0.01; + } else { + xd = 0.01; + } + } + + enemy.xa += xd; + xa -= xd; + } + + public void explode (Explosion explosion) { + die(); + } + + public void collideMonster (Entity e) { + die(); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Hat.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Hat.java index df2ce001e04..5fc23e789b6 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Hat.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Hat.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.badlogic.gdx.graphics.g2d.TextureRegion; @@ -8,77 +9,78 @@ import com.mojang.metagun.screen.Screen; public class Hat extends Entity { - double time = 0; - int noTakeTime = 30; - private int xPos, yPos; - public double xxa; + double time = 0; + int noTakeTime = 30; + private int xPos, yPos; + public double xxa; - public Hat(double x, double y) { - this(x, y, -1, -1); - } + public Hat (double x, double y) { + this(x, y, -1, -1); + } - public Hat(double x, double y, int xPos, int yPos) { - this.x = x; - this.y = y; - this.xPos = xPos; - this.yPos = yPos; - w = 6; - h = 3; - bounce = 0; - ya = -1; - time = Math.PI * 0.5; - } + public Hat (double x, double y, int xPos, int yPos) { + this.x = x; + this.y = y; + this.xPos = xPos; + this.yPos = yPos; + w = 6; + h = 3; + bounce = 0; + ya = -1; + time = Math.PI * 0.5; + } - public void tick() { - tryMove(xa, ya); - if (onGround) { - time = 0; - } else { - time++; - } + public void tick () { + tryMove(xa, ya); + if (onGround) { + time = 0; + } else { + time++; + } - xa = xxa+Math.sin(time * 0.05) * 0.2; - xxa*=0.95; - ya *= 0.95; - ya += Level.GRAVITY * 0.1; + xa = xxa + Math.sin(time * 0.05) * 0.2; + xxa *= 0.95; + ya *= 0.95; + ya += Level.GRAVITY * 0.1; - if (noTakeTime > 0) noTakeTime--; - else { - java.util.List entities = level.getEntities((int) x, (int) y, w, h); - for (int i = 0; i < entities.size(); i++) { - Entity e = entities.get(i); - if (e instanceof Player) { - Player player = (Player) e; - player.hatCount++; + if (noTakeTime > 0) + noTakeTime--; + else { + java.util.List entities = level.getEntities((int)x, (int)y, w, h); + for (int i = 0; i < entities.size(); i++) { + Entity e = entities.get(i); + if (e instanceof Player) { + Player player = (Player)e; + player.hatCount++; - if (xPos >= 0 && yPos >= 0) { - Art.level.setColor(0, 0, 0, 0); - Art.level.drawPixel(xPos, yPos); - } - Sound.gethat.play(); - remove(); - } - } - } - } + if (xPos >= 0 && yPos >= 0) { + Art.level.setColor(0, 0, 0, 0); + Art.level.drawPixel(xPos, yPos); + } + Sound.gethat.play(); + remove(); + } + } + } + } - public void render(Screen g, Camera camera) { - int dir = 1; - int xp = (int) x - (16 - w) / 2; - int yp = (int) y - 2; - TextureRegion[][] sheet = dir == 1 ? Art.player1 : Art.player2; + public void render (Screen g, Camera camera) { + int dir = 1; + int xp = (int)x - (16 - w) / 2; + int yp = (int)y - 2; + TextureRegion[][] sheet = dir == 1 ? Art.player1 : Art.player2; - int xFrame = (int) (xa * 10); - if (xFrame < -1) xFrame = -1; - if (xFrame > +1) xFrame = +1; - g.draw(sheet[1 + xFrame][1], xp, yp); - } + int xFrame = (int)(xa * 10); + if (xFrame < -1) xFrame = -1; + if (xFrame > +1) xFrame = +1; + g.draw(sheet[1 + xFrame][1], xp, yp); + } - public boolean shot(Bullet bullet) { - Sound.hit.play(); - xa += bullet.xa * 0.5; - ya += bullet.ya * 0.5; + public boolean shot (Bullet bullet) { + Sound.hit.play(); + xa += bullet.xa * 0.5; + ya += bullet.ya * 0.5; - return true; - } + return true; + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/HeadGore.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/HeadGore.java index 4b5c2993e35..6beca8b6a3f 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/HeadGore.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/HeadGore.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -6,49 +7,49 @@ import com.mojang.metagun.screen.Screen; public class HeadGore extends Entity { - private int life; - - public HeadGore(double x, double y) { - this.x = x; - this.y = y; - this.w = 2; - this.h = 2; - bounce = 0.2; - this.xa = 0 + (random.nextDouble() - random.nextDouble()) * 0.5; - this.ya = -1 + (random.nextDouble() - random.nextDouble()) * 0.5; - - life = random.nextInt(60) + 20; - } - - public void tick() { - if (life-- <= 0) remove(); - onGround = false; - tryMove(xa, ya); - - xa *= Level.FRICTION; - ya *= Level.FRICTION; - ya += Level.GRAVITY*0.5; - level.add(new Gore(x+random.nextDouble(), y+random.nextDouble()-1, xa, ya)); - } - - protected void hitWall(double xa, double ya) { - this.xa *= 0.8; - this.ya *= 0.8; - } - - public void render(Screen g, Camera camera) { - int xp = (int) x; - int yp = (int) y; - g.draw(Art.guys[6][1], xp, yp); - } - - public void hitSpikes() { - for (int i = 0; i < 4; i++) { - xa = (random.nextFloat()-random.nextFloat())*6; - ya = (random.nextFloat()-random.nextFloat())*6; - level.add(new Gore(x + random.nextDouble(), y + random.nextDouble() - 1, xa, ya)); - } - remove(); - } - + private int life; + + public HeadGore (double x, double y) { + this.x = x; + this.y = y; + this.w = 2; + this.h = 2; + bounce = 0.2; + this.xa = 0 + (random.nextDouble() - random.nextDouble()) * 0.5; + this.ya = -1 + (random.nextDouble() - random.nextDouble()) * 0.5; + + life = random.nextInt(60) + 20; + } + + public void tick () { + if (life-- <= 0) remove(); + onGround = false; + tryMove(xa, ya); + + xa *= Level.FRICTION; + ya *= Level.FRICTION; + ya += Level.GRAVITY * 0.5; + level.add(new Gore(x + random.nextDouble(), y + random.nextDouble() - 1, xa, ya)); + } + + protected void hitWall (double xa, double ya) { + this.xa *= 0.8; + this.ya *= 0.8; + } + + public void render (Screen g, Camera camera) { + int xp = (int)x; + int yp = (int)y; + g.draw(Art.guys[6][1], xp, yp); + } + + public void hitSpikes () { + for (int i = 0; i < 4; i++) { + xa = (random.nextFloat() - random.nextFloat()) * 6; + ya = (random.nextFloat() - random.nextFloat()) * 6; + level.add(new Gore(x + random.nextDouble(), y + random.nextDouble() - 1, xa, ya)); + } + remove(); + } + } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Jabberwocky.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Jabberwocky.java index 32f2efdae2b..9da5a579820 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Jabberwocky.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Jabberwocky.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -7,85 +8,85 @@ import com.mojang.metagun.screen.Screen; public class Jabberwocky extends Entity { - private static final int MAX_TEMPERATURE = 80 * 5; - private int temperature = 0; - public int slamTime = 0; + private static final int MAX_TEMPERATURE = 80 * 5; + private int temperature = 0; + public int slamTime = 0; - public Jabberwocky(int x, int y) { - this.x = x; - this.y = y; - w = 30; - h = 20; - bounce = 0; - } + public Jabberwocky (int x, int y) { + this.x = x; + this.y = y; + w = 30; + h = 20; + bounce = 0; + } - public void tick() { - slamTime++; - if (temperature > 0) { - temperature--; - for (int i = 0; i < 1; i++) { - if (random.nextInt(MAX_TEMPERATURE) <= temperature) { - double xd = (random.nextDouble() - random.nextDouble()) * 0.2; - double yd = (random.nextDouble() - random.nextDouble()) * 0.2; - level.add(new Spark(x + random.nextDouble() * w, y + random.nextDouble() * h, xa * 0.2 + xd, ya * 0.2 + yd)); - } - } - } - tryMove(xa, ya); - xa *= Level.FRICTION; - ya *= Level.FRICTION; - ya += Level.GRAVITY; + public void tick () { + slamTime++; + if (temperature > 0) { + temperature--; + for (int i = 0; i < 1; i++) { + if (random.nextInt(MAX_TEMPERATURE) <= temperature) { + double xd = (random.nextDouble() - random.nextDouble()) * 0.2; + double yd = (random.nextDouble() - random.nextDouble()) * 0.2; + level.add(new Spark(x + random.nextDouble() * w, y + random.nextDouble() * h, xa * 0.2 + xd, ya * 0.2 + yd)); + } + } + } + tryMove(xa, ya); + xa *= Level.FRICTION; + ya *= Level.FRICTION; + ya += Level.GRAVITY; - java.util.List entities = level.getEntities((int) x + 4, (int) y + 4, w - 8, h - 4); - for (int i = 0; i < entities.size(); i++) { - Entity e = entities.get(i); - if (e instanceof Gunner) { - temperature += 10; - if (temperature >= MAX_TEMPERATURE) { - die(); - } - } - e.collideMonster(this); - } - } + java.util.List entities = level.getEntities((int)x + 4, (int)y + 4, w - 8, h - 4); + for (int i = 0; i < entities.size(); i++) { + Entity e = entities.get(i); + if (e instanceof Gunner) { + temperature += 10; + if (temperature >= MAX_TEMPERATURE) { + die(); + } + } + e.collideMonster(this); + } + } - public void render(Screen g, Camera camera) { - int xp = (int) x; - int yp = (int) y-10; - g.draw(Art.gremlins[3+(slamTime/10%5==2?1:0)][0], xp, yp); - // FIXME -// g.setColor(Color.BLACK); -// yp+=10; -// g.fillRect(xp + 5, yp - 8, 20, 3); -// g.setColor(Color.RED); -// g.fillRect(xp + 5, yp - 8, (20 * temperature / MAX_TEMPERATURE), 2); - } + public void render (Screen g, Camera camera) { + int xp = (int)x; + int yp = (int)y - 10; + g.draw(Art.gremlins[3 + (slamTime / 10 % 5 == 2 ? 1 : 0)][0], xp, yp); + // FIXME +// g.setColor(Color.BLACK); +// yp+=10; +// g.fillRect(xp + 5, yp - 8, 20, 3); +// g.setColor(Color.RED); +// g.fillRect(xp + 5, yp - 8, (20 * temperature / MAX_TEMPERATURE), 2); + } - public void hitSpikes() { - die(); - } + public void hitSpikes () { + die(); + } - private void die() { - Sound.death.play(); - for (int i = 0; i < 16; i++) { - level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); - } - Sound.boom.play(); - for (int i = 0; i < 32; i++) { - double dir = i * Math.PI * 2 / 8.0; - double xa = Math.sin(dir); - double ya = Math.cos(dir); - double dist = ((i / 8) + 1); - level.add(new Explosion(0, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); - } - remove(); - } + private void die () { + Sound.death.play(); + for (int i = 0; i < 16; i++) { + level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); + } + Sound.boom.play(); + for (int i = 0; i < 32; i++) { + double dir = i * Math.PI * 2 / 8.0; + double xa = Math.sin(dir); + double ya = Math.cos(dir); + double dist = ((i / 8) + 1); + level.add(new Explosion(0, i * 3, x + w / 2 + xa * dist, y + h / 2 + ya * dist, xa, ya)); + } + remove(); + } - public boolean shot(Bullet bullet) { - return true; - } + public boolean shot (Bullet bullet) { + return true; + } - public void explode(Explosion explosion) { - die(); - } + public void explode (Explosion explosion) { + die(); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Player.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Player.java index 15d6289302b..fcb3207f320 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Player.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Player.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.badlogic.gdx.graphics.g2d.TextureRegion; @@ -10,229 +11,229 @@ import com.mojang.metagun.screen.Screen; public class Player extends Entity { - private int dir = 1; - private int yAim = 0; - private int frame = 0; - public int hatCount = 1; - public int damage = 0; - private int noHurtTime = 0; - public int gunLevel = 0; - public boolean readSign = false; - private int shootTime = 0; - - public Player(int x, int y) { - this.x = x; - this.y = y; - w = 8; - h = 18; - bounce = 0; - } - - public void tick() { - } - - public void render(Screen g, Camera camera) { - // g.setColor(Color.GREEN); - int xp = (int) x - (16 - w) / 2; - int yp = (int) y - 2; - // g.fillRect(xp, yp, w, h); - - int stepFrame = frame / 4 % 4; - - TextureRegion[][] sheet = dir == 1 ? Art.player1 : Art.player2; - if (!onGround) { - int yya = (int) Math.round(-ya); - stepFrame = 4; - if (yya < -1) stepFrame = 5; - yp += yya; - } - g.draw(sheet[3 + stepFrame][hatCount > 0 ? 0 : 1], xp, yp); - - - yp += (stepFrame == 3 ? 1 : 0); - for (int i = 1; i < hatCount; i++) { - g.draw(sheet[0][1], xp, yp - i * 2); - } - - if (gunLevel > 0) { - if (!onGround) { - int yya = (int) Math.round(-ya); - if (yya < -1) yya = -1; - if (yya > 1) yya = 1; - yp += yya; - } - g.draw(sheet[1 + yAim][(gunLevel - 1) * 2], xp, yp); - } - } - - public void tick(Input input) { - readSign = true; //onGround && input.buttons[Input.UP] && !input.oldButtons[Input.UP]; - if (noHurtTime > 0) noHurtTime--; - double speed = 0.4; - double aimAngle = -0.2; - yAim = 0; - if (input.buttons[Input.UP]) { - aimAngle -= 0.8; - yAim--; - } - if (input.buttons[Input.DOWN]) { - aimAngle += 0.8; - yAim++; - } - boolean walk = false; - if (input.buttons[Input.LEFT]) { - walk = true; - xa -= speed; - dir = -1; - } - if (input.buttons[Input.RIGHT]) { - walk = true; - xa += speed; - dir = 1; - } - if (walk) frame++; - else frame = 0; - if (input.buttons[Input.JUMP] && !input.oldButtons[Input.JUMP] && onGround) { - Sound.jump.play(); - ya -= 2 + Math.abs(xa) * 0.5; - } - - tryMove(xa, ya); - - xa *= 0.7; - if (ya < 0 && input.buttons[Input.JUMP]) { - ya *= 0.992; - ya += Level.GRAVITY * 0.5; - } else { - ya *= Level.FRICTION; - ya += Level.GRAVITY; - } - - - boolean shooting = false; - if (gunLevel > 0 && input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) shooting = true; - if (gunLevel > 1 && input.buttons[Input.SHOOT] && (!input.oldButtons[Input.SHOOT] || shootTime>0)) { - shooting = shootTime++%3==0; - } else { - shootTime = 0; - } - if (shooting) { - double pow = 3; - Sound.launch.play(); - - double xx = x + w / 2.0 - 2.5 + dir * 7; - double yy = y + h / 2.0 - 2.5 + yAim * 2; - for (int i = 0; i < 4; i++) { - double xAim = Math.cos(aimAngle + 0.2) * dir * pow; - double yAim = Math.sin(aimAngle + 0.2) * pow; - double xxa = xa + xAim * 0.2; - double yya = ya + yAim * 0.2; - level.add(new Spark(xx, yy + (-2 + i) * 0.5, xxa, yya)); - } - double xAim = Math.cos(aimAngle) * dir * pow; - double yAim = Math.sin(aimAngle) * pow; - double xxa = xa + xAim; - double yya = ya + yAim; - if (gunLevel==2) { - xa-=xAim*0.1; - ya-=yAim*0.1; - } - xx = x + w / 2.0 - 2.5; - Stats.instance.shots++; - level.add(new Gunner(xx, yy, xxa, yya)); - } - - if (y < 5) level.transition(0, -1); - if (y > 240 - w + 10 - 5) level.transition(0, 1); - if (x < 0 + 5) level.transition(-1, 0); - if (x > 320 - h + 10 - 5) level.transition(1, 0); - } - - public void hitSpikes() { - die(); - } - - public void die() { - if (removed) return; - if (hatCount > 0) { - level.add(new Hat(x, y - hatCount * 2)); - hatCount--; - } - Sound.death.play(); - for (int i = 0; i < 16; i++) { - level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); - } - Stats.instance.deaths++; - remove(); - } - - public boolean shot(Bullet bullet) { - Sound.pew.play(); - xa += bullet.xa * 0.5; - ya += bullet.ya * 0.5; - for (int i = 0; i < 4; i++) { - double xd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.xa * 3; - double yd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.ya * 3; - level.add(new Gore(bullet.x, bullet.y, xa + xd, ya + yd)); - } - if (noHurtTime != 0) return true; - - if (hatCount > 0) { - while (hatCount>0) { - Hat hat = new Hat(x, y); - hat.ya-=hatCount*0.05; - hat.xxa=(random.nextFloat()-random.nextFloat())*(hatCount-1)*0.5; - hat.time+=hatCount*6; - level.add(hat); - hat.tryMove(0, -hatCount*2); - hatCount--; - } - noHurtTime = 20; - } else { - Sound.oof.play(); - damage++; - noHurtTime = 20; - if (damage == 4) { - Sound.death.play(); - for (int i = 0; i < 16; i++) { - level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); - } - remove(); - } else { - level.add(new PlayerGore(bullet.x, bullet.y)); - } - } - - return true; - } - - public void readSign(Sign sign) { - if (sign.autoRead || readSign) { - sign.autoRead = false; - if (sign.id == 6) { - sign.remove(); - gunLevel = 1; - level.getGun(1); - } - if (sign.id == 15) { - sign.remove(); - gunLevel = 2; - level.getGun(2); - } - level.readSign(sign); - } - sign.remove(); - } - - public void outOfBounds() { - } - - public void explode(Explosion explosion) { - die(); - } - - public void collideMonster(Entity e) { - die(); - } + private int dir = 1; + private int yAim = 0; + private int frame = 0; + public int hatCount = 1; + public int damage = 0; + private int noHurtTime = 0; + public int gunLevel = 0; + public boolean readSign = false; + private int shootTime = 0; + + public Player (int x, int y) { + this.x = x; + this.y = y; + w = 8; + h = 18; + bounce = 0; + } + + public void tick () { + } + + public void render (Screen g, Camera camera) { + // g.setColor(Color.GREEN); + int xp = (int)x - (16 - w) / 2; + int yp = (int)y - 2; + // g.fillRect(xp, yp, w, h); + + int stepFrame = frame / 4 % 4; + + TextureRegion[][] sheet = dir == 1 ? Art.player1 : Art.player2; + if (!onGround) { + int yya = (int)Math.round(-ya); + stepFrame = 4; + if (yya < -1) stepFrame = 5; + yp += yya; + } + g.draw(sheet[3 + stepFrame][hatCount > 0 ? 0 : 1], xp, yp); + + yp += (stepFrame == 3 ? 1 : 0); + for (int i = 1; i < hatCount; i++) { + g.draw(sheet[0][1], xp, yp - i * 2); + } + + if (gunLevel > 0) { + if (!onGround) { + int yya = (int)Math.round(-ya); + if (yya < -1) yya = -1; + if (yya > 1) yya = 1; + yp += yya; + } + g.draw(sheet[1 + yAim][(gunLevel - 1) * 2], xp, yp); + } + } + + public void tick (Input input) { + readSign = true; // onGround && input.buttons[Input.UP] && !input.oldButtons[Input.UP]; + if (noHurtTime > 0) noHurtTime--; + double speed = 0.4; + double aimAngle = -0.2; + yAim = 0; + if (input.buttons[Input.UP]) { + aimAngle -= 0.8; + yAim--; + } + if (input.buttons[Input.DOWN]) { + aimAngle += 0.8; + yAim++; + } + boolean walk = false; + if (input.buttons[Input.LEFT]) { + walk = true; + xa -= speed; + dir = -1; + } + if (input.buttons[Input.RIGHT]) { + walk = true; + xa += speed; + dir = 1; + } + if (walk) + frame++; + else + frame = 0; + if (input.buttons[Input.JUMP] && !input.oldButtons[Input.JUMP] && onGround) { + Sound.jump.play(); + ya -= 2 + Math.abs(xa) * 0.5; + } + + tryMove(xa, ya); + + xa *= 0.7; + if (ya < 0 && input.buttons[Input.JUMP]) { + ya *= 0.992; + ya += Level.GRAVITY * 0.5; + } else { + ya *= Level.FRICTION; + ya += Level.GRAVITY; + } + + boolean shooting = false; + if (gunLevel > 0 && input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) shooting = true; + if (gunLevel > 1 && input.buttons[Input.SHOOT] && (!input.oldButtons[Input.SHOOT] || shootTime > 0)) { + shooting = shootTime++ % 3 == 0; + } else { + shootTime = 0; + } + if (shooting) { + double pow = 3; + Sound.launch.play(); + + double xx = x + w / 2.0 - 2.5 + dir * 7; + double yy = y + h / 2.0 - 2.5 + yAim * 2; + for (int i = 0; i < 4; i++) { + double xAim = Math.cos(aimAngle + 0.2) * dir * pow; + double yAim = Math.sin(aimAngle + 0.2) * pow; + double xxa = xa + xAim * 0.2; + double yya = ya + yAim * 0.2; + level.add(new Spark(xx, yy + (-2 + i) * 0.5, xxa, yya)); + } + double xAim = Math.cos(aimAngle) * dir * pow; + double yAim = Math.sin(aimAngle) * pow; + double xxa = xa + xAim; + double yya = ya + yAim; + if (gunLevel == 2) { + xa -= xAim * 0.1; + ya -= yAim * 0.1; + } + xx = x + w / 2.0 - 2.5; + Stats.instance.shots++; + level.add(new Gunner(xx, yy, xxa, yya)); + } + + if (y < 5) level.transition(0, -1); + if (y > 240 - w + 10 - 5) level.transition(0, 1); + if (x < 0 + 5) level.transition(-1, 0); + if (x > 320 - h + 10 - 5) level.transition(1, 0); + } + + public void hitSpikes () { + die(); + } + + public void die () { + if (removed) return; + if (hatCount > 0) { + level.add(new Hat(x, y - hatCount * 2)); + hatCount--; + } + Sound.death.play(); + for (int i = 0; i < 16; i++) { + level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); + } + Stats.instance.deaths++; + remove(); + } + + public boolean shot (Bullet bullet) { + Sound.pew.play(); + xa += bullet.xa * 0.5; + ya += bullet.ya * 0.5; + for (int i = 0; i < 4; i++) { + double xd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.xa * 3; + double yd = (random.nextDouble() - random.nextDouble()) * 4 - bullet.ya * 3; + level.add(new Gore(bullet.x, bullet.y, xa + xd, ya + yd)); + } + if (noHurtTime != 0) return true; + + if (hatCount > 0) { + while (hatCount > 0) { + Hat hat = new Hat(x, y); + hat.ya -= hatCount * 0.05; + hat.xxa = (random.nextFloat() - random.nextFloat()) * (hatCount - 1) * 0.5; + hat.time += hatCount * 6; + level.add(hat); + hat.tryMove(0, -hatCount * 2); + hatCount--; + } + noHurtTime = 20; + } else { + Sound.oof.play(); + damage++; + noHurtTime = 20; + if (damage == 4) { + Sound.death.play(); + for (int i = 0; i < 16; i++) { + level.add(new PlayerGore(x + random.nextDouble() * w, y + random.nextDouble() * h)); + } + remove(); + } else { + level.add(new PlayerGore(bullet.x, bullet.y)); + } + } + + return true; + } + + public void readSign (Sign sign) { + if (sign.autoRead || readSign) { + sign.autoRead = false; + if (sign.id == 6) { + sign.remove(); + gunLevel = 1; + level.getGun(1); + } + if (sign.id == 15) { + sign.remove(); + gunLevel = 2; + level.getGun(2); + } + level.readSign(sign); + } + sign.remove(); + } + + public void outOfBounds () { + } + + public void explode (Explosion explosion) { + die(); + } + + public void collideMonster (Entity e) { + die(); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/PlayerGore.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/PlayerGore.java index c970637f11e..84e705edf29 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/PlayerGore.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/PlayerGore.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -6,48 +7,48 @@ import com.mojang.metagun.screen.Screen; public class PlayerGore extends Entity { - private int life; - - public PlayerGore(double x, double y) { - this.x = x; - this.y = y; - this.w = 2; - this.h = 2; - bounce = 0.8; - this.xa = 0 + (random.nextDouble() - random.nextDouble()) * 1.5; - this.ya = -1 + (random.nextDouble() - random.nextDouble()) * 1.5; - - life = random.nextInt(90) + 60; - } - - public void tick() { - if (life-- <= 0) remove(); - onGround = false; - tryMove(xa, ya); - - xa *= Level.FRICTION; - ya *= Level.FRICTION; - ya += Level.GRAVITY * 0.5; - level.add(new Gore(x + random.nextDouble(), y + random.nextDouble() - 1, xa, ya)); - } - - protected void hitWall(double xa, double ya) { - this.xa *= 0.9; - this.ya *= 0.9; - } - - public void render(Screen g, Camera camera) { - int xp = (int) x; - int yp = (int) y; - g.draw(Art.guys[6][1], xp, yp); - } - - public void hitSpikes() { - for (int i = 0; i < 4; i++) { - xa = (random.nextFloat()-random.nextFloat())*6; - ya = (random.nextFloat()-random.nextFloat())*6; - level.add(new Gore(x + random.nextDouble(), y + random.nextDouble() - 1, xa, ya)); - } - remove(); - } + private int life; + + public PlayerGore (double x, double y) { + this.x = x; + this.y = y; + this.w = 2; + this.h = 2; + bounce = 0.8; + this.xa = 0 + (random.nextDouble() - random.nextDouble()) * 1.5; + this.ya = -1 + (random.nextDouble() - random.nextDouble()) * 1.5; + + life = random.nextInt(90) + 60; + } + + public void tick () { + if (life-- <= 0) remove(); + onGround = false; + tryMove(xa, ya); + + xa *= Level.FRICTION; + ya *= Level.FRICTION; + ya += Level.GRAVITY * 0.5; + level.add(new Gore(x + random.nextDouble(), y + random.nextDouble() - 1, xa, ya)); + } + + protected void hitWall (double xa, double ya) { + this.xa *= 0.9; + this.ya *= 0.9; + } + + public void render (Screen g, Camera camera) { + int xp = (int)x; + int yp = (int)y; + g.draw(Art.guys[6][1], xp, yp); + } + + public void hitSpikes () { + for (int i = 0; i < 4; i++) { + xa = (random.nextFloat() - random.nextFloat()) * 6; + ya = (random.nextFloat() - random.nextFloat()) * 6; + level.add(new Gore(x + random.nextDouble(), y + random.nextDouble() - 1, xa, ya)); + } + remove(); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Sign.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Sign.java index 0aa9783a183..7758562c48c 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Sign.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Sign.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -5,43 +6,43 @@ import com.mojang.metagun.screen.Screen; public class Sign extends Entity { - public int id; - public boolean autoRead = false; + public int id; + public boolean autoRead = false; - public Sign(int x, int y, int id) { - this.x = x; - this.y = y; - this.w = 6; - this.h = 6; - xa = ya = 0; - this.id = id; - autoRead = id == 1; - if (id==6) autoRead = true; - if (id==15) autoRead = true; - } + public Sign (int x, int y, int id) { + this.x = x; + this.y = y; + this.w = 6; + this.h = 6; + xa = ya = 0; + this.id = id; + autoRead = id == 1; + if (id == 6) autoRead = true; + if (id == 15) autoRead = true; + } - public void tick() { - if (id==6 && level.player.gunLevel>=1) remove(); - if (id==15 && level.player.gunLevel>=2) remove(); - java.util.List entities = level.getEntities((int) x, (int) y, 6, 6); - for (int i = 0; i < entities.size(); i++) { - Entity e = entities.get(i); - if (e instanceof Player) { - Player player = (Player) e; - player.readSign(this); - } - } - } + public void tick () { + if (id == 6 && level.player.gunLevel >= 1) remove(); + if (id == 15 && level.player.gunLevel >= 2) remove(); + java.util.List entities = level.getEntities((int)x, (int)y, 6, 6); + for (int i = 0; i < entities.size(); i++) { + Entity e = entities.get(i); + if (e instanceof Player) { + Player player = (Player)e; + player.readSign(this); + } + } + } - public void render(Screen g, Camera camera) { - if (id==6 && level.player.gunLevel>=1) return; - if (id==15 && level.player.gunLevel>=2) return; - if (id==6) { - g.draw(Art.walls[5][0], (int)x, (int)y); - } else if (id==15) { - g.draw(Art.walls[6][0], (int)x, (int)y); - } else { - g.draw(Art.walls[4][0], (int)x, (int)y); - } - } + public void render (Screen g, Camera camera) { + if (id == 6 && level.player.gunLevel >= 1) return; + if (id == 15 && level.player.gunLevel >= 2) return; + if (id == 6) { + g.draw(Art.walls[5][0], (int)x, (int)y); + } else if (id == 15) { + g.draw(Art.walls[6][0], (int)x, (int)y); + } else { + g.draw(Art.walls[4][0], (int)x, (int)y); + } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Spark.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Spark.java index f40adf9e2af..209d8d1cd2b 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Spark.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/entity/Spark.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.entity; import com.mojang.metagun.Art; @@ -6,38 +7,38 @@ import com.mojang.metagun.screen.Screen; public class Spark extends Entity { - private int life; - - public Spark(double x, double y, double xa, double ya) { - this.x = x; - this.y = y; - this.w = 1; - this.h = 1; - bounce = 0.2; - this.xa = (xa + (random.nextDouble() - random.nextDouble()) * 0.2); - this.ya = (ya + (random.nextDouble() - random.nextDouble()) * 0.2); - - life = random.nextInt(20) + 10; - } - - public void tick() { - if (life-- <= 0) remove(); - onGround = false; - tryMove(xa, ya); - - xa *= 0.999; - ya *= 0.999; - ya += Level.GRAVITY*0.15; - } - - protected void hitWall(double xa, double ya) { - this.xa *= 0.4; - this.ya *= 0.4; - } - - public void render(Screen g, Camera camera) { - int xp = (int) x; - int yp = (int) y; - g.draw(Art.guys[9][1], xp, yp); - } + private int life; + + public Spark (double x, double y, double xa, double ya) { + this.x = x; + this.y = y; + this.w = 1; + this.h = 1; + bounce = 0.2; + this.xa = (xa + (random.nextDouble() - random.nextDouble()) * 0.2); + this.ya = (ya + (random.nextDouble() - random.nextDouble()) * 0.2); + + life = random.nextInt(20) + 10; + } + + public void tick () { + if (life-- <= 0) remove(); + onGround = false; + tryMove(xa, ya); + + xa *= 0.999; + ya *= 0.999; + ya += Level.GRAVITY * 0.15; + } + + protected void hitWall (double xa, double ya) { + this.xa *= 0.4; + this.ya *= 0.4; + } + + public void render (Screen g, Camera camera) { + int xp = (int)x; + int yp = (int)y; + g.draw(Art.guys[9][1], xp, yp); + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Camera.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Camera.java index 927d1a856a8..118e36cb9a6 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Camera.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Camera.java @@ -1,10 +1,11 @@ + package com.mojang.metagun.level; public class Camera { - public int x, y, width, height; - - public Camera(int width, int height) { - this.width = width; - this.height = height; - } -} \ No newline at end of file + public int x, y, width, height; + + public Camera (int width, int height) { + this.width = width; + this.height = height; + } +} diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Level.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Level.java index fe0c0a2d587..bd10aa25bff 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Level.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/level/Level.java @@ -37,13 +37,13 @@ public class Level { // private int xo, yo; private int tick; - @SuppressWarnings("unchecked") public Level (GameScreen screen, int w, int h, int xo, int yo, int xSpawn, int ySpawn) { + @SuppressWarnings("unchecked") + public Level (GameScreen screen, int w, int h, int xo, int yo, int xSpawn, int ySpawn) { this.screen = screen; -// int[] pixels = new int[32 * 24]; +// int[] pixels = new int[32 * 24]; this.xSpawn = xSpawn; this.ySpawn = ySpawn; - // Art.level.getRGB(xo * 31, yo * 23, 32, 24, pixels, 0, 32); walls = new byte[w * h]; @@ -56,7 +56,7 @@ public class Level { entityMap[x + y * w] = new ArrayList(); // int col = pixels[x + y * w] & 0xffffff; - int col = (Art.level.getPixel(x + xo * 31, y + yo * 23) & 0xffffff00) >>> 8; + int col = (Art.level.getPixel(x + xo * 31, y + yo * 23) & 0xffffff00) >>> 8; byte wall = 0; if (col == 0xffffff) @@ -117,8 +117,8 @@ else if (col == 0x83FFFF) { add(e); } walls[x + y * w] = wall; - } - } + } + } player = new Player(this.xSpawn, this.ySpawn); add(player); } @@ -205,7 +205,7 @@ public void render (Screen screen, Camera camera) { matrix.setToTranslation(camera.x, camera.y, 0); screen.spriteBatch.setTransformMatrix(matrix); screen.spriteBatch.begin(); - //g.translate(-camera.x, -camera.y); + // g.translate(-camera.x, -camera.y); int xo = 0; int yo = 0; @@ -243,9 +243,8 @@ public void render (Screen screen, Camera camera) { ximg = 3; } - if(w == 0) - continue; - + if (w == 0) continue; + screen.draw(Art.walls[ximg][yimg], x * 10, y * 10); } } @@ -254,7 +253,7 @@ public void render (Screen screen, Camera camera) { Entity e = entities.get(i); e.render(screen, camera); } - + screen.spriteBatch.end(); } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/ExpositionScreen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/ExpositionScreen.java index 850cda88894..ade61503dc7 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/ExpositionScreen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/ExpositionScreen.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.screen; import java.io.BufferedReader; @@ -10,53 +11,53 @@ import com.mojang.metagun.Input; public class ExpositionScreen extends Screen { - private int time = 0; - - // "1234567890123456789012345678901234567890" - - private List lines = new ArrayList(); - - public ExpositionScreen() { - try { - BufferedReader br = new BufferedReader(new InputStreamReader(Gdx.files.internal("res/exposition.txt").read())); - - String line = ""; - while ((line = br.readLine()) != null) { - lines.add(line); - } - br.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public void render() { - int w = -Art.bg.getRegionHeight(); - spriteBatch.begin(); - draw(Art.bg, 0, -(time / 8 % w)); - draw(Art.bg, 0, -(time / 8 % w) + w); - - int yo = time / 4; - for (int y = 0; y <= 240 / 6; y++) { - int yl = yo / 6 - 240 / 6+y; - if (yl >= 0 && yl < lines.size()) { - drawString(lines.get(yl), (320 - 40 * 6)/2, y * 6 - yo % 6); - } - } - spriteBatch.end(); - } - - public void tick(Input input) { - time++; - if (time / 4 > lines.size() * 6 + 250) { - setScreen(new TitleScreen()); - } - if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT] || Gdx.input.isTouched()) { - setScreen(new TitleScreen()); - } - if (input.buttons[Input.ESCAPE] && !input.oldButtons[Input.ESCAPE]) { - setScreen(new TitleScreen()); - } - } + private int time = 0; + + // "1234567890123456789012345678901234567890" + + private List lines = new ArrayList(); + + public ExpositionScreen () { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(Gdx.files.internal("res/exposition.txt").read())); + + String line = ""; + while ((line = br.readLine()) != null) { + lines.add(line); + } + br.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public void render () { + int w = -Art.bg.getRegionHeight(); + spriteBatch.begin(); + draw(Art.bg, 0, -(time / 8 % w)); + draw(Art.bg, 0, -(time / 8 % w) + w); + + int yo = time / 4; + for (int y = 0; y <= 240 / 6; y++) { + int yl = yo / 6 - 240 / 6 + y; + if (yl >= 0 && yl < lines.size()) { + drawString(lines.get(yl), (320 - 40 * 6) / 2, y * 6 - yo % 6); + } + } + spriteBatch.end(); + } + + public void tick (Input input) { + time++; + if (time / 4 > lines.size() * 6 + 250) { + setScreen(new TitleScreen()); + } + if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT] || Gdx.input.isTouched()) { + setScreen(new TitleScreen()); + } + if (input.buttons[Input.ESCAPE] && !input.oldButtons[Input.ESCAPE]) { + setScreen(new TitleScreen()); + } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/GameScreen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/GameScreen.java index 1b0c587b7cc..934cc1120b8 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/GameScreen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/GameScreen.java @@ -74,25 +74,25 @@ public void transition (int xa, int ya) { public void render () { spriteBatch.begin(); -// draw(Art.bg, -xLevel * 160, -yLevel * 120); +// draw(Art.bg, -xLevel * 160, -yLevel * 120); draw(Art.bg, 0, 0); spriteBatch.end(); level.render(this, camera); - + spriteBatch.begin(); if (mayRespawn) { String msg = "PRESS X TO TRY AGAIN"; drawString(msg, 160 - msg.length() * 3, 120 - 3); } - if(Gdx.app.getType() == ApplicationType.Android) { - draw(Art.buttons[0][0], 0, 240-32); - draw(Art.buttons[1][0], 32, 240-32); - - draw(Art.buttons[4][0], 160-32, 240-32); - draw(Art.buttons[5][0], 160, 240-32); - - draw(Art.buttons[2][0], 320-64, 240-32); - draw(Art.buttons[3][0], 320-32, 240-32); + if (Gdx.app.getType() == ApplicationType.Android) { + draw(Art.buttons[0][0], 0, 240 - 32); + draw(Art.buttons[1][0], 32, 240 - 32); + + draw(Art.buttons[4][0], 160 - 32, 240 - 32); + draw(Art.buttons[5][0], 160, 240 - 32); + + draw(Art.buttons[2][0], 320 - 64, 240 - 32); + draw(Art.buttons[3][0], 320 - 32, 240 - 32); } spriteBatch.end(); } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/LevelTransitionScreen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/LevelTransitionScreen.java index c63a5f32024..264fbc219b4 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/LevelTransitionScreen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/LevelTransitionScreen.java @@ -31,23 +31,24 @@ public void tick (Input input) { setScreen(parent); } } - - Camera c = new Camera(320, 240); - public void render () { + + Camera c = new Camera(320, 240); + + public void render () { double pow = time / (double)TRANSITION_DURATION; - + spriteBatch.getTransformMatrix().idt(); - spriteBatch.begin(); -// draw(Art.bg, -xLevel * 160 - (int)(xa * 160 * pow), -yLevel * 120 - (int)(ya * 120 * pow)); + spriteBatch.begin(); +// draw(Art.bg, -xLevel * 160 - (int)(xa * 160 * pow), -yLevel * 120 - (int)(ya * 120 * pow)); draw(Art.bg, 0, 0); spriteBatch.end(); - + c.x = (int)(-xa * 320 * pow); - c.y = (int)(-ya * 240 * pow); - level1.render(this, c); - - c.x = (int)(xa * 320 * (1-pow)); - c.y = (int)(ya * 240 * (1-pow)); - level2.render(this, c); + c.y = (int)(-ya * 240 * pow); + level1.render(this, c); + + c.x = (int)(xa * 320 * (1 - pow)); + c.y = (int)(ya * 240 * (1 - pow)); + level2.render(this, c); } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/PauseScreen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/PauseScreen.java index 9aa9ccfa741..5cfb31d8ac6 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/PauseScreen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/PauseScreen.java @@ -1,79 +1,80 @@ + package com.mojang.metagun.screen; import com.mojang.metagun.Art; import com.mojang.metagun.Input; public class PauseScreen extends Screen { - private GameScreen parent; - private int selected = 0; + private GameScreen parent; + private int selected = 0; + + private String[] options = {"BACK TO GAME", "AUTOMORTIS", "QUIT TO TITLE"}; - private String[] options = { "BACK TO GAME", "AUTOMORTIS", "QUIT TO TITLE" }; + public PauseScreen (GameScreen parent) { + this.parent = parent; + } - public PauseScreen(GameScreen parent) { - this.parent = parent; - } + public void render () { + parent.render(); - public void render() { - parent.render(); - - spriteBatch.begin(); - int xs = 0; - int ys = options.length; - for (int y = 0; y < options.length; y++) { - int s = options[y].length(); - if (s > xs) xs = s; - } - xs += 1; - int xp = 40; - int yp = 40; - for (int x = 0 - 1; x < xs + 1; x++) { - for (int y = 0 - 1; y < ys + 1; y++) { - int xf = 1; - int yf = 12; - if (x < 0) xf--; - if (y < 0) yf--; - if (x >= xs) xf++; - if (y >= ys) yf++; - draw(Art.guys[xf][yf], xp + x * 6, yp + y * 6); - } - } - for (int y = 0; y < options.length; y++) { - if (y == selected) { - drawString("+", xp, yp + y * 6); - } - drawString(options[y], xp + 6, yp + y * 6); - } - spriteBatch.end(); - } + spriteBatch.begin(); + int xs = 0; + int ys = options.length; + for (int y = 0; y < options.length; y++) { + int s = options[y].length(); + if (s > xs) xs = s; + } + xs += 1; + int xp = 40; + int yp = 40; + for (int x = 0 - 1; x < xs + 1; x++) { + for (int y = 0 - 1; y < ys + 1; y++) { + int xf = 1; + int yf = 12; + if (x < 0) xf--; + if (y < 0) yf--; + if (x >= xs) xf++; + if (y >= ys) yf++; + draw(Art.guys[xf][yf], xp + x * 6, yp + y * 6); + } + } + for (int y = 0; y < options.length; y++) { + if (y == selected) { + drawString("+", xp, yp + y * 6); + } + drawString(options[y], xp + 6, yp + y * 6); + } + spriteBatch.end(); + } - public void tick(Input input) { - if (!input.oldButtons[Input.ESCAPE] && input.buttons[Input.ESCAPE]) { - setScreen(parent); - return; - } - if (input.buttons[Input.UP] && !input.oldButtons[Input.UP]) { - selected--; - if (selected < 0) selected += options.length; - } - if (input.buttons[Input.DOWN] && !input.oldButtons[Input.DOWN]) { - selected++; - if (selected >= options.length) selected -= options.length; - } - if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { - if (selected==0) { - setScreen(parent); - } else if (selected==1) { - parent.level.player.die(); - setScreen(parent); - } else if (selected==2) { - setScreen(new TitleScreen()); - } else if (selected==3) { - setScreen(new WinScreen()); - } - } - // if (delay>0) delay--; - // if (delay==0 && input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { - // setScreen(parent); - // } - } + public void tick (Input input) { + if (!input.oldButtons[Input.ESCAPE] && input.buttons[Input.ESCAPE]) { + setScreen(parent); + return; + } + if (input.buttons[Input.UP] && !input.oldButtons[Input.UP]) { + selected--; + if (selected < 0) selected += options.length; + } + if (input.buttons[Input.DOWN] && !input.oldButtons[Input.DOWN]) { + selected++; + if (selected >= options.length) selected -= options.length; + } + if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { + if (selected == 0) { + setScreen(parent); + } else if (selected == 1) { + parent.level.player.die(); + setScreen(parent); + } else if (selected == 2) { + setScreen(new TitleScreen()); + } else if (selected == 3) { + setScreen(new WinScreen()); + } + } + // if (delay>0) delay--; + // if (delay==0 && input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { + // setScreen(parent); + // } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/Screen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/Screen.java index a99fde9d71a..bd5dfa1a4da 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/Screen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/Screen.java @@ -36,7 +36,7 @@ protected void setScreen (Screen screen) { public void draw (TextureRegion region, int x, int y) { int width = region.getRegionWidth(); - if(width <0) width = -width; + if (width < 0) width = -width; spriteBatch.draw(region, x, y, width, -region.getRegionHeight()); } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/SignReadScreen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/SignReadScreen.java index 503956637a2..369d7473999 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/SignReadScreen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/SignReadScreen.java @@ -1,205 +1,81 @@ + package com.mojang.metagun.screen; -import com.badlogic.gdx.Gdx; import com.mojang.metagun.Art; import com.mojang.metagun.Input; public class SignReadScreen extends Screen { - private Screen parent; - - private String[][] signs = { - { - "READING", - "", - "PRESS UP TO READ SIGNS" - }, - { - "JUMPING", - "", - "PRESS Z TO JUMP", - "YOU CAN JUMP HIGHER BY", - "GETTING A RUNNING START", - "OR HOLDING DOWN Z", - }, - { - "PROGRESSING", - "", - "LEAVE A ROOM THROUGH ANY", - "EXIT TO CONTINUE YOUR", - "ADVENTURE", - }, - { - "DYING", - "", - "IF YOU DIE, YOU RESTART", - "AT THE BEGINNING OF THE", - "CURRENT ROOM", - }, - { - "DODGING", - "", - "THE GUNNERS DON'T LIKE YOU", - "AND SHOOT AT YOU.", - "IT WOULD BE WISE TO STAY AWAY", - }, - { - "THE LAUNCHER", - "", - "AS YOU PICK UP THE LAUNCHER,", - "YOU REALIZE IT'S NOT YOUR", - "AVERAGE LAUNCHER.", - "", - "PRESS UP AND DOWN TO AIM", - "PRESS X TO FIRE THE LAUNCHER", - }, - { - "JONESING", - "", - "DON'T FORGET YOUR FEDORA!", - }, - { - "EXPLODING", - "", - "TNT BLOCKS ARE HIGHLY", - "EXPLOSIVE, AND WILL", - "REACT POORLY TO BEING", - "SHOT.", - }, - { - "PUSHING", - "", - "THE CAMARADERIE BOX IS", - "SOMETHING SOMETHING", - "", - "IT'S FROM PORTAL.", - }, - { - "BATTLING", - "", - "THE GREMLIN IS LARGE", - "AND IN YOUR WAY.", - "OVERHEAT IT TO DESTROY", - "IT AND CLAIM YOUR PRIZE", - }, - { - "EVADING", - "", - "THE GUNNERS SHOTS WILL", - "PASS THROUGH GLASS.", - "YOU, HOWEVER, WILL NOT", - }, - { - "SWEATING", - "", - "THESE SLIGHTLY MORE", - "SOPHISTICATED GREMLINS", - "HAVE LEARNED A NEW", - "TRICK", - }, - { - "CONVEYING", - "", - "TIME TO BURN OFF SOME", - "FAT AND HAVE FUN WHILE", - "DOING IT!", - }, - { - "BOSSFIGHTING", - "", - "BEHIND THIS DOOR, MEGAN", - "AWAITS! WHO IS MEGAN?", - "ARE YOU MEGAN?", - }, - { - "THE NEW LAUNCHER", - "", - "WELL, THIS IS BAD." - }, - { - "FEEDING", - "", - "THE JABBERWOCKY IS", - "HUNGRY, AND WILL EAT", - "WAY MORE THAN IT SHOULD", - "", - "PLEASE DO NOT FEED!", - }, - { - "HOVERING", - "", - "THE RECOIL ON THE NEW", - "LAUNCHER SURE IS", - "POWERFUL!", - }, - { - "FLYING", - "", - "SERIOUSLY, THE RECOIL", - "IS OUT OF THIS WORLD!", - }, - { - "WINNING", - "", - "YOUR FINAL CHALLENGE", - "IS RIGHT DOWN THIS", - "HALLWAY.", - }, - { - "FRESHERERST", - "", - "BIG ADAM, GIANT SISTER.", - "IT IS KNOWN BY MANY NAMES", - "BUT JUDITH 4HRPG BLUEBERRY.", - "", - "FISSION MAILED!", - }, - }; - - private int delay = 15; - private int id; - public SignReadScreen(Screen parent, int id) { - this.parent = parent; - this.id = id; - } - - public void render() { - parent.render(); - spriteBatch.begin(); - int xs = 0; - int ys = signs[id].length+3; - for (int y=0; yxs) xs = s; - } - int xp = 160-xs*3; - int yp = 120-ys*3; - for (int x=0-1; x=xs) xf++; - if (y>=ys) yf++; - draw(Art.guys[xf][yf], xp+x*6, yp+y*6); - } - } - for (int y=0; y0) delay--; - if (delay==0 && input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { - setScreen(parent); - } - } + private Screen parent; + + private String[][] signs = { + {"READING", "", "PRESS UP TO READ SIGNS"}, + {"JUMPING", "", "PRESS Z TO JUMP", "YOU CAN JUMP HIGHER BY", "GETTING A RUNNING START", "OR HOLDING DOWN Z",}, + {"PROGRESSING", "", "LEAVE A ROOM THROUGH ANY", "EXIT TO CONTINUE YOUR", "ADVENTURE",}, + {"DYING", "", "IF YOU DIE, YOU RESTART", "AT THE BEGINNING OF THE", "CURRENT ROOM",}, + {"DODGING", "", "THE GUNNERS DON'T LIKE YOU", "AND SHOOT AT YOU.", "IT WOULD BE WISE TO STAY AWAY",}, + {"THE LAUNCHER", "", "AS YOU PICK UP THE LAUNCHER,", "YOU REALIZE IT'S NOT YOUR", "AVERAGE LAUNCHER.", "", + "PRESS UP AND DOWN TO AIM", "PRESS X TO FIRE THE LAUNCHER",}, + {"JONESING", "", "DON'T FORGET YOUR FEDORA!",}, + {"EXPLODING", "", "TNT BLOCKS ARE HIGHLY", "EXPLOSIVE, AND WILL", "REACT POORLY TO BEING", "SHOT.",}, + {"PUSHING", "", "THE CAMARADERIE BOX IS", "SOMETHING SOMETHING", "", "IT'S FROM PORTAL.",}, + {"BATTLING", "", "THE GREMLIN IS LARGE", "AND IN YOUR WAY.", "OVERHEAT IT TO DESTROY", "IT AND CLAIM YOUR PRIZE",}, + {"EVADING", "", "THE GUNNERS SHOTS WILL", "PASS THROUGH GLASS.", "YOU, HOWEVER, WILL NOT",}, + {"SWEATING", "", "THESE SLIGHTLY MORE", "SOPHISTICATED GREMLINS", "HAVE LEARNED A NEW", "TRICK",}, + {"CONVEYING", "", "TIME TO BURN OFF SOME", "FAT AND HAVE FUN WHILE", "DOING IT!",}, + {"BOSSFIGHTING", "", "BEHIND THIS DOOR, MEGAN", "AWAITS! WHO IS MEGAN?", "ARE YOU MEGAN?",}, + {"THE NEW LAUNCHER", "", "WELL, THIS IS BAD."}, + {"FEEDING", "", "THE JABBERWOCKY IS", "HUNGRY, AND WILL EAT", "WAY MORE THAN IT SHOULD", "", "PLEASE DO NOT FEED!",}, + {"HOVERING", "", "THE RECOIL ON THE NEW", "LAUNCHER SURE IS", "POWERFUL!",}, + {"FLYING", "", "SERIOUSLY, THE RECOIL", "IS OUT OF THIS WORLD!",}, + {"WINNING", "", "YOUR FINAL CHALLENGE", "IS RIGHT DOWN THIS", "HALLWAY.",}, + {"FRESHERERST", "", "BIG ADAM, GIANT SISTER.", "IT IS KNOWN BY MANY NAMES", "BUT JUDITH 4HRPG BLUEBERRY.", "", + "FISSION MAILED!",},}; + + private int delay = 15; + private int id; + + public SignReadScreen (Screen parent, int id) { + this.parent = parent; + this.id = id; + } + + public void render () { + parent.render(); + spriteBatch.begin(); + int xs = 0; + int ys = signs[id].length + 3; + for (int y = 0; y < signs[id].length; y++) { + int s = signs[id][y].length(); + if (s > xs) xs = s; + } + int xp = 160 - xs * 3; + int yp = 120 - ys * 3; + for (int x = 0 - 1; x < xs + 1; x++) { + for (int y = 0 - 1; y < ys + 1; y++) { + int xf = 1; + int yf = 12; + if (x < 0) xf--; + if (y < 0) yf--; + if (x >= xs) xf++; + if (y >= ys) yf++; + draw(Art.guys[xf][yf], xp + x * 6, yp + y * 6); + } + } + for (int y = 0; y < signs[id].length; y++) { + drawString(signs[id][y], xp, yp + y * 6); + } + if (delay == 0) drawString("PRESS X", xp + (xs - 8) * 6, yp + (signs[id].length + 2) * 6); + spriteBatch.end(); + } + + public void tick (Input input) { + if (!input.oldButtons[Input.ESCAPE] && input.buttons[Input.ESCAPE]) { + setScreen(parent); + return; + } + if (delay > 0) delay--; + if (delay == 0 && input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { + setScreen(parent); + } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/TitleScreen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/TitleScreen.java index a5cd49d1fb5..f30ca84951f 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/TitleScreen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/TitleScreen.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.screen; import com.badlogic.gdx.Application.ApplicationType; @@ -7,41 +8,41 @@ import com.mojang.metagun.Sound; public class TitleScreen extends Screen { - private int time = 0; - - public void render() { - int yOffs = 480 - time * 2; - if (yOffs < 0) yOffs = 0; - spriteBatch.begin(); - draw(Art.bg, 0, 0); - draw(Art.titleScreen, 0, -yOffs); - if (time > 240) { - String msg = null; - if(Gdx.app.getType()==ApplicationType.Android) - msg = "TOUCH TO START"; - else - msg = "PRESS X TO START"; - drawString(msg, 160 - msg.length() * 3, 140 - 3 - (int) (Math.abs(Math.sin(time * 0.1) * 10))); + private int time = 0; + + public void render () { + int yOffs = 480 - time * 2; + if (yOffs < 0) yOffs = 0; + spriteBatch.begin(); + draw(Art.bg, 0, 0); + draw(Art.titleScreen, 0, -yOffs); + if (time > 240) { + String msg = null; + if (Gdx.app.getType() == ApplicationType.Android) + msg = "TOUCH TO START"; + else + msg = "PRESS X TO START"; + drawString(msg, 160 - msg.length() * 3, 140 - 3 - (int)(Math.abs(Math.sin(time * 0.1) * 10))); - } - if (time >=0) { - String msg = "COPYRIGHT MOJANG 2010"; - drawString(msg, 2, 240-6-2); - } - spriteBatch.end(); - } + } + if (time >= 0) { + String msg = "COPYRIGHT MOJANG 2010"; + drawString(msg, 2, 240 - 6 - 2); + } + spriteBatch.end(); + } - public void tick(Input input) { - time++; - if (time > 240) { - if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT] || Gdx.input.isTouched()) { - Sound.startgame.play(); - setScreen(new GameScreen()); - input.releaseAllKeys(); - } - } - if (time > 60*10) { - setScreen(new ExpositionScreen()); - } - } + public void tick (Input input) { + time++; + if (time > 240) { + if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT] || Gdx.input.isTouched()) { + Sound.startgame.play(); + setScreen(new GameScreen()); + input.releaseAllKeys(); + } + } + if (time > 60 * 10) { + setScreen(new ExpositionScreen()); + } + } } diff --git a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/WinScreen.java b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/WinScreen.java index 9bb3579d1a2..e5dcf7267ed 100644 --- a/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/WinScreen.java +++ b/demos/metagun/metagun-desktop/src/com/mojang/metagun/screen/WinScreen.java @@ -1,3 +1,4 @@ + package com.mojang.metagun.screen; import com.mojang.metagun.Art; @@ -5,67 +6,67 @@ import com.mojang.metagun.Stats; public class WinScreen extends Screen { - private int time = 0; - - public void render() { - spriteBatch.begin(); - int w = 240 * 8; //Art.bg.getHeight(); - draw(Art.bg, 0, -(time*2%w)); - draw(Art.bg, 0, -(time*2%w)+w); + private int time = 0; + + public void render () { + spriteBatch.begin(); + int w = 240 * 8; // Art.bg.getHeight(); + draw(Art.bg, 0, -(time * 2 % w)); + draw(Art.bg, 0, -(time * 2 % w) + w); + + int offs0 = 500 - time * 10; + if (offs0 < 0) offs0 = 0; + int offs1 = 1200 - time * 16; + if (offs1 < 0) offs1 = 0; + int yOffs = 600 - time * 5; + if (yOffs < -120) yOffs = -120; + if (yOffs > 0) yOffs = 0; + draw(Art.winScreen1, offs0, yOffs + 30); + draw(Art.winScreen2, -offs1, yOffs * 2 / 3 + 30); + + int tt = time - (60 * 2 + 30); + int yo = 130; + int xo = 120 - 8 * 3; + if (tt >= 0) { + drawString(" TIME: " + Stats.instance.getTimeString(), xo, yo + 0 * 6); + drawString(" DEATHS: " + Stats.instance.deaths, xo, yo + 1 * 6); + drawString(" FEDORAS: " + Stats.instance.hats + "/" + 7, xo, yo + 2 * 6); + drawString("SHOTS FIRED: " + Stats.instance.shots, xo, yo + 3 * 6); + drawString("FINAL SCORE: " + timeScale(Stats.instance.getFinalScore(), tt - 30 * 5), xo, yo + 5 * 6); + + drawString(timeHideScale(Stats.instance.getSpeedScore(), tt - 30 * 1), xo + 20 * 6, yo + 0 * 6); + drawString(timeHideScale(Stats.instance.getDeathScore(), tt - 30 * 2), xo + 20 * 6, yo + 1 * 6); + drawString(timeHideScale(Stats.instance.getHatScore(), tt - 30 * 3), xo + 20 * 6, yo + 2 * 6); + drawString(timeHideScale(Stats.instance.getShotScore(), tt - 30 * 4), xo + 20 * 6, yo + 3 * 6); + } + + if (time > 60 * 7 && (time / 30 % 2 == 0)) { + String msg = "PRESS X TO RESET THE GAME"; + drawString(msg, 160 - msg.length() * 3, yo + 10 * 6); + } + spriteBatch.end(); + } - int offs0 = 500-time*10; - if (offs0<0) offs0=0; - int offs1 = 1200-time*16; - if (offs1<0) offs1=0; - int yOffs = 600-time*5; - if (yOffs<-120) yOffs = -120; - if (yOffs>0) yOffs = 0; - draw(Art.winScreen1, offs0, yOffs+30); - draw(Art.winScreen2, -offs1, yOffs*2/3+30); - - int tt = time-(60*2+30); - int yo = 130; - int xo = 120-8*3; - if (tt>=0) { - drawString(" TIME: "+Stats.instance.getTimeString(), xo, yo+0*6); - drawString(" DEATHS: "+Stats.instance.deaths, xo, yo+1*6); - drawString(" FEDORAS: "+Stats.instance.hats+"/"+7, xo, yo+2*6); - drawString("SHOTS FIRED: "+Stats.instance.shots, xo, yo+3*6); - drawString("FINAL SCORE: "+timeScale(Stats.instance.getFinalScore(), tt-30*5), xo, yo+5*6); + private String timeHideScale (int val, int time) { + if (time < 10) return ""; +// if (time>60+60) return ""; + if (time < 0) time = 0; + if (time > 60) time = 60; + return "+" + val * time / 60; + } - drawString(timeHideScale(Stats.instance.getSpeedScore(), tt-30*1), xo+20*6, yo+0*6); - drawString(timeHideScale(Stats.instance.getDeathScore(), tt-30*2), xo+20*6, yo+1*6); - drawString(timeHideScale(Stats.instance.getHatScore(), tt-30*3), xo+20*6, yo+2*6); - drawString(timeHideScale(Stats.instance.getShotScore(), tt-30*4), xo+20*6, yo+3*6); - } - - if (time>60*7 && (time/30%2==0)) { - String msg = "PRESS X TO RESET THE GAME"; - drawString(msg, 160-msg.length()*3, yo+10*6); - } - spriteBatch.end(); - } - - private String timeHideScale(int val, int time) { - if (time<10) return ""; -// if (time>60+60) return ""; - if (time<0) time = 0; - if (time>60) time = 60; - return "+"+val*time/60; - } + private String timeScale (int val, int time) { + if (time < 0) time = 0; + if (time > 60) time = 60; + return "" + val * time / 60; + } - private String timeScale(int val, int time) { - if (time<0) time = 0; - if (time>60) time = 60; - return ""+val*time/60; - } - - public void tick(Input input) { - time++; - if (time>60*7) { - if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { - setScreen(new TitleScreen()); - } - } - } + public void tick (Input input) { + time++; + if (time > 60 * 7) { + if (input.buttons[Input.SHOOT] && !input.oldButtons[Input.SHOOT]) { + setScreen(new TitleScreen()); + } + } + } } diff --git a/demos/returntomarchfeld/rtm-android/src/com/badlogic/rtm/Rtm.java b/demos/returntomarchfeld/rtm-android/src/com/badlogic/rtm/Rtm.java index 9d33493d5e7..2e89d281a99 100644 --- a/demos/returntomarchfeld/rtm-android/src/com/badlogic/rtm/Rtm.java +++ b/demos/returntomarchfeld/rtm-android/src/com/badlogic/rtm/Rtm.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.rtm; import android.content.pm.ActivityInfo; @@ -21,7 +22,8 @@ import com.badlogic.gdx.backends.android.AndroidApplication; public class Rtm extends AndroidApplication { - @Override public void onCreate (Bundle savedInstanceState) { + @Override + public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); initialize(new LevelRenderer(), false); diff --git a/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/LevelRenderer.java b/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/LevelRenderer.java index cbd949f7216..7b8675469ee 100644 --- a/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/LevelRenderer.java +++ b/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/LevelRenderer.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.rtm; import java.io.BufferedReader; @@ -46,10 +47,11 @@ public class LevelRenderer implements ApplicationListener { ImmediateModeRenderer10 renderer; float angle = -90; - @Override public void create () { + @Override + public void create () { camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.near = 1; - camera.far = 2000; + camera.far = 2000; batch = new SpriteBatch(); font = new BitmapFont(); @@ -180,17 +182,19 @@ private void load () { } } - @Override public void resume () { + @Override + public void resume () { } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.gl10; 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_TEXTURE_2D); - + camera.update(); camera.apply(gl); @@ -232,15 +236,18 @@ private void processInput () { camera.direction.set((float)Math.cos(Math.toRadians(angle)), 0, (float)Math.sin(Math.toRadians(angle))); } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } - @Override public void pause () { + @Override + public void pause () { } - @Override public void dispose () { + @Override + public void dispose () { } } diff --git a/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/RtmDesktop.java b/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/RtmDesktop.java index 58caf4115db..7a24ed5accf 100644 --- a/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/RtmDesktop.java +++ b/demos/returntomarchfeld/rtm/src/com/badlogic/rtm/RtmDesktop.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.rtm; import com.badlogic.gdx.backends.jogl.JoglApplication; diff --git a/demos/superjumper/superjumper-android/src/com/badlogicgames/superjumper/SuperJumperAndroid.java b/demos/superjumper/superjumper-android/src/com/badlogicgames/superjumper/SuperJumperAndroid.java index db3b8983174..00ee7ea4157 100644 --- a/demos/superjumper/superjumper-android/src/com/badlogicgames/superjumper/SuperJumperAndroid.java +++ b/demos/superjumper/superjumper-android/src/com/badlogicgames/superjumper/SuperJumperAndroid.java @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -import com.badlogicgames.superjumper.SuperJumper; public class SuperJumperAndroid extends AndroidApplication { - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - initialize(new SuperJumper(), false); - } -} \ No newline at end of file + /** Called when the activity is first created. */ + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + initialize(new SuperJumper(), false); + } +} diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Animation.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Animation.java index c802e911544..4985a588f9d 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Animation.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Animation.java @@ -13,31 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.graphics.g2d.TextureRegion; - public class Animation { - public static final int ANIMATION_LOOPING = 0; - public static final int ANIMATION_NONLOOPING = 1; - - final TextureRegion[] keyFrames; - final float frameDuration; - - public Animation(float frameDuration, TextureRegion ... keyFrames) { - this.frameDuration = frameDuration; - this.keyFrames = keyFrames; - } - - public TextureRegion getKeyFrame(float stateTime, int mode) { - int frameNumber = (int)(stateTime / frameDuration); - - if(mode == ANIMATION_NONLOOPING) { - frameNumber = Math.min(keyFrames.length-1, frameNumber); - } else { - frameNumber = frameNumber % keyFrames.length; - } - return keyFrames[frameNumber]; - } + public static final int ANIMATION_LOOPING = 0; + public static final int ANIMATION_NONLOOPING = 1; + + final TextureRegion[] keyFrames; + final float frameDuration; + + public Animation (float frameDuration, TextureRegion... keyFrames) { + this.frameDuration = frameDuration; + this.keyFrames = keyFrames; + } + + public TextureRegion getKeyFrame (float stateTime, int mode) { + int frameNumber = (int)(stateTime / frameDuration); + + if (mode == ANIMATION_NONLOOPING) { + frameNumber = Math.min(keyFrames.length - 1, frameNumber); + } else { + frameNumber = frameNumber % keyFrames.length; + } + return keyFrames[frameNumber]; + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Assets.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Assets.java index 1cbb56c45a6..97c85299d81 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Assets.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Assets.java @@ -13,110 +13,95 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; 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.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class Assets { - public static Texture background; - public static TextureRegion backgroundRegion; - - public static Texture items; - public static TextureRegion mainMenu; - public static TextureRegion pauseMenu; - public static TextureRegion ready; - public static TextureRegion gameOver; - public static TextureRegion highScoresRegion; - public static TextureRegion logo; - public static TextureRegion soundOn; - public static TextureRegion soundOff; - public static TextureRegion arrow; - public static TextureRegion pause; - public static TextureRegion spring; - public static TextureRegion castle; - public static Animation coinAnim; - public static Animation bobJump; - public static Animation bobFall; - public static TextureRegion bobHit; - public static Animation squirrelFly; - public static TextureRegion platform; - public static Animation brakingPlatform; - public static BitmapFont font; - - public static Music music; - public static Sound jumpSound; - public static Sound highJumpSound; - public static Sound hitSound; - public static Sound coinSound; - public static Sound clickSound; - - public static Texture loadTexture(String file) { - return new Texture(Gdx.files.internal(file)); - } - - public static void load() { - background = loadTexture("data/background.png"); - backgroundRegion = new TextureRegion(background, 0, 0, 320, 480); - - items = loadTexture("data/items.png"); - mainMenu = new TextureRegion(items, 0, 224, 300, 110); - pauseMenu = new TextureRegion(items, 224, 128, 192, 96); - ready = new TextureRegion(items, 320, 224, 192, 32); - gameOver = new TextureRegion(items, 352, 256, 160, 96); - highScoresRegion = new TextureRegion(Assets.items, 0, 257, 300, 110 / 3); - logo = new TextureRegion(items, 0, 352, 274, 142); - soundOff = new TextureRegion(items, 0, 0, 64, 64); - soundOn = new TextureRegion(items, 64, 0, 64, 64); - arrow = new TextureRegion(items, 0, 64, 64, 64); - pause = new TextureRegion(items, 64, 64, 64, 64); - - spring = new TextureRegion(items, 128, 0, 32, 32); - castle = new TextureRegion(items, 128, 64, 64, 64); - coinAnim = new Animation(0.2f, - new TextureRegion(items, 128, 32, 32, 32), - new TextureRegion(items, 160, 32, 32, 32), - new TextureRegion(items, 192, 32, 32, 32), - new TextureRegion(items, 160, 32, 32, 32)); - bobJump = new Animation(0.2f, - new TextureRegion(items, 0, 128, 32, 32), - new TextureRegion(items, 32, 128, 32, 32)); - bobFall = new Animation(0.2f, - new TextureRegion(items, 64, 128, 32, 32), - new TextureRegion(items, 96, 128, 32, 32)); - bobHit = new TextureRegion(items, 128, 128, 32, 32); - squirrelFly = new Animation(0.2f, - new TextureRegion(items, 0, 160, 32, 32), - new TextureRegion(items, 32, 160, 32, 32)); - platform = new TextureRegion(items, 64, 160, 64, 16); - brakingPlatform = new Animation(0.2f, - new TextureRegion(items, 64, 160, 64, 16), - new TextureRegion(items, 64, 176, 64, 16), - new TextureRegion(items, 64, 192, 64, 16), - new TextureRegion(items, 64, 208, 64, 16)); - - font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); - - music = Gdx.audio.newMusic(Gdx.files.internal("data/music.mp3")); - music.setLooping(true); - music.setVolume(0.5f); - if(Settings.soundEnabled) - music.play(); - jumpSound = Gdx.audio.newSound(Gdx.files.internal("data/jump.ogg")); - highJumpSound = Gdx.audio.newSound(Gdx.files.internal("data/highjump.ogg")); - hitSound = Gdx.audio.newSound(Gdx.files.internal("data/hit.ogg")); - coinSound = Gdx.audio.newSound(Gdx.files.internal("data/coin.ogg")); - clickSound = Gdx.audio.newSound(Gdx.files.internal("data/click.ogg")); - } - - public static void playSound(Sound sound) { - if(Settings.soundEnabled) - sound.play(1); - } + public static Texture background; + public static TextureRegion backgroundRegion; + + public static Texture items; + public static TextureRegion mainMenu; + public static TextureRegion pauseMenu; + public static TextureRegion ready; + public static TextureRegion gameOver; + public static TextureRegion highScoresRegion; + public static TextureRegion logo; + public static TextureRegion soundOn; + public static TextureRegion soundOff; + public static TextureRegion arrow; + public static TextureRegion pause; + public static TextureRegion spring; + public static TextureRegion castle; + public static Animation coinAnim; + public static Animation bobJump; + public static Animation bobFall; + public static TextureRegion bobHit; + public static Animation squirrelFly; + public static TextureRegion platform; + public static Animation brakingPlatform; + public static BitmapFont font; + + public static Music music; + public static Sound jumpSound; + public static Sound highJumpSound; + public static Sound hitSound; + public static Sound coinSound; + public static Sound clickSound; + + public static Texture loadTexture (String file) { + return new Texture(Gdx.files.internal(file)); + } + + public static void load () { + background = loadTexture("data/background.png"); + backgroundRegion = new TextureRegion(background, 0, 0, 320, 480); + + items = loadTexture("data/items.png"); + mainMenu = new TextureRegion(items, 0, 224, 300, 110); + pauseMenu = new TextureRegion(items, 224, 128, 192, 96); + ready = new TextureRegion(items, 320, 224, 192, 32); + gameOver = new TextureRegion(items, 352, 256, 160, 96); + highScoresRegion = new TextureRegion(Assets.items, 0, 257, 300, 110 / 3); + logo = new TextureRegion(items, 0, 352, 274, 142); + soundOff = new TextureRegion(items, 0, 0, 64, 64); + soundOn = new TextureRegion(items, 64, 0, 64, 64); + arrow = new TextureRegion(items, 0, 64, 64, 64); + pause = new TextureRegion(items, 64, 64, 64, 64); + + spring = new TextureRegion(items, 128, 0, 32, 32); + castle = new TextureRegion(items, 128, 64, 64, 64); + coinAnim = new Animation(0.2f, new TextureRegion(items, 128, 32, 32, 32), new TextureRegion(items, 160, 32, 32, 32), + new TextureRegion(items, 192, 32, 32, 32), new TextureRegion(items, 160, 32, 32, 32)); + bobJump = new Animation(0.2f, new TextureRegion(items, 0, 128, 32, 32), new TextureRegion(items, 32, 128, 32, 32)); + bobFall = new Animation(0.2f, new TextureRegion(items, 64, 128, 32, 32), new TextureRegion(items, 96, 128, 32, 32)); + bobHit = new TextureRegion(items, 128, 128, 32, 32); + squirrelFly = new Animation(0.2f, new TextureRegion(items, 0, 160, 32, 32), new TextureRegion(items, 32, 160, 32, 32)); + platform = new TextureRegion(items, 64, 160, 64, 16); + brakingPlatform = new Animation(0.2f, new TextureRegion(items, 64, 160, 64, 16), new TextureRegion(items, 64, 176, 64, 16), + new TextureRegion(items, 64, 192, 64, 16), new TextureRegion(items, 64, 208, 64, 16)); + + font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); + + music = Gdx.audio.newMusic(Gdx.files.internal("data/music.mp3")); + music.setLooping(true); + music.setVolume(0.5f); + if (Settings.soundEnabled) music.play(); + jumpSound = Gdx.audio.newSound(Gdx.files.internal("data/jump.ogg")); + highJumpSound = Gdx.audio.newSound(Gdx.files.internal("data/highjump.ogg")); + hitSound = Gdx.audio.newSound(Gdx.files.internal("data/hit.ogg")); + coinSound = Gdx.audio.newSound(Gdx.files.internal("data/coin.ogg")); + clickSound = Gdx.audio.newSound(Gdx.files.internal("data/click.ogg")); + } + + public static void playSound (Sound sound) { + if (Settings.soundEnabled) sound.play(1); + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Bob.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Bob.java index 48aa7e459da..e3782a843d9 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Bob.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Bob.java @@ -13,69 +13,68 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; -public class Bob extends DynamicGameObject{ - public static final int BOB_STATE_JUMP = 0; - public static final int BOB_STATE_FALL = 1; - public static final int BOB_STATE_HIT = 2; - public static final float BOB_JUMP_VELOCITY = 11; - public static final float BOB_MOVE_VELOCITY = 20; - public static final float BOB_WIDTH = 0.8f; - public static final float BOB_HEIGHT = 0.8f; - - int state; - float stateTime; +public class Bob extends DynamicGameObject { + public static final int BOB_STATE_JUMP = 0; + public static final int BOB_STATE_FALL = 1; + public static final int BOB_STATE_HIT = 2; + public static final float BOB_JUMP_VELOCITY = 11; + public static final float BOB_MOVE_VELOCITY = 20; + public static final float BOB_WIDTH = 0.8f; + public static final float BOB_HEIGHT = 0.8f; + + int state; + float stateTime; + + public Bob (float x, float y) { + super(x, y, BOB_WIDTH, BOB_HEIGHT); + state = BOB_STATE_FALL; + stateTime = 0; + } + + public void update (float deltaTime) { + velocity.add(World.gravity.x * deltaTime, World.gravity.y * deltaTime); + position.add(velocity.x * deltaTime, velocity.y * deltaTime); + bounds.x = position.x - bounds.width / 2; + bounds.y = position.y - bounds.height / 2; + + if (velocity.y > 0 && state != BOB_STATE_HIT) { + if (state != BOB_STATE_JUMP) { + state = BOB_STATE_JUMP; + stateTime = 0; + } + } + + if (velocity.y < 0 && state != BOB_STATE_HIT) { + if (state != BOB_STATE_FALL) { + state = BOB_STATE_FALL; + stateTime = 0; + } + } + + if (position.x < 0) position.x = World.WORLD_WIDTH; + if (position.x > World.WORLD_WIDTH) position.x = 0; + + stateTime += deltaTime; + } - public Bob(float x, float y) { - super(x, y, BOB_WIDTH, BOB_HEIGHT); - state = BOB_STATE_FALL; - stateTime = 0; - } + public void hitSquirrel () { + velocity.set(0, 0); + state = BOB_STATE_HIT; + stateTime = 0; + } - public void update(float deltaTime) { - velocity.add(World.gravity.x * deltaTime, World.gravity.y * deltaTime); - position.add(velocity.x * deltaTime, velocity.y * deltaTime); - bounds.x = position.x - bounds.width / 2; - bounds.y = position.y - bounds.height / 2; - - if(velocity.y > 0 && state != BOB_STATE_HIT) { - if(state != BOB_STATE_JUMP) { - state = BOB_STATE_JUMP; - stateTime = 0; - } - } - - if(velocity.y < 0 && state != BOB_STATE_HIT) { - if(state != BOB_STATE_FALL) { - state = BOB_STATE_FALL; - stateTime = 0; - } - } - - if(position.x < 0) - position.x = World.WORLD_WIDTH; - if(position.x > World.WORLD_WIDTH) - position.x = 0; - - stateTime += deltaTime; - } - - public void hitSquirrel() { - velocity.set(0,0); - state = BOB_STATE_HIT; - stateTime = 0; - } - - public void hitPlatform() { - velocity.y = BOB_JUMP_VELOCITY; - state = BOB_STATE_JUMP; - stateTime = 0; - } + public void hitPlatform () { + velocity.y = BOB_JUMP_VELOCITY; + state = BOB_STATE_JUMP; + stateTime = 0; + } - public void hitSpring() { - velocity.y = BOB_JUMP_VELOCITY * 1.5f; - state = BOB_STATE_JUMP; - stateTime = 0; - } + public void hitSpring () { + velocity.y = BOB_JUMP_VELOCITY * 1.5f; + state = BOB_STATE_JUMP; + stateTime = 0; + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Castle.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Castle.java index b72f39a96e3..0d262abafc5 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Castle.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Castle.java @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogicgames.superjumper; +package com.badlogicgames.superjumper; public class Castle extends GameObject { - public static float CASTLE_WIDTH = 1.7f; - public static float CASTLE_HEIGHT = 1.7f; + public static float CASTLE_WIDTH = 1.7f; + public static float CASTLE_HEIGHT = 1.7f; - public Castle(float x, float y) { - super(x, y, CASTLE_WIDTH, CASTLE_HEIGHT); - } + public Castle (float x, float y) { + super(x, y, CASTLE_WIDTH, CASTLE_HEIGHT); + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Coin.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Coin.java index 88722b9e0c9..e67aa3a6f0d 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Coin.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Coin.java @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogicgames.superjumper; +package com.badlogicgames.superjumper; public class Coin extends GameObject { - public static final float COIN_WIDTH = 0.5f; - public static final float COIN_HEIGHT = 0.8f; - public static final int COIN_SCORE = 10; + public static final float COIN_WIDTH = 0.5f; + public static final float COIN_HEIGHT = 0.8f; + public static final int COIN_SCORE = 10; + + float stateTime; + + public Coin (float x, float y) { + super(x, y, COIN_WIDTH, COIN_HEIGHT); + stateTime = 0; + } - float stateTime; - public Coin(float x, float y) { - super(x, y, COIN_WIDTH, COIN_HEIGHT); - stateTime = 0; - } - - public void update(float deltaTime) { - stateTime += deltaTime; - } + public void update (float deltaTime) { + stateTime += deltaTime; + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/DynamicGameObject.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/DynamicGameObject.java index 8a39b68bc7a..152e1bcadf8 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/DynamicGameObject.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/DynamicGameObject.java @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.math.Vector2; public class DynamicGameObject extends GameObject { - public final Vector2 velocity; - public final Vector2 accel; - - public DynamicGameObject(float x, float y, float width, float height) { - super(x, y, width, height); - velocity = new Vector2(); - accel = new Vector2(); - } + public final Vector2 velocity; + public final Vector2 accel; + + public DynamicGameObject (float x, float y, float width, float height) { + super(x, y, width, height); + velocity = new Vector2(); + accel = new Vector2(); + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Game.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Game.java index 4975e1a9bf0..c01b89700f4 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Game.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Game.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.ApplicationListener; @@ -20,37 +21,43 @@ public abstract class Game implements ApplicationListener { Screen screen; - + public void setScreen (Screen helpScreen2) { screen.pause(); screen.dispose(); screen = helpScreen2; } - - public abstract Screen getStartScreen(); - - @Override public void create () { + + public abstract Screen getStartScreen (); + + @Override + public void create () { screen = getStartScreen(); } - @Override public void resume () { + @Override + public void resume () { screen.resume(); } - @Override public void render () { + @Override + public void render () { screen.update(Gdx.graphics.getDeltaTime()); screen.present(Gdx.graphics.getDeltaTime()); } - @Override public void resize (int width, int height) { - + @Override + public void resize (int width, int height) { + } - @Override public void pause () { + @Override + public void pause () { screen.pause(); } - @Override public void dispose () { + @Override + public void dispose () { screen.dispose(); } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameObject.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameObject.java index a5226620bd7..f0e31702907 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameObject.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameObject.java @@ -13,17 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; public class GameObject { - public final Vector2 position; - public final Rectangle bounds; - - public GameObject(float x, float y, float width, float height) { - this.position = new Vector2(x,y); - this.bounds = new Rectangle(x-width/2, y-height/2, width, height); - } + public final Vector2 position; + public final Rectangle bounds; + + public GameObject (float x, float y, float width, float height) { + this.position = new Vector2(x, y); + this.bounds = new Rectangle(x - width / 2, y - height / 2, width, height); + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameScreen.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameScreen.java index 6316cac80fd..25e7309319f 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameScreen.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/GameScreen.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Application; @@ -49,24 +50,28 @@ public class GameScreen extends Screen { public GameScreen (Game game) { super(game); state = GAME_READY; - guiCam = new OrthographicCamera(320, 480); + guiCam = new OrthographicCamera(320, 480); guiCam.position.set(320 / 2, 480 / 2, 0); touchPoint = new Vector3(); batcher = new SpriteBatch(); worldListener = new WorldListener() { - @Override public void jump () { + @Override + public void jump () { Assets.playSound(Assets.jumpSound); } - @Override public void highJump () { + @Override + public void highJump () { Assets.playSound(Assets.highJumpSound); } - @Override public void hit () { + @Override + public void hit () { Assets.playSound(Assets.hitSound); } - @Override public void coin () { + @Override + public void coin () { Assets.playSound(Assets.coinSound); } }; @@ -79,7 +84,8 @@ public GameScreen (Game game) { scoreString = "SCORE: 0"; } - @Override public void update (float deltaTime) { + @Override + public void update (float deltaTime) { if (deltaTime > 0.1f) deltaTime = 0.1f; switch (state) { @@ -109,7 +115,7 @@ private void updateReady () { private void updateRunning (float deltaTime) { if (Gdx.input.justTouched()) { - guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); + guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); if (OverlapTester.pointInRectangle(pauseBounds, touchPoint.x, touchPoint.y)) { Assets.playSound(Assets.clickSound); @@ -118,15 +124,12 @@ private void updateRunning (float deltaTime) { } } - if(Gdx.app.getType() == Application.ApplicationType.Android) { + if (Gdx.app.getType() == Application.ApplicationType.Android) { world.update(deltaTime, Gdx.input.getAccelerometerX()); - } - else { + } else { float accel = 0; - if(Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) - accel = 5f; - if(Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) - accel = -5f; + if (Gdx.input.isKeyPressed(Keys.DPAD_LEFT)) accel = 5f; + if (Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)) accel = -5f; world.update(deltaTime, accel); } if (world.score != lastScore) { @@ -167,7 +170,7 @@ private void updatePaused () { } private void updateLevelEnd () { - if(Gdx.input.justTouched()) { + if (Gdx.input.justTouched()) { world = new World(worldListener); renderer = new WorldRenderer(batcher, world); world.score = lastScore; @@ -176,12 +179,13 @@ private void updateLevelEnd () { } private void updateGameOver () { - if(Gdx.input.justTouched()) { + if (Gdx.input.justTouched()) { game.setScreen(new MainMenuScreen(game)); } } - @Override public void present (float deltaTime) { + @Override + public void present (float deltaTime) { GLCommon gl = Gdx.gl; gl.glClear(GL10.GL_COLOR_BUFFER_BIT); gl.glEnable(GL10.GL_TEXTURE_2D); @@ -189,9 +193,9 @@ private void updateGameOver () { renderer.render(); guiCam.update(); - batcher.setProjectionMatrix(guiCam.combined); + batcher.setProjectionMatrix(guiCam.combined); batcher.enableBlending(); - batcher.begin(); + batcher.begin(); switch (state) { case GAME_READY: presentReady(); @@ -209,7 +213,7 @@ private void updateGameOver () { presentGameOver(); break; } - batcher.end(); + batcher.end(); } private void presentReady () { @@ -222,7 +226,7 @@ private void presentRunning () { } private void presentPaused () { - batcher.draw( Assets.pauseMenu, 160 - 192 / 2, 240 - 96 / 2, 192, 96); + batcher.draw(Assets.pauseMenu, 160 - 192 / 2, 240 - 96 / 2, 192, 96); Assets.font.draw(batcher, scoreString, 16, 480 - 20); } @@ -241,13 +245,16 @@ private void presentGameOver () { Assets.font.draw(batcher, scoreString, 160 - scoreWidth / 2, 480 - 20); } - @Override public void pause () { + @Override + public void pause () { if (state == GAME_RUNNING) state = GAME_PAUSED; } - @Override public void resume () { + @Override + public void resume () { } - @Override public void dispose () { + @Override + public void dispose () { } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen.java index 27776b6c07e..a9cb16cb1a7 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; @@ -26,70 +27,70 @@ import com.badlogic.gdx.math.Vector3; public class HelpScreen extends Screen { - OrthographicCamera guiCam; - SpriteBatch batcher; - Rectangle nextBounds; - Vector3 touchPoint; - Texture helpImage; - TextureRegion helpRegion; - - public HelpScreen(Game game) { - super(game); - - guiCam = new OrthographicCamera(320, 480); - guiCam.position.set(320 / 2, 480 / 2, 0); - nextBounds = new Rectangle(320 - 64, 0, 64, 64); - touchPoint = new Vector3(); - batcher = new SpriteBatch(); - helpImage = Assets.loadTexture("data/help1.png" ); - helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); - } - - @Override - public void resume() { - } - - @Override - public void pause() { - helpImage.dispose(); - } + OrthographicCamera guiCam; + SpriteBatch batcher; + Rectangle nextBounds; + Vector3 touchPoint; + Texture helpImage; + TextureRegion helpRegion; + + public HelpScreen (Game game) { + super(game); + + guiCam = new OrthographicCamera(320, 480); + guiCam.position.set(320 / 2, 480 / 2, 0); + nextBounds = new Rectangle(320 - 64, 0, 64, 64); + touchPoint = new Vector3(); + batcher = new SpriteBatch(); + helpImage = Assets.loadTexture("data/help1.png"); + helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); + } + + @Override + public void resume () { + } + + @Override + public void pause () { + helpImage.dispose(); + } + + @Override + public void update (float deltaTime) { + if (Gdx.input.justTouched()) { + guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); + + if (OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { + Assets.playSound(Assets.clickSound); + game.setScreen(new HelpScreen2(game)); + return; + } + } + } + + @Override + public void present (float deltaTime) { + GLCommon gl = Gdx.gl; + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + guiCam.update(); + guiCam.apply(Gdx.gl10); + + gl.glEnable(GL10.GL_TEXTURE_2D); + + batcher.disableBlending(); + batcher.begin(); + batcher.draw(helpRegion, 0, 0, 320, 480); + batcher.end(); - @Override - public void update(float deltaTime) { - if(Gdx.input.justTouched()) { - guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); - - if(OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { - Assets.playSound(Assets.clickSound); - game.setScreen(new HelpScreen2(game)); - return; - } - } - } + batcher.enableBlending(); + batcher.begin(); + batcher.draw(Assets.arrow, 320, 0, -64, 64); + batcher.end(); - @Override - public void present(float deltaTime) { - GLCommon gl = Gdx.gl; - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - guiCam.update(); - guiCam.apply(Gdx.gl10); - - gl.glEnable(GL10.GL_TEXTURE_2D); - - batcher.disableBlending(); - batcher.begin(); - batcher.draw(helpRegion, 0, 0, 320, 480); - batcher.end(); - - batcher.enableBlending(); - batcher.begin(); - batcher.draw(Assets.arrow, 320, 0, -64, 64); - batcher.end(); - - gl.glDisable(GL10.GL_BLEND); - } + gl.glDisable(GL10.GL_BLEND); + } - @Override - public void dispose() { - } + @Override + public void dispose () { + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen2.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen2.java index 3c4c4e11f83..ff5cf1669a2 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen2.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen2.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; @@ -27,70 +28,69 @@ public class HelpScreen2 extends Screen { OrthographicCamera guiCam; - SpriteBatch batcher; - Rectangle nextBounds; - Vector3 touchPoint; - Texture helpImage; - TextureRegion helpRegion; - - public HelpScreen2(Game game) { - super(game); - - guiCam = new OrthographicCamera(320, 480); - guiCam.position.set(320 / 2, 480 / 2, 0); - nextBounds = new Rectangle(320 - 64, 0, 64, 64); - touchPoint = new Vector3(); - batcher = new SpriteBatch(); - helpImage = Assets.loadTexture("data/help2.png" ); - helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); - } - - @Override - public void resume() { - } - - @Override - public void pause() { - helpImage.dispose(); - } + SpriteBatch batcher; + Rectangle nextBounds; + Vector3 touchPoint; + Texture helpImage; + TextureRegion helpRegion; - @Override - public void update(float deltaTime) { - if(Gdx.input.justTouched()) { - guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); - - if(OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { - Assets.playSound(Assets.clickSound); - game.setScreen(new HelpScreen3(game)); - return; - } - } - } + public HelpScreen2 (Game game) { + super(game); - @Override - public void present(float deltaTime) { - GLCommon gl = Gdx.gl; - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - guiCam.update(); - guiCam.apply(Gdx.gl10); - - gl.glEnable(GL10.GL_TEXTURE_2D); - - batcher.disableBlending(); - batcher.begin(); - batcher.draw(helpRegion, 0, 0, 320, 480); - batcher.end(); - - batcher.enableBlending(); - batcher.begin(); - batcher.draw(Assets.arrow, 320, 0, -64, 64); - batcher.end(); - - gl.glDisable(GL10.GL_BLEND); - } + guiCam = new OrthographicCamera(320, 480); + guiCam.position.set(320 / 2, 480 / 2, 0); + nextBounds = new Rectangle(320 - 64, 0, 64, 64); + touchPoint = new Vector3(); + batcher = new SpriteBatch(); + helpImage = Assets.loadTexture("data/help2.png"); + helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); + } - @Override - public void dispose() { - } -} + @Override + public void resume () { + } + + @Override + public void pause () { + helpImage.dispose(); + } + + @Override + public void update (float deltaTime) { + if (Gdx.input.justTouched()) { + guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); + + if (OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { + Assets.playSound(Assets.clickSound); + game.setScreen(new HelpScreen3(game)); + return; + } + } + } + + @Override + public void present (float deltaTime) { + GLCommon gl = Gdx.gl; + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + guiCam.update(); + guiCam.apply(Gdx.gl10); + gl.glEnable(GL10.GL_TEXTURE_2D); + + batcher.disableBlending(); + batcher.begin(); + batcher.draw(helpRegion, 0, 0, 320, 480); + batcher.end(); + + batcher.enableBlending(); + batcher.begin(); + batcher.draw(Assets.arrow, 320, 0, -64, 64); + batcher.end(); + + gl.glDisable(GL10.GL_BLEND); + } + + @Override + public void dispose () { + } +} diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen3.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen3.java index 1d461bc74de..07a689a1a1b 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen3.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen3.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; @@ -27,70 +28,69 @@ public class HelpScreen3 extends Screen { OrthographicCamera guiCam; - SpriteBatch batcher; - Rectangle nextBounds; - Vector3 touchPoint; - Texture helpImage; - TextureRegion helpRegion; - - public HelpScreen3(Game game) { - super(game); - - guiCam = new OrthographicCamera(320, 480); - guiCam.position.set(320 / 2, 480 / 2, 0); - nextBounds = new Rectangle(320 - 64, 0, 64, 64); - touchPoint = new Vector3(); - batcher = new SpriteBatch(); - helpImage = Assets.loadTexture("data/help3.png" ); - helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); - } - - @Override - public void resume() { - } - - @Override - public void pause() { - helpImage.dispose(); - } + SpriteBatch batcher; + Rectangle nextBounds; + Vector3 touchPoint; + Texture helpImage; + TextureRegion helpRegion; - @Override - public void update(float deltaTime) { - if(Gdx.input.justTouched()) { - guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); - - if(OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { - Assets.playSound(Assets.clickSound); - game.setScreen(new HelpScreen4(game)); - return; - } - } - } + public HelpScreen3 (Game game) { + super(game); - @Override - public void present(float deltaTime) { - GLCommon gl = Gdx.gl; - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - guiCam.update(); - guiCam.apply(Gdx.gl10); - - gl.glEnable(GL10.GL_TEXTURE_2D); - - batcher.disableBlending(); - batcher.begin(); - batcher.draw(helpRegion, 0, 0, 320, 480); - batcher.end(); - - batcher.enableBlending(); - batcher.begin(); - batcher.draw(Assets.arrow, 320, 0, -64, 64); - batcher.end(); - - gl.glDisable(GL10.GL_BLEND); - } + guiCam = new OrthographicCamera(320, 480); + guiCam.position.set(320 / 2, 480 / 2, 0); + nextBounds = new Rectangle(320 - 64, 0, 64, 64); + touchPoint = new Vector3(); + batcher = new SpriteBatch(); + helpImage = Assets.loadTexture("data/help3.png"); + helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); + } - @Override - public void dispose() { - } -} + @Override + public void resume () { + } + + @Override + public void pause () { + helpImage.dispose(); + } + + @Override + public void update (float deltaTime) { + if (Gdx.input.justTouched()) { + guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); + + if (OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { + Assets.playSound(Assets.clickSound); + game.setScreen(new HelpScreen4(game)); + return; + } + } + } + + @Override + public void present (float deltaTime) { + GLCommon gl = Gdx.gl; + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + guiCam.update(); + guiCam.apply(Gdx.gl10); + gl.glEnable(GL10.GL_TEXTURE_2D); + + batcher.disableBlending(); + batcher.begin(); + batcher.draw(helpRegion, 0, 0, 320, 480); + batcher.end(); + + batcher.enableBlending(); + batcher.begin(); + batcher.draw(Assets.arrow, 320, 0, -64, 64); + batcher.end(); + + gl.glDisable(GL10.GL_BLEND); + } + + @Override + public void dispose () { + } +} diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen4.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen4.java index 4b396d0eb9e..f1ed03f697c 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen4.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen4.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; @@ -27,69 +28,69 @@ public class HelpScreen4 extends Screen { OrthographicCamera guiCam; - SpriteBatch batcher; - Rectangle nextBounds; - Vector3 touchPoint; - Texture helpImage; - TextureRegion helpRegion; - - public HelpScreen4(Game game) { - super(game); - - guiCam = new OrthographicCamera(320, 480); - guiCam.position.set(320 / 2, 480 / 2, 0); - nextBounds = new Rectangle(320 - 64, 0, 64, 64); - touchPoint = new Vector3(); - batcher = new SpriteBatch(); - helpImage = Assets.loadTexture("data/help4.png" ); - helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); - } - - @Override - public void resume() { - } - - @Override - public void pause() { - helpImage.dispose(); - } + SpriteBatch batcher; + Rectangle nextBounds; + Vector3 touchPoint; + Texture helpImage; + TextureRegion helpRegion; + + public HelpScreen4 (Game game) { + super(game); + + guiCam = new OrthographicCamera(320, 480); + guiCam.position.set(320 / 2, 480 / 2, 0); + nextBounds = new Rectangle(320 - 64, 0, 64, 64); + touchPoint = new Vector3(); + batcher = new SpriteBatch(); + helpImage = Assets.loadTexture("data/help4.png"); + helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); + } + + @Override + public void resume () { + } + + @Override + public void pause () { + helpImage.dispose(); + } + + @Override + public void update (float deltaTime) { + if (Gdx.input.justTouched()) { + guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); + + if (OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { + Assets.playSound(Assets.clickSound); + game.setScreen(new HelpScreen5(game)); + return; + } + } + } + + @Override + public void present (float deltaTime) { + GLCommon gl = Gdx.gl; + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + guiCam.update(); + guiCam.apply(Gdx.gl10); + + gl.glEnable(GL10.GL_TEXTURE_2D); + + batcher.disableBlending(); + batcher.begin(); + batcher.draw(helpRegion, 0, 0, 320, 480); + batcher.end(); - @Override - public void update(float deltaTime) { - if(Gdx.input.justTouched()) { - guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); - - if(OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { - Assets.playSound(Assets.clickSound); - game.setScreen(new HelpScreen5(game)); - return; - } - } - } + batcher.enableBlending(); + batcher.begin(); + batcher.draw(Assets.arrow, 320, 0, -64, 64); + batcher.end(); - @Override - public void present(float deltaTime) { - GLCommon gl = Gdx.gl; - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - guiCam.update(); - guiCam.apply(Gdx.gl10); - - gl.glEnable(GL10.GL_TEXTURE_2D); - - batcher.disableBlending(); - batcher.begin(); - batcher.draw(helpRegion, 0, 0, 320, 480); - batcher.end(); - - batcher.enableBlending(); - batcher.begin(); - batcher.draw(Assets.arrow, 320, 0, -64, 64); - batcher.end(); - - gl.glDisable(GL10.GL_BLEND); - } + gl.glDisable(GL10.GL_BLEND); + } - @Override - public void dispose() { - } + @Override + public void dispose () { + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen5.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen5.java index b5363c26809..5bcdfabd059 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen5.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HelpScreen5.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; @@ -27,70 +28,69 @@ public class HelpScreen5 extends Screen { OrthographicCamera guiCam; - SpriteBatch batcher; - Rectangle nextBounds; - Vector3 touchPoint; - Texture helpImage; - TextureRegion helpRegion; - - public HelpScreen5(Game game) { - super(game); - - guiCam = new OrthographicCamera(320, 480); - guiCam.position.set(320 / 2, 480 / 2, 0); - nextBounds = new Rectangle(320 - 64, 0, 64, 64); - touchPoint = new Vector3(); - batcher = new SpriteBatch(); - helpImage = Assets.loadTexture("data/help5.png" ); - helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); - } - - @Override - public void resume() { - } - - @Override - public void pause() { - helpImage.dispose(); - } + SpriteBatch batcher; + Rectangle nextBounds; + Vector3 touchPoint; + Texture helpImage; + TextureRegion helpRegion; - @Override - public void update(float deltaTime) { - if(Gdx.input.justTouched()) { - guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); - - if(OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { - Assets.playSound(Assets.clickSound); - game.setScreen(new MainMenuScreen(game)); - return; - } - } - } + public HelpScreen5 (Game game) { + super(game); - @Override - public void present(float deltaTime) { - GLCommon gl = Gdx.gl; - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - guiCam.update(); - guiCam.apply(Gdx.gl10); - - gl.glEnable(GL10.GL_TEXTURE_2D); - - batcher.disableBlending(); - batcher.begin(); - batcher.draw(helpRegion, 0, 0, 320, 480); - batcher.end(); - - batcher.enableBlending(); - batcher.begin(); - batcher.draw(Assets.arrow, 320, 0, -64, 64); - batcher.end(); - - gl.glDisable(GL10.GL_BLEND); - } + guiCam = new OrthographicCamera(320, 480); + guiCam.position.set(320 / 2, 480 / 2, 0); + nextBounds = new Rectangle(320 - 64, 0, 64, 64); + touchPoint = new Vector3(); + batcher = new SpriteBatch(); + helpImage = Assets.loadTexture("data/help5.png"); + helpRegion = new TextureRegion(helpImage, 0, 0, 320, 480); + } - @Override - public void dispose() { - } -} + @Override + public void resume () { + } + + @Override + public void pause () { + helpImage.dispose(); + } + + @Override + public void update (float deltaTime) { + if (Gdx.input.justTouched()) { + guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); + + if (OverlapTester.pointInRectangle(nextBounds, touchPoint.x, touchPoint.y)) { + Assets.playSound(Assets.clickSound); + game.setScreen(new MainMenuScreen(game)); + return; + } + } + } + + @Override + public void present (float deltaTime) { + GLCommon gl = Gdx.gl; + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + guiCam.update(); + guiCam.apply(Gdx.gl10); + gl.glEnable(GL10.GL_TEXTURE_2D); + + batcher.disableBlending(); + batcher.begin(); + batcher.draw(helpRegion, 0, 0, 320, 480); + batcher.end(); + + batcher.enableBlending(); + batcher.begin(); + batcher.draw(Assets.arrow, 320, 0, -64, 64); + batcher.end(); + + gl.glDisable(GL10.GL_BLEND); + } + + @Override + public void dispose () { + } +} diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HighscoresScreen.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HighscoresScreen.java index a92c0566326..15b2392d30d 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HighscoresScreen.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/HighscoresScreen.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; @@ -34,7 +35,7 @@ public class HighscoresScreen extends Screen { public HighscoresScreen (Game game) { super(game); - guiCam = new OrthographicCamera(320, 480); + guiCam = new OrthographicCamera(320, 480); guiCam.position.set(320 / 2, 480 / 2, 0); backBounds = new Rectangle(0, 0, 64, 64); touchPoint = new Vector3(); @@ -47,10 +48,11 @@ public HighscoresScreen (Game game) { xOffset = 160 - xOffset / 2 + Assets.font.getSpaceWidth() / 2; } - @Override public void update (float deltaTime) { + @Override + public void update (float deltaTime) { if (Gdx.input.justTouched()) { guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); - + if (OverlapTester.pointInRectangle(backBounds, touchPoint.x, touchPoint.y)) { Assets.playSound(Assets.clickSound); game.setScreen(new MainMenuScreen(game)); @@ -59,7 +61,8 @@ public HighscoresScreen (Game game) { } } - @Override public void present (float deltaTime) { + @Override + public void present (float deltaTime) { GLCommon gl = Gdx.gl; gl.glClear(GL10.GL_COLOR_BUFFER_BIT); guiCam.update(); @@ -71,7 +74,7 @@ public HighscoresScreen (Game game) { batcher.begin(); batcher.draw(Assets.backgroundRegion, 0, 0, 320, 480); batcher.end(); - + batcher.enableBlending(); batcher.begin(); batcher.draw(Assets.highScoresRegion, 10, 360 - 16, 300, 33); @@ -83,15 +86,18 @@ public HighscoresScreen (Game game) { } batcher.draw(Assets.arrow, 0, 0, 64, 64); - batcher.end(); + batcher.end(); } - @Override public void resume () { + @Override + public void resume () { } - @Override public void pause () { + @Override + public void pause () { } - @Override public void dispose () { + @Override + public void dispose () { } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/MainMenuScreen.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/MainMenuScreen.java index 6b721eb13b5..d11b4e113bc 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/MainMenuScreen.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/MainMenuScreen.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.Gdx; @@ -34,7 +35,7 @@ public class MainMenuScreen extends Screen { public MainMenuScreen (Game game) { super(game); - guiCam = new OrthographicCamera(320, 480); + guiCam = new OrthographicCamera(320, 480); guiCam.position.set(320 / 2, 480 / 2, 0); batcher = new SpriteBatch(); soundBounds = new Rectangle(0, 0, 64, 64); @@ -44,7 +45,8 @@ public MainMenuScreen (Game game) { touchPoint = new Vector3(); } - @Override public void update (float deltaTime) { + @Override + public void update (float deltaTime) { if (Gdx.input.justTouched()) { guiCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); @@ -74,12 +76,13 @@ public MainMenuScreen (Game game) { } } - @Override public void present (float deltaTime) { + @Override + public void present (float deltaTime) { GLCommon gl = Gdx.gl; gl.glClearColor(1, 0, 0, 1); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); guiCam.update(); - batcher.setProjectionMatrix(guiCam.combined); + batcher.setProjectionMatrix(guiCam.combined); batcher.disableBlending(); batcher.begin(); @@ -91,16 +94,19 @@ public MainMenuScreen (Game game) { batcher.draw(Assets.logo, 160 - 274 / 2, 480 - 10 - 142, 274, 142); batcher.draw(Assets.mainMenu, 10, (int)(200 - 110 / 2), 300, 110); batcher.draw(Settings.soundEnabled ? Assets.soundOn : Assets.soundOff, 0, 0, 64, 64); - batcher.end(); + batcher.end(); } - @Override public void pause () { + @Override + public void pause () { Settings.save(); } - @Override public void resume () { + @Override + public void resume () { } - @Override public void dispose () { + @Override + public void dispose () { } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/OverlapTester.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/OverlapTester.java index 247f0e36c21..02319a51ec9 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/OverlapTester.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/OverlapTester.java @@ -13,29 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; -public class OverlapTester { - public static boolean overlapRectangles(Rectangle r1, Rectangle r2) { - if(r1.x < r2.x + r2.width && - r1.x + r1.width > r2.x && - r1.y < r2.y + r2.height && - r1.y + r1.height > r2.y) - return true; - else - return false; - } - - public static boolean pointInRectangle(Rectangle r, Vector2 p) { - return r.x <= p.x && r.x + r.width >= p.x && - r.y <= p.y && r.y + r.height >= p.y; - } - - public static boolean pointInRectangle(Rectangle r, float x, float y) { - return r.x <= x && r.x + r.width >= x && - r.y <= y && r.y + r.height >= y; - } +public class OverlapTester { + public static boolean overlapRectangles (Rectangle r1, Rectangle r2) { + if (r1.x < r2.x + r2.width && r1.x + r1.width > r2.x && r1.y < r2.y + r2.height && r1.y + r1.height > r2.y) + return true; + else + return false; + } + + public static boolean pointInRectangle (Rectangle r, Vector2 p) { + return r.x <= p.x && r.x + r.width >= p.x && r.y <= p.y && r.y + r.height >= p.y; + } + + public static boolean pointInRectangle (Rectangle r, float x, float y) { + return r.x <= x && r.x + r.width >= x && r.y <= y && r.y + r.height >= y; + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Platform.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Platform.java index 591c012ded8..da6c756abf1 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Platform.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Platform.java @@ -13,54 +13,55 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; public class Platform extends DynamicGameObject { - public static final float PLATFORM_WIDTH = 2; - public static final float PLATFORM_HEIGHT = 0.5f; - public static final int PLATFORM_TYPE_STATIC = 0; - public static final int PLATFORM_TYPE_MOVING = 1; - public static final int PLATFORM_STATE_NORMAL = 0; - public static final int PLATFORM_STATE_PULVERIZING = 1; - public static final float PLATFORM_PULVERIZE_TIME = 0.2f * 4; - public static final float PLATFORM_VELOCITY = 2; - - int type; - int state; - float stateTime; - - public Platform(int type, float x, float y) { - super(x, y, PLATFORM_WIDTH, PLATFORM_HEIGHT); - this.type = type; - this.state = PLATFORM_STATE_NORMAL; - this.stateTime = 0; - if(type == PLATFORM_TYPE_MOVING) { - velocity.x = PLATFORM_VELOCITY; - } - } - - public void update(float deltaTime) { - if(type == PLATFORM_TYPE_MOVING) { - position.add(velocity.x * deltaTime, 0); - bounds.x = position.x - PLATFORM_WIDTH / 2; - bounds.y = position.y - PLATFORM_HEIGHT / 2; - - if(position.x < PLATFORM_WIDTH / 2) { - velocity.x = -velocity.x; - position.x = PLATFORM_WIDTH / 2; - } - if(position.x > World.WORLD_WIDTH - PLATFORM_WIDTH / 2) { - velocity.x = -velocity.x; - position.x = World.WORLD_WIDTH - PLATFORM_WIDTH / 2; - } - } - - stateTime += deltaTime; - } - - public void pulverize() { - state = PLATFORM_STATE_PULVERIZING; - stateTime = 0; - velocity.x = 0; - } + public static final float PLATFORM_WIDTH = 2; + public static final float PLATFORM_HEIGHT = 0.5f; + public static final int PLATFORM_TYPE_STATIC = 0; + public static final int PLATFORM_TYPE_MOVING = 1; + public static final int PLATFORM_STATE_NORMAL = 0; + public static final int PLATFORM_STATE_PULVERIZING = 1; + public static final float PLATFORM_PULVERIZE_TIME = 0.2f * 4; + public static final float PLATFORM_VELOCITY = 2; + + int type; + int state; + float stateTime; + + public Platform (int type, float x, float y) { + super(x, y, PLATFORM_WIDTH, PLATFORM_HEIGHT); + this.type = type; + this.state = PLATFORM_STATE_NORMAL; + this.stateTime = 0; + if (type == PLATFORM_TYPE_MOVING) { + velocity.x = PLATFORM_VELOCITY; + } + } + + public void update (float deltaTime) { + if (type == PLATFORM_TYPE_MOVING) { + position.add(velocity.x * deltaTime, 0); + bounds.x = position.x - PLATFORM_WIDTH / 2; + bounds.y = position.y - PLATFORM_HEIGHT / 2; + + if (position.x < PLATFORM_WIDTH / 2) { + velocity.x = -velocity.x; + position.x = PLATFORM_WIDTH / 2; + } + if (position.x > World.WORLD_WIDTH - PLATFORM_WIDTH / 2) { + velocity.x = -velocity.x; + position.x = World.WORLD_WIDTH - PLATFORM_WIDTH / 2; + } + } + + stateTime += deltaTime; + } + + public void pulverize () { + state = PLATFORM_STATE_PULVERIZING; + stateTime = 0; + velocity.x = 0; + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Screen.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Screen.java index ef9cad9126a..72ec88bf8fe 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Screen.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Screen.java @@ -13,22 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; public abstract class Screen { Game game; - - public Screen(Game game) { + + public Screen (Game game) { this.game = game; } - - public abstract void update(float deltaTime); - - public abstract void present(float deltaTime); - - public abstract void pause(); - - public abstract void resume(); - - public abstract void dispose(); + + public abstract void update (float deltaTime); + + public abstract void present (float deltaTime); + + public abstract void pause (); + + public abstract void resume (); + + public abstract void dispose (); } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Settings.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Settings.java index 0a14dc374a6..9887e38fd20 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Settings.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Settings.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import java.io.BufferedReader; @@ -23,58 +24,55 @@ import com.badlogic.gdx.Gdx; - public class Settings { - public static boolean soundEnabled = true; - public final static int[] highscores = new int[] { 100, 80, 50, 30, 10 }; - public final static String file = ".superjumper"; + public static boolean soundEnabled = true; + public final static int[] highscores = new int[] {100, 80, 50, 30, 10}; + public final static String file = ".superjumper"; - public static void load() { - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader(Gdx.files.external(file).read())); - soundEnabled = Boolean.parseBoolean(in.readLine()); - for(int i = 0; i < 5; i++) { - highscores[i] = Integer.parseInt(in.readLine()); - } - } catch (Throwable e) { - // :( It's ok we have defaults - } finally { - try { - if (in != null) - in.close(); - } catch (IOException e) { - } - } - } + public static void load () { + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader(Gdx.files.external(file).read())); + soundEnabled = Boolean.parseBoolean(in.readLine()); + for (int i = 0; i < 5; i++) { + highscores[i] = Integer.parseInt(in.readLine()); + } + } catch (Throwable e) { + // :( It's ok we have defaults + } finally { + try { + if (in != null) in.close(); + } catch (IOException e) { + } + } + } - public static void save() { - BufferedWriter out = null; - try { - out = new BufferedWriter(new OutputStreamWriter(Gdx.files.external(file).write(false))); - out.write(Boolean.toString(soundEnabled)); - for(int i = 0; i < 5; i++) { - out.write(Integer.toString(highscores[i])); - } + public static void save () { + BufferedWriter out = null; + try { + out = new BufferedWriter(new OutputStreamWriter(Gdx.files.external(file).write(false))); + out.write(Boolean.toString(soundEnabled)); + for (int i = 0; i < 5; i++) { + out.write(Integer.toString(highscores[i])); + } - } catch (Throwable e) { - } finally { - try { - if (out != null) - out.close(); - } catch (IOException e) { - } - } - } + } catch (Throwable e) { + } finally { + try { + if (out != null) out.close(); + } catch (IOException e) { + } + } + } - public static void addScore(int score) { - for(int i=0; i < 5; i++) { - if(highscores[i] < score) { - for(int j= 4; j > i; j--) - highscores[j] = highscores[j-1]; - highscores[i] = score; - break; - } - } - } + public static void addScore (int score) { + for (int i = 0; i < 5; i++) { + if (highscores[i] < score) { + for (int j = 4; j > i; j--) + highscores[j] = highscores[j - 1]; + highscores[i] = score; + break; + } + } + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Spring.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Spring.java index c01c63569d2..842e0a76c55 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Spring.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Spring.java @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogicgames.superjumper; +package com.badlogicgames.superjumper; public class Spring extends GameObject { - public static float SPRING_WIDTH = 0.3f; - public static float SPRING_HEIGHT = 0.3f; - - public Spring(float x, float y) { - super(x, y, SPRING_WIDTH, SPRING_HEIGHT); - } + public static float SPRING_WIDTH = 0.3f; + public static float SPRING_HEIGHT = 0.3f; + + public Spring (float x, float y) { + super(x, y, SPRING_WIDTH, SPRING_HEIGHT); + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Squirrel.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Squirrel.java index b52946ea201..a848d151e21 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Squirrel.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/Squirrel.java @@ -13,33 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; public class Squirrel extends DynamicGameObject { - public static final float SQUIRREL_WIDTH = 1; - public static final float SQUIRREL_HEIGHT = 0.6f; - public static final float SQUIRREL_VELOCITY = 3f; - - float stateTime = 0; - - public Squirrel(float x, float y) { - super(x, y, SQUIRREL_WIDTH, SQUIRREL_HEIGHT); - velocity.set(SQUIRREL_VELOCITY, 0); - } - - public void update(float deltaTime) { - position.add(velocity.x * deltaTime, velocity.y * deltaTime); - bounds.x = position.x - SQUIRREL_WIDTH / 2; - bounds.y = position.y - SQUIRREL_HEIGHT / 2; - - if(position.x < SQUIRREL_WIDTH / 2 ) { - position.x = SQUIRREL_WIDTH / 2; - velocity.x = SQUIRREL_VELOCITY; - } - if(position.x > World.WORLD_WIDTH - SQUIRREL_WIDTH / 2) { - position.x = World.WORLD_WIDTH - SQUIRREL_WIDTH / 2; - velocity.x = -SQUIRREL_VELOCITY; - } - stateTime += deltaTime; - } + public static final float SQUIRREL_WIDTH = 1; + public static final float SQUIRREL_HEIGHT = 0.6f; + public static final float SQUIRREL_VELOCITY = 3f; + + float stateTime = 0; + + public Squirrel (float x, float y) { + super(x, y, SQUIRREL_WIDTH, SQUIRREL_HEIGHT); + velocity.set(SQUIRREL_VELOCITY, 0); + } + + public void update (float deltaTime) { + position.add(velocity.x * deltaTime, velocity.y * deltaTime); + bounds.x = position.x - SQUIRREL_WIDTH / 2; + bounds.y = position.y - SQUIRREL_HEIGHT / 2; + + if (position.x < SQUIRREL_WIDTH / 2) { + position.x = SQUIRREL_WIDTH / 2; + velocity.x = SQUIRREL_VELOCITY; + } + if (position.x > World.WORLD_WIDTH - SQUIRREL_WIDTH / 2) { + position.x = World.WORLD_WIDTH - SQUIRREL_WIDTH / 2; + velocity.x = -SQUIRREL_VELOCITY; + } + stateTime += deltaTime; + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumper.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumper.java index ebfeafa817d..3914cb567bc 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumper.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumper.java @@ -13,21 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogicgames.superjumper; +package com.badlogicgames.superjumper; public class SuperJumper extends Game { - boolean firstTimeCreate = true; - - @Override - public Screen getStartScreen() { - return new MainMenuScreen(this); - } - - @Override - public void create() { - Settings.load(); - Assets.load(); - super.create(); - } + boolean firstTimeCreate = true; + + @Override + public Screen getStartScreen () { + return new MainMenuScreen(this); + } + + @Override + public void create () { + Settings.load(); + Assets.load(); + super.create(); + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumperDesktop.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumperDesktop.java index 78d6e2b8aeb..ac7cc8498f6 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumperDesktop.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/SuperJumperDesktop.java @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.backends.jogl.JoglApplication; public class SuperJumperDesktop { - public static void main(String[] argv) { + public static void main (String[] argv) { new JoglApplication(new SuperJumper(), "Super Jumper", 320, 480, false); } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/World.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/World.java index d15e42f587f..505272fd8a4 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/World.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/World.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import java.util.ArrayList; @@ -22,218 +23,203 @@ import com.badlogic.gdx.math.Vector2; public class World { - public interface WorldListener { - public void jump(); - - public void highJump(); - - public void hit(); - - public void coin(); - } - - public static final float WORLD_WIDTH = 10; - public static final float WORLD_HEIGHT = 15 * 20; - public static final int WORLD_STATE_RUNNING = 0; - public static final int WORLD_STATE_NEXT_LEVEL = 1; - public static final int WORLD_STATE_GAME_OVER = 2; - public static final Vector2 gravity = new Vector2(0, -12); - - public final Bob bob; - public final List platforms; - public final List springs; - public final List squirrels; - public final List coins; - public Castle castle; - public final WorldListener listener; - public final Random rand; - - public float heightSoFar; - public int score; - public int state; - - public World(WorldListener listener) { - this.bob = new Bob(5, 1); - this.platforms = new ArrayList(); - this.springs = new ArrayList(); - this.squirrels = new ArrayList(); - this.coins = new ArrayList(); - this.listener = listener; - rand = new Random(); - generateLevel(); - - this.heightSoFar = 0; - this.score = 0; - this.state = WORLD_STATE_RUNNING; - } - - private void generateLevel() { - float y = Platform.PLATFORM_HEIGHT / 2; - float maxJumpHeight = Bob.BOB_JUMP_VELOCITY * Bob.BOB_JUMP_VELOCITY - / (2 * -gravity.y); - while (y < WORLD_HEIGHT - WORLD_WIDTH / 2) { - int type = rand.nextFloat() > 0.8f ? Platform.PLATFORM_TYPE_MOVING - : Platform.PLATFORM_TYPE_STATIC; - float x = rand.nextFloat() - * (WORLD_WIDTH - Platform.PLATFORM_WIDTH) - + Platform.PLATFORM_WIDTH / 2; - - Platform platform = new Platform(type, x, y); - platforms.add(platform); - - if (rand.nextFloat() > 0.9f - && type != Platform.PLATFORM_TYPE_MOVING) { - Spring spring = new Spring(platform.position.x, - platform.position.y + Platform.PLATFORM_HEIGHT / 2 - + Spring.SPRING_HEIGHT / 2); - springs.add(spring); - } - - if (y > WORLD_HEIGHT / 3 && rand.nextFloat() > 0.8f) { - Squirrel squirrel = new Squirrel(platform.position.x - + rand.nextFloat(), platform.position.y - + Squirrel.SQUIRREL_HEIGHT + rand.nextFloat() * 2); - squirrels.add(squirrel); - } - - if (rand.nextFloat() > 0.6f) { - Coin coin = new Coin(platform.position.x + rand.nextFloat(), - platform.position.y + Coin.COIN_HEIGHT - + rand.nextFloat() * 3); - coins.add(coin); - } - - y += (maxJumpHeight - 0.5f); - y -= rand.nextFloat() * (maxJumpHeight / 3); - } - - castle = new Castle(WORLD_WIDTH / 2, y); - } - - public void update(float deltaTime, float accelX) { - updateBob(deltaTime, accelX); - updatePlatforms(deltaTime); - updateSquirrels(deltaTime); - updateCoins(deltaTime); - if (bob.state != Bob.BOB_STATE_HIT) - checkCollisions(); - checkGameOver(); - } - - private void updateBob(float deltaTime, float accelX) { - if (bob.state != Bob.BOB_STATE_HIT && bob.position.y <= 0.5f) - bob.hitPlatform(); - if (bob.state != Bob.BOB_STATE_HIT) - bob.velocity.x = -accelX / 10 * Bob.BOB_MOVE_VELOCITY; - bob.update(deltaTime); - heightSoFar = Math.max(bob.position.y, heightSoFar); - } - - private void updatePlatforms(float deltaTime) { - int len = platforms.size(); - for (int i = 0; i < len; i++) { - Platform platform = platforms.get(i); - platform.update(deltaTime); - if (platform.state == Platform.PLATFORM_STATE_PULVERIZING - && platform.stateTime > Platform.PLATFORM_PULVERIZE_TIME) { - platforms.remove(platform); - len = platforms.size(); - } - } - } - - private void updateSquirrels(float deltaTime) { - int len = squirrels.size(); - for (int i = 0; i < len; i++) { - Squirrel squirrel = squirrels.get(i); - squirrel.update(deltaTime); - } - } - - private void updateCoins(float deltaTime) { - int len = coins.size(); - for (int i = 0; i < len; i++) { - Coin coin = coins.get(i); - coin.update(deltaTime); - } - } - - private void checkCollisions() { - checkPlatformCollisions(); - checkSquirrelCollisions(); - checkItemCollisions(); - checkCastleCollisions(); - } - - private void checkPlatformCollisions() { - if (bob.velocity.y > 0) - return; - - int len = platforms.size(); - for (int i = 0; i < len; i++) { - Platform platform = platforms.get(i); - if (bob.position.y > platform.position.y) { - if (OverlapTester - .overlapRectangles(bob.bounds, platform.bounds)) { - bob.hitPlatform(); - listener.jump(); - if (rand.nextFloat() > 0.5f) { - platform.pulverize(); - } - break; - } - } - } - } - - private void checkSquirrelCollisions() { - int len = squirrels.size(); - for (int i = 0; i < len; i++) { - Squirrel squirrel = squirrels.get(i); - if (OverlapTester.overlapRectangles(squirrel.bounds, bob.bounds)) { - bob.hitSquirrel(); - listener.hit(); - } - } - } - - private void checkItemCollisions() { - int len = coins.size(); - for (int i = 0; i < len; i++) { - Coin coin = coins.get(i); - if (OverlapTester.overlapRectangles(bob.bounds, coin.bounds)) { - coins.remove(coin); - len = coins.size(); - listener.coin(); - score += Coin.COIN_SCORE; - } - - } - - if (bob.velocity.y > 0) - return; - - len = springs.size(); - for (int i = 0; i < len; i++) { - Spring spring = springs.get(i); - if (bob.position.y > spring.position.y) { - if (OverlapTester.overlapRectangles(bob.bounds, spring.bounds)) { - bob.hitSpring(); - listener.highJump(); - } - } - } - } - - private void checkCastleCollisions() { - if (OverlapTester.overlapRectangles(castle.bounds, bob.bounds)) { - state = WORLD_STATE_NEXT_LEVEL; - } - } - - private void checkGameOver() { - if (heightSoFar - 7.5f > bob.position.y) { - state = WORLD_STATE_GAME_OVER; - } - } + public interface WorldListener { + public void jump (); + + public void highJump (); + + public void hit (); + + public void coin (); + } + + public static final float WORLD_WIDTH = 10; + public static final float WORLD_HEIGHT = 15 * 20; + public static final int WORLD_STATE_RUNNING = 0; + public static final int WORLD_STATE_NEXT_LEVEL = 1; + public static final int WORLD_STATE_GAME_OVER = 2; + public static final Vector2 gravity = new Vector2(0, -12); + + public final Bob bob; + public final List platforms; + public final List springs; + public final List squirrels; + public final List coins; + public Castle castle; + public final WorldListener listener; + public final Random rand; + + public float heightSoFar; + public int score; + public int state; + + public World (WorldListener listener) { + this.bob = new Bob(5, 1); + this.platforms = new ArrayList(); + this.springs = new ArrayList(); + this.squirrels = new ArrayList(); + this.coins = new ArrayList(); + this.listener = listener; + rand = new Random(); + generateLevel(); + + this.heightSoFar = 0; + this.score = 0; + this.state = WORLD_STATE_RUNNING; + } + + private void generateLevel () { + float y = Platform.PLATFORM_HEIGHT / 2; + float maxJumpHeight = Bob.BOB_JUMP_VELOCITY * Bob.BOB_JUMP_VELOCITY / (2 * -gravity.y); + while (y < WORLD_HEIGHT - WORLD_WIDTH / 2) { + int type = rand.nextFloat() > 0.8f ? Platform.PLATFORM_TYPE_MOVING : Platform.PLATFORM_TYPE_STATIC; + float x = rand.nextFloat() * (WORLD_WIDTH - Platform.PLATFORM_WIDTH) + Platform.PLATFORM_WIDTH / 2; + + Platform platform = new Platform(type, x, y); + platforms.add(platform); + + if (rand.nextFloat() > 0.9f && type != Platform.PLATFORM_TYPE_MOVING) { + Spring spring = new Spring(platform.position.x, platform.position.y + Platform.PLATFORM_HEIGHT / 2 + + Spring.SPRING_HEIGHT / 2); + springs.add(spring); + } + + if (y > WORLD_HEIGHT / 3 && rand.nextFloat() > 0.8f) { + Squirrel squirrel = new Squirrel(platform.position.x + rand.nextFloat(), platform.position.y + + Squirrel.SQUIRREL_HEIGHT + rand.nextFloat() * 2); + squirrels.add(squirrel); + } + + if (rand.nextFloat() > 0.6f) { + Coin coin = new Coin(platform.position.x + rand.nextFloat(), platform.position.y + Coin.COIN_HEIGHT + + rand.nextFloat() * 3); + coins.add(coin); + } + + y += (maxJumpHeight - 0.5f); + y -= rand.nextFloat() * (maxJumpHeight / 3); + } + + castle = new Castle(WORLD_WIDTH / 2, y); + } + + public void update (float deltaTime, float accelX) { + updateBob(deltaTime, accelX); + updatePlatforms(deltaTime); + updateSquirrels(deltaTime); + updateCoins(deltaTime); + if (bob.state != Bob.BOB_STATE_HIT) checkCollisions(); + checkGameOver(); + } + + private void updateBob (float deltaTime, float accelX) { + if (bob.state != Bob.BOB_STATE_HIT && bob.position.y <= 0.5f) bob.hitPlatform(); + if (bob.state != Bob.BOB_STATE_HIT) bob.velocity.x = -accelX / 10 * Bob.BOB_MOVE_VELOCITY; + bob.update(deltaTime); + heightSoFar = Math.max(bob.position.y, heightSoFar); + } + + private void updatePlatforms (float deltaTime) { + int len = platforms.size(); + for (int i = 0; i < len; i++) { + Platform platform = platforms.get(i); + platform.update(deltaTime); + if (platform.state == Platform.PLATFORM_STATE_PULVERIZING && platform.stateTime > Platform.PLATFORM_PULVERIZE_TIME) { + platforms.remove(platform); + len = platforms.size(); + } + } + } + + private void updateSquirrels (float deltaTime) { + int len = squirrels.size(); + for (int i = 0; i < len; i++) { + Squirrel squirrel = squirrels.get(i); + squirrel.update(deltaTime); + } + } + + private void updateCoins (float deltaTime) { + int len = coins.size(); + for (int i = 0; i < len; i++) { + Coin coin = coins.get(i); + coin.update(deltaTime); + } + } + + private void checkCollisions () { + checkPlatformCollisions(); + checkSquirrelCollisions(); + checkItemCollisions(); + checkCastleCollisions(); + } + + private void checkPlatformCollisions () { + if (bob.velocity.y > 0) return; + + int len = platforms.size(); + for (int i = 0; i < len; i++) { + Platform platform = platforms.get(i); + if (bob.position.y > platform.position.y) { + if (OverlapTester.overlapRectangles(bob.bounds, platform.bounds)) { + bob.hitPlatform(); + listener.jump(); + if (rand.nextFloat() > 0.5f) { + platform.pulverize(); + } + break; + } + } + } + } + + private void checkSquirrelCollisions () { + int len = squirrels.size(); + for (int i = 0; i < len; i++) { + Squirrel squirrel = squirrels.get(i); + if (OverlapTester.overlapRectangles(squirrel.bounds, bob.bounds)) { + bob.hitSquirrel(); + listener.hit(); + } + } + } + + private void checkItemCollisions () { + int len = coins.size(); + for (int i = 0; i < len; i++) { + Coin coin = coins.get(i); + if (OverlapTester.overlapRectangles(bob.bounds, coin.bounds)) { + coins.remove(coin); + len = coins.size(); + listener.coin(); + score += Coin.COIN_SCORE; + } + + } + + if (bob.velocity.y > 0) return; + + len = springs.size(); + for (int i = 0; i < len; i++) { + Spring spring = springs.get(i); + if (bob.position.y > spring.position.y) { + if (OverlapTester.overlapRectangles(bob.bounds, spring.bounds)) { + bob.hitSpring(); + listener.highJump(); + } + } + } + } + + private void checkCastleCollisions () { + if (OverlapTester.overlapRectangles(castle.bounds, bob.bounds)) { + state = WORLD_STATE_NEXT_LEVEL; + } + } + + private void checkGameOver () { + if (heightSoFar - 7.5f > bob.position.y) { + state = WORLD_STATE_GAME_OVER; + } + } } diff --git a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/WorldRenderer.java b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/WorldRenderer.java index 613b4ab317d..b88246e42dc 100644 --- a/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/WorldRenderer.java +++ b/demos/superjumper/superjumper/src/com/badlogicgames/superjumper/WorldRenderer.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogicgames.superjumper; import com.badlogic.gdx.graphics.OrthographicCamera; @@ -29,7 +30,7 @@ public class WorldRenderer { public WorldRenderer (SpriteBatch batch, World world) { this.world = world; - this.cam = new OrthographicCamera(FRUSTUM_WIDTH, FRUSTUM_HEIGHT); + this.cam = new OrthographicCamera(FRUSTUM_WIDTH, FRUSTUM_HEIGHT); this.cam.position.set(FRUSTUM_WIDTH / 2, FRUSTUM_HEIGHT / 2, 0); this.batch = batch; } @@ -45,11 +46,12 @@ public void render () { public void renderBackground () { batch.disableBlending(); batch.begin(); - batch.draw(Assets.backgroundRegion, cam.position.x - FRUSTUM_WIDTH / 2, cam.position.y - FRUSTUM_HEIGHT / 2, FRUSTUM_WIDTH, FRUSTUM_HEIGHT); + batch.draw(Assets.backgroundRegion, cam.position.x - FRUSTUM_WIDTH / 2, cam.position.y - FRUSTUM_HEIGHT / 2, FRUSTUM_WIDTH, + FRUSTUM_HEIGHT); batch.end(); } - public void renderObjects () { + public void renderObjects () { batch.enableBlending(); batch.begin(); renderBob(); @@ -57,7 +59,7 @@ public void renderObjects () { renderItems(); renderSquirrels(); renderCastle(); - batch.end(); + batch.end(); } private void renderBob () { @@ -75,7 +77,7 @@ private void renderBob () { } float side = world.bob.velocity.x < 0 ? -1 : 1; - if(side < 0) + if (side < 0) batch.draw(keyFrame, world.bob.position.x + 0.5f, world.bob.position.y - 0.5f, side * 1, 1); else batch.draw(keyFrame, world.bob.position.x - 0.5f, world.bob.position.y - 0.5f, side * 1, 1); @@ -115,7 +117,7 @@ private void renderSquirrels () { Squirrel squirrel = world.squirrels.get(i); TextureRegion keyFrame = Assets.squirrelFly.getKeyFrame(squirrel.stateTime, Animation.ANIMATION_LOOPING); float side = squirrel.velocity.x < 0 ? -1 : 1; - if(side < 0 ) + if (side < 0) batch.draw(keyFrame, squirrel.position.x + 0.5f, squirrel.position.y - 0.5f, side * 1, 1); else batch.draw(keyFrame, squirrel.position.x - 0.5f, squirrel.position.y - 0.5f, side * 1, 1); diff --git a/demos/vector-pinball/gdx-vectorpinball-android/src/com/dozingcatsoftware/bouncy/BouncyAndroid.java b/demos/vector-pinball/gdx-vectorpinball-android/src/com/dozingcatsoftware/bouncy/BouncyAndroid.java index 00c5f23836a..85b3f9ccffd 100644 --- a/demos/vector-pinball/gdx-vectorpinball-android/src/com/dozingcatsoftware/bouncy/BouncyAndroid.java +++ b/demos/vector-pinball/gdx-vectorpinball-android/src/com/dozingcatsoftware/bouncy/BouncyAndroid.java @@ -4,11 +4,11 @@ import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy; public class BouncyAndroid extends AndroidApplication { /** Called when the activity is first created. */ - @Override public void onCreate (Bundle savedInstanceState) { + @Override + public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize(new Bouncy(), false); } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/BaseFieldDelegate.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/BaseFieldDelegate.java index 1d94056189f..c6e0534aa7a 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/BaseFieldDelegate.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/BaseFieldDelegate.java @@ -7,38 +7,45 @@ import com.dozingcatsoftware.bouncy.elements.RolloverGroupElement; import com.dozingcatsoftware.bouncy.elements.SensorElement; -/** - * This class implements the Field.Delegate interface and does nothing for each of the interface methods. Real delegates can +/** This class implements the Field.Delegate interface and does nothing for each of the interface methods. Real delegates can * subclass this class to avoid having to create empty implementations for events they don't care about. If a field definition * doesn't specify a delegate class, an instance of this class will be used as a placeholder delegate. - * @author brian - */ + * @author brian */ public class BaseFieldDelegate implements Field.Delegate { - @Override public void allDropTargetsInGroupHit (Field field, DropTargetGroupElement targetGroup) { + @Override + public void allDropTargetsInGroupHit (Field field, DropTargetGroupElement targetGroup) { } - @Override public void allRolloversInGroupActivated (Field field, RolloverGroupElement rolloverGroup) { + @Override + public void allRolloversInGroupActivated (Field field, RolloverGroupElement rolloverGroup) { } - @Override public void flipperActivated (Field field) { + @Override + public void flipperActivated (Field field) { } - @Override public void processCollision (Field field, FieldElement element, Body hitBody, Body ball) { + @Override + public void processCollision (Field field, FieldElement element, Body hitBody, Body ball) { } - @Override public void gameStarted (Field field) { + @Override + public void gameStarted (Field field) { } - @Override public void ballLost (Field field) { + @Override + public void ballLost (Field field) { } - @Override public void gameEnded (Field field) { + @Override + public void gameEnded (Field field) { } - @Override public void tick (Field field, long msecs) { + @Override + public void tick (Field field, long msecs) { } - @Override public void ballInSensorRange (Field field, SensorElement sensor) { + @Override + public void ballInSensorRange (Field field, SensorElement sensor) { } } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Bouncy.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Bouncy.java index e69775d7da2..ce4a5796f9c 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Bouncy.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Bouncy.java @@ -19,7 +19,8 @@ public class Bouncy extends InputAdapter implements ApplicationListener { WindowedMean renderMean = new WindowedMean(10); long startTime = System.nanoTime(); - @Override public void create () { + @Override + public void create () { Thread.currentThread().setPriority(Thread.MAX_PRIORITY); cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); renderer = new GLFieldRenderer(); @@ -28,11 +29,13 @@ public class Bouncy extends InputAdapter implements ApplicationListener { Gdx.input.setInputProcessor(this); } - @Override public void resume () { + @Override + public void resume () { } - @Override public void render () { + @Override + public void render () { GLCommon gl = Gdx.gl; long startPhysics = System.nanoTime(); @@ -67,32 +70,38 @@ public class Bouncy extends InputAdapter implements ApplicationListener { } } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } - @Override public void pause () { + @Override + public void pause () { } - @Override public void dispose () { + @Override + public void dispose () { } - @Override public boolean touchDown (int x, int y, int pointer, int button) { + @Override + public boolean touchDown (int x, int y, int pointer, int button) { field.removeDeadBalls(); if (field.getBalls().size() != 0) field.setAllFlippersEngaged(true); return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { field.removeDeadBalls(); if (field.getBalls().size() == 0) field.launchBall(); field.setAllFlippersEngaged(false); return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { if (field.getBalls().size() != 0) field.setAllFlippersEngaged(true); return false; } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Field.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Field.java index 73752740097..994b479fa54 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Field.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/Field.java @@ -75,18 +75,17 @@ static class ScheduledAction implements Comparable { Long actionTime; Runnable action; - @Override public int compareTo (ScheduledAction another) { + @Override + public int compareTo (ScheduledAction another) { // sort by action time so these objects can be added to a PriorityQueue in the right order return actionTime.compareTo(another.actionTime); } } - /** - * Creates Box2D world, reads layout definitions for the given level (currently only one), and initializes the game to the + /** Creates Box2D world, reads layout definitions for the given level (currently only one), and initializes the game to the * starting state. * @param context - * @param level - */ + * @param level */ public void resetForLevel (int level) { Vector2 gravity = new Vector2(0.0f, -1.0f); boolean doSleep = true; @@ -142,18 +141,14 @@ public void startGame () { getDelegate().gameStarted(this); } - /** - * Returns the FieldElement with the given value for its "id" attribute, or null if there is no such element. - */ + /** Returns the FieldElement with the given value for its "id" attribute, or null if there is no such element. */ public FieldElement getFieldElementByID (String elementID) { return fieldElements.get(elementID); } - /** - * Called to advance the game's state by the specified number of milliseconds. iters is the number of times to call the Box2D + /** Called to advance the game's state by the specified number of milliseconds. iters is the number of times to call the Box2D * World.step method; more iterations produce better accuracy. After updating physics, processes element collisions, calls - * tick() on every FieldElement, and performs scheduled actions. - */ + * tick() on every FieldElement, and performs scheduled actions. */ void tick (long msecs, int iters) { float dt = (msecs / 1000.0f) / iters; @@ -171,9 +166,7 @@ void tick (long msecs, int iters) { getDelegate().tick(this, msecs); } - /** - * Calls the tick() method of every FieldElement in the layout. - */ + /** Calls the tick() method of every FieldElement in the layout. */ void processElementTicks () { int size = fieldElementsToTick.length; for (int i = 0; i < size; i++) { @@ -181,9 +174,7 @@ void processElementTicks () { } } - /** - * Runs actions that were scheduled with scheduleAction and whose execution time has arrived. - */ + /** Runs actions that were scheduled with scheduleAction and whose execution time has arrived. */ void processScheduledActions () { while (true) { ScheduledAction nextAction = scheduledActions.peek(); @@ -196,9 +187,7 @@ void processScheduledActions () { } } - /** - * Schedules an action to be run after the given interval in milliseconds has elapsed. Interval is in game time, not real time. - */ + /** Schedules an action to be run after the given interval in milliseconds has elapsed. Interval is in game time, not real time. */ public void scheduleAction (long interval, Runnable action) { ScheduledAction sa = new ScheduledAction(); sa.actionTime = gameTime + interval; @@ -206,9 +195,7 @@ public void scheduleAction (long interval, Runnable action) { scheduledActions.add(sa); } - /** - * Launches a new ball. The position and velocity of the ball are controlled by the "launch" key in the field layout JSON. - */ + /** Launches a new ball. The position and velocity of the ball are controlled by the "launch" key in the field layout JSON. */ public Body launchBall () { List position = layout.getLaunchPosition(); List velocity = layout.getLaunchVelocity(); @@ -221,9 +208,7 @@ public Body launchBall () { return ball; } - /** - * Removes a ball from play. If this results in no balls remaining on the field, calls doBallLost. - */ + /** Removes a ball from play. If this results in no balls remaining on the field, calls doBallLost. */ public void removeBall (Body ball) { world.destroyBody(ball); this.balls.remove(ball); @@ -232,10 +217,8 @@ public void removeBall (Body ball) { } } - /** - * Called when a ball has ended. Ends the game if that was the last ball, otherwise updates GameState to the next ball. Shows a - * game message to indicate the ball number or game over. - */ + /** Called when a ball has ended. Ends the game if that was the last ball, otherwise updates GameState to the next ball. Shows a + * game message to indicate the ball number or game over. */ public void doBallLost () { boolean hasExtraBall = (this.gameState.getExtraBalls() > 0); this.gameState.doNextBall(); @@ -260,10 +243,8 @@ public void run () { getDelegate().ballLost(this); } - /** - * Returns true if there are active elements in motion. Returns false if there are no active elements, indicating that tick() - * can be called with larger time steps, less frequently, or not at all. - */ + /** Returns true if there are active elements in motion. Returns false if there are no active elements, indicating that tick() + * can be called with larger time steps, less frequently, or not at all. */ public boolean hasActiveElements () { // HACK: to allow flippers to drop properly at beginning of game, we need accurate simulation if (this.gameTime < 500) return true; @@ -273,9 +254,7 @@ public boolean hasActiveElements () { ArrayList deadBalls = new ArrayList(); - /** - * Removes balls that are not in play, currently defined as those having a y position of less than 1. - */ + /** Removes balls that are not in play, currently defined as those having a y position of less than 1. */ public void removeDeadBalls () { int len = balls.size(); deadBalls.clear(); @@ -293,9 +272,7 @@ public void removeDeadBalls () { } } - /** - * Called by FieldView to draw the balls currently in play. - */ + /** Called by FieldView to draw the balls currently in play. */ public void drawBalls (IFieldRenderer renderer) { List color = layout.getBallColor(); int len = balls.size(); @@ -307,10 +284,8 @@ public void drawBalls (IFieldRenderer renderer) { } } - /** - * Called to engage or disengage all flippers. If called with an argument of true, and all flippers were not previously - * engaged, calls the flipperActivated methods of all field elements and the field's delegate. - */ + /** Called to engage or disengage all flippers. If called with an argument of true, and all flippers were not previously + * engaged, calls the flipperActivated methods of all field elements and the field's delegate. */ public void setAllFlippersEngaged (boolean engaged) { boolean allFlippersPreviouslyActive = true; for (FlipperElement flipper : this.getFlipperElements()) { @@ -326,10 +301,8 @@ public void setAllFlippersEngaged (boolean engaged) { } } - /** - * Ends a game in progress by removing all balls in play, calling setGameInProgress(false) on the GameState, and setting a - * "Game Over" message for display by the score view. - */ + /** Ends a game in progress by removing all balls in play, calling setGameInProgress(false) on the GameState, and setting a + * "Game Over" message for display by the score view. */ public void endGame () { int len = balls.size(); for (int i = 0; i < len; i++) { @@ -341,9 +314,7 @@ public void endGame () { getDelegate().gameEnded(this); } - /** - * Adjusts gravity in response to the device being tilted; not currently used. - */ + /** Adjusts gravity in response to the device being tilted; not currently used. */ public void receivedOrientationValues (float azimuth, float pitch, float roll) { double angle = roll - Math.PI / 2; float gravity = layout.getGravity(); @@ -359,9 +330,7 @@ void clearBallContacts () { ballContacts.clear(); } - /** - * Called after Box2D world step method, to notify FieldElements that the ball collided with. - */ + /** Called after Box2D world step method, to notify FieldElements that the ball collided with. */ void processBallContacts () { int len = balls.size(); for (int i = 0; i < len; i++) { @@ -386,11 +355,13 @@ void processBallContacts () { } // ContactListener methods - @Override public void beginContact (Contact contact) { + @Override + public void beginContact (Contact contact) { // nothing here, contact is recorded in endContact() } - @Override public void endContact (Contact contact) { + @Override + public void endContact (Contact contact) { // A ball can have multiple contacts (e.g. against two walls), so store list of contacted fixtures Body ball = null; Fixture fixture = null; @@ -413,10 +384,8 @@ void processBallContacts () { // end ContactListener methods - /** - * Displays a message in the score view for the specified duration in milliseconds. Duration is in real world time, not - * simulated game time. - */ + /** Displays a message in the score view for the specified duration in milliseconds. Duration is in real world time, not + * simulated game time. */ public void showGameMessage (String text, long duration) { gameMessage = new GameMessage(); gameMessage.text = text; @@ -433,9 +402,7 @@ void processGameMessages () { } } - /** - * Adds the given value to the game score. The value is multiplied by the GameState's current multipler. - */ + /** Adds the given value to the game score. The value is multiplied by the GameState's current multipler. */ public void addScore (long s) { gameState.addScore(s); } @@ -490,14 +457,14 @@ public Delegate getDelegate () { } @Override - public void preSolve(Contact contact, Manifold oldManifold) { + public void preSolve (Contact contact, Manifold oldManifold) { // TODO Auto-generated method stub - + } @Override - public void postSolve(Contact contact, ContactImpulse impulse) { + public void postSolve (Contact contact, ContactImpulse impulse) { // TODO Auto-generated method stub - + } } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/FieldLayout.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/FieldLayout.java index 00e133d462f..de4ff20d5d4 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/FieldLayout.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/FieldLayout.java @@ -143,10 +143,8 @@ public float getHeight () { return height; } - /** - * Returns the desired ratio between real world time and simulation time. The application should adjust the frame rate and/or - * time interval passed to Field.tick() to keep the ratio as close to this value as possible. - */ + /** Returns the desired ratio between real world time and simulation time. The application should adjust the frame rate and/or + * time interval passed to Field.tick() to keep the ratio as close to this value as possible. */ public float getTargetTimeRatio () { return targetTimeRatio; } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GLFieldRenderer.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GLFieldRenderer.java index 1c5157f49d7..f1e47d62ab5 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GLFieldRenderer.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GLFieldRenderer.java @@ -26,7 +26,8 @@ public void begin () { renderer.begin(GL10.GL_LINES); } - @Override public void drawLine (float x1, float y1, float x2, float y2, int r, int g, int b) { + @Override + public void drawLine (float x1, float y1, float x2, float y2, int r, int g, int b) { float fr = r / 255f; float fg = g / 255f; float fb = b / 255f; @@ -36,7 +37,8 @@ public void begin () { renderer.vertex(x2, y2, 0); } - @Override public void fillCircle (float cx, float cy, float radius, int r, int g, int b) { + @Override + public void fillCircle (float cx, float cy, float radius, int r, int g, int b) { end(); renderer.begin(GL10.GL_TRIANGLE_FAN); float fr = r / 255f; @@ -58,7 +60,8 @@ public void begin () { begin(); } - @Override public void frameCircle (float cx, float cy, float radius, int r, int g, int b) { + @Override + public void frameCircle (float cx, float cy, float radius, int r, int g, int b) { float fr = r / 255f; float fg = g / 255f; float fb = b / 255f; diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GameMessage.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GameMessage.java index 121faaed347..156f4aefb7e 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GameMessage.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/GameMessage.java @@ -1,9 +1,7 @@ package com.dozingcatsoftware.bouncy; -/** - * Simple class to hold a message displayed in the ScoreView above the game field. - */ +/** Simple class to hold a message displayed in the ScoreView above the game field. */ public class GameMessage { public String text; diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/IFieldRenderer.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/IFieldRenderer.java index c53b7387877..16141e9fc78 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/IFieldRenderer.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/IFieldRenderer.java @@ -1,10 +1,8 @@ package com.dozingcatsoftware.bouncy; -/** - * This interface defines methods that draw graphical elements such as lines as circles to display the field. An implementation of - * this interface is passed to FieldElement objects so they can draw themselves without depending directly on Android UI classes. - */ +/** This interface defines methods that draw graphical elements such as lines as circles to display the field. An implementation of + * this interface is passed to FieldElement objects so they can draw themselves without depending directly on Android UI classes. */ public interface IFieldRenderer { diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/Box2DFactory.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/Box2DFactory.java index 244ca2d7899..7ac09724e9a 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/Box2DFactory.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/Box2DFactory.java @@ -9,16 +9,12 @@ import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; -/** - * Methods to create Box2D shapes. - * @author brian - */ +/** Methods to create Box2D shapes. + * @author brian */ public class Box2DFactory { - /** - * Creates a circle object with the given position and radius. Resitution defaults to 0.6. - */ + /** Creates a circle object with the given position and radius. Resitution defaults to 0.6. */ public static Body createCircle (World world, float x, float y, float radius, boolean isStatic) { CircleShape sd = new CircleShape(); sd.setRadius(radius); @@ -43,18 +39,14 @@ public static Body createCircle (World world, float x, float y, float radius, bo return body; } - /** - * Creates a wall by constructing a rectangle whose corners are (xmin,ymin) and (xmax,ymax), and rotating the box - * counterclockwise through the given angle. Restitution defaults to 0.5. - */ + /** Creates a wall by constructing a rectangle whose corners are (xmin,ymin) and (xmax,ymax), and rotating the box + * counterclockwise through the given angle. Restitution defaults to 0.5. */ public static Body createWall (World world, float xmin, float ymin, float xmax, float ymax, float angle) { return createWall(world, xmin, ymin, xmax, ymax, angle, 0f); } - /** - * Creates a wall by constructing a rectangle whose corners are (xmin,ymin) and (xmax,ymax), and rotating the box - * counterclockwise through the given angle, with specified restitution. - */ + /** Creates a wall by constructing a rectangle whose corners are (xmin,ymin) and (xmax,ymax), and rotating the box + * counterclockwise through the given angle, with specified restitution. */ public static Body createWall (World world, float xmin, float ymin, float xmax, float ymax, float angle, float restitution) { float cx = (xmin + xmax) / 2; float cy = (ymin + ymax) / 2; diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/BumperElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/BumperElement.java index 67849a6c416..b74a1a4dda9 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/BumperElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/BumperElement.java @@ -14,10 +14,8 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * This FieldElement subclass represents a bumper that applies an impulse to a ball when it hits. The impulse magnitude is - * controlled by the "kick" parameter in the configuration map. - */ +/** This FieldElement subclass represents a bumper that applies an impulse to a ball when it hits. The impulse magnitude is + * controlled by the "kick" parameter in the configuration map. */ public class BumperElement extends FieldElement { @@ -39,11 +37,13 @@ public void finishCreate (Map params, World world) { pegBodySet = Collections.singleton(pegBody); } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return pegBodySet; } - @Override public boolean shouldCallTick () { + @Override + public boolean shouldCallTick () { // needs to call tick to decrement flash counter (but can use superclass tick() implementation) return true; } @@ -59,7 +59,8 @@ Vector2 impulseForBall (Body ball) { return new Vector2(ix * scale, iy * scale); } - @Override public void handleCollision (Body ball, Body bodyHit, Field field) { + @Override + public void handleCollision (Body ball, Body bodyHit, Field field) { Vector2 impulse = this.impulseForBall(ball); if (impulse != null) { ball.applyLinearImpulse(impulse, ball.getWorldCenter()); @@ -67,7 +68,8 @@ Vector2 impulseForBall (Body ball) { } } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { renderer.fillCircle(cx, cy, radius, redColorComponent(0), greenColorComponent(0), blueColorComponent(255)); } } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/DropTargetGroupElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/DropTargetGroupElement.java index 509e975a300..50c37708474 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/DropTargetGroupElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/DropTargetGroupElement.java @@ -14,11 +14,9 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * This FieldElement subclass represents a set of drop targets, which are segments that disappear when hit. When all targets are +/** This FieldElement subclass represents a set of drop targets, which are segments that disappear when hit. When all targets are * hit, the Field delegate is notified, and if the reset parameter is set, the targets will reappear after a delay. - * @author brian - */ + * @author brian */ public class DropTargetGroupElement extends FieldElement { @@ -26,7 +24,8 @@ public class DropTargetGroupElement extends FieldElement { List allBodies = new ArrayList(); Map bodyPositions = new HashMap(); - @Override public void finishCreate (Map params, World world) { + @Override + public void finishCreate (Map params, World world) { // individual targets are specified in "positions" list List positions = (List)params.get("positions"); for (List pos : positions) { @@ -38,7 +37,8 @@ public class DropTargetGroupElement extends FieldElement { } } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return allBodies; } @@ -50,7 +50,8 @@ public boolean allTargetsHit () { return true; } - @Override public void handleCollision (Body ball, Body bodyHit, final Field field) { + @Override + public void handleCollision (Body ball, Body bodyHit, final Field field) { bodyHit.setActive(false); // if all hit, notify delegate and check for reset parameter if (allTargetsHit()) { @@ -74,7 +75,8 @@ public void makeAllTargetsVisible (Field field) { } } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { // draw line for each target int r = redColorComponent(0); int g = greenColorComponent(255); diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FieldElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FieldElement.java index cd91addac5f..37c9e5aae42 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FieldElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FieldElement.java @@ -10,10 +10,8 @@ import com.dozingcatsoftware.bouncy.Field; import com.dozingcatsoftware.bouncy.IFieldRenderer; -/** - * Abstract superclass of all elements in the pinball field, such as walls, bumpers, and flippers. - * @author brian - */ +/** Abstract superclass of all elements in the pinball field, such as walls, bumpers, and flippers. + * @author brian */ public abstract class FieldElement { @@ -30,11 +28,9 @@ public abstract class FieldElement { static int DEFAULT_WALL_GREEN = 64; static int DEFAULT_WALL_BLUE = 160; - /** - * Creates and returns a FieldElement object from the given map of parameters. The default class to instantiate is an argument + /** Creates and returns a FieldElement object from the given map of parameters. The default class to instantiate is an argument * to this method, and can be overridden by the "class" property of the parameter map. Calls the no-argument constructor of the - * default or custom class, and then calls initialize() passing the parameter map and World. - */ + * default or custom class, and then calls initialize() passing the parameter map and World. */ public static FieldElement createFromParameters (Map params, World world, Class defaultClass) { try { if (params.containsKey("class")) { @@ -54,10 +50,8 @@ public static FieldElement createFromParameters (Map params, World world, Class } } - /** - * Extracts common values from the definition parameter map, and calls finishCreate to allow subclasses to further initialize - * themselves. Subclasses should override finishCreate, and should not override this method. - */ + /** Extracts common values from the definition parameter map, and calls finishCreate to allow subclasses to further initialize + * themselves. Subclasses should override finishCreate, and should not override this method. */ public void initialize (Map params, World world) { this.parameters = params; this.box2dWorld = world; @@ -75,80 +69,58 @@ public void initialize (Map params, World world) { this.finishCreate(params, world); } - /** - * Called after creation to determine if tick() needs to be called after every frame is simulated. Default returns false, + /** Called after creation to determine if tick() needs to be called after every frame is simulated. Default returns false, * subclasses must override to return true in order for tick() to be called. This is an optimization to avoid needless method - * calls in the game loop. - */ + * calls in the game loop. */ public boolean shouldCallTick () { return false; } - /** - * Called on every update from Field.tick. Default implementation decrements flash counter if active, subclasses can override + /** Called on every update from Field.tick. Default implementation decrements flash counter if active, subclasses can override * to perform additional processing, e.g. RolloverGroupElement checking for balls within radius of rollovers. Subclasses should - * call super.tick(field). - */ + * call super.tick(field). */ public void tick (Field field) { if (flashCounter > 0) flashCounter--; } - /** - * Called when the player activates one or more flippers. The default implementation does nothing; subclasses can override. - */ + /** Called when the player activates one or more flippers. The default implementation does nothing; subclasses can override. */ public void flipperActivated (Field field) { } - /** - * Causes the colors returned by red/blue/greenColorComponent methods to be inverted for the given number of frames. This can - * be used to flash an element when it is hit by a ball, see PegElement. - */ + /** Causes the colors returned by red/blue/greenColorComponent methods to be inverted for the given number of frames. This can + * be used to flash an element when it is hit by a ball, see PegElement. */ public void flashForFrames (int frames) { flashCounter = frames; } - /** - * Must be overridden by subclasses, which should perform any setup required after creation. - */ + /** Must be overridden by subclasses, which should perform any setup required after creation. */ public abstract void finishCreate (Map params, World world); - /** - * Must be overridden by subclasses to return a collection of all Box2D bodies which make up this element. - */ + /** Must be overridden by subclasses to return a collection of all Box2D bodies which make up this element. */ public abstract Collection getBodies (); - /** - * Must be overridden by subclasses to draw the element, using IFieldRenderer methods. - */ + /** Must be overridden by subclasses to draw the element, using IFieldRenderer methods. */ public abstract void draw (IFieldRenderer renderer); - /** - * Called when a ball collides with a Body in this element. The default implementation does nothing (allowing objects to bounce - * off each other normally), subclasses can override (e.g. to apply extra force) - */ + /** Called when a ball collides with a Body in this element. The default implementation does nothing (allowing objects to bounce + * off each other normally), subclasses can override (e.g. to apply extra force) */ public void handleCollision (Body ball, Body bodyHit, Field field) { } - /** - * Returns this element's ID as specified in the JSON definition, or null if the ID is not specified. - */ + /** Returns this element's ID as specified in the JSON definition, or null if the ID is not specified. */ public String getElementID () { return elementID; } - /** - * Returns the parameter map from which this element was created. - */ + /** Returns the parameter map from which this element was created. */ public Map getParameters () { return parameters; } - /** - * Returns the "score" value for this element. The score is automatically added when the element is hit by a ball, and elements + /** Returns the "score" value for this element. The score is automatically added when the element is hit by a ball, and elements * may apply scores under other conditions, e.g. RolloverGroupElement adds the score when a ball comes within range of a - * rollover. - */ + * rollover. */ public long getScore () { return score; } @@ -160,26 +132,20 @@ protected int colorComponent (int index, int defvalue) { return (flashCounter > 0) ? 255 - value : value; } - /** - * Returns the red component of this element's base color, taken from the "color" parameter. If there is no color parameter, - * the default argument is returned. - */ + /** Returns the red component of this element's base color, taken from the "color" parameter. If there is no color parameter, + * the default argument is returned. */ protected int redColorComponent (int defvalue) { return colorComponent(0, defvalue); } - /** - * Returns the green component of this element's base color, taken from the "color" parameter. If there is no color parameter, - * the default argument is returned. - */ + /** Returns the green component of this element's base color, taken from the "color" parameter. If there is no color parameter, + * the default argument is returned. */ protected int greenColorComponent (int defvalue) { return colorComponent(1, defvalue); } - /** - * Returns the blue component of this element's base color, taken from the "color" parameter. If there is no color parameter, - * the default argument is returned. - */ + /** Returns the blue component of this element's base color, taken from the "color" parameter. If there is no color parameter, + * the default argument is returned. */ protected int blueColorComponent (int defvalue) { return colorComponent(2, defvalue); } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FlipperElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FlipperElement.java index 99099b60784..a47e155a910 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FlipperElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/FlipperElement.java @@ -17,16 +17,14 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * FieldElement subclass for a flipper that is controlled by the player. A flipper consists of a Box2D RevoluteJoint where a thin +/** FieldElement subclass for a flipper that is controlled by the player. A flipper consists of a Box2D RevoluteJoint where a thin * wall rotates around an invisible anchor. Flippers are defined in the layout JSON as follows: { "class": "FlipperElement", * "position": [5.5, 10], // x,y of fixed end of flipper which it rotates around "length": 2.5, // length of the flipper. Negative * if the flipper rotates around its right end. "minangle": -20, // minimum angle from the horizontal. Negative angles are below * horizontal. "maxangle": 20, // maximum angle from the horizontal. "upspeed": 7, // rate at which the flipper rotates up when * activated (in radians/sec?) "downspeed": 3 // rate at which the flipper rotates down when not activated (in radians/sec?) } * - * @author brian - */ + * @author brian */ public class FlipperElement extends FieldElement { @@ -41,7 +39,8 @@ public class FlipperElement extends FieldElement { float minangle, maxangle; float cx, cy; - @Override public void finishCreate (Map params, World world) { + @Override + public void finishCreate (Map params, World world) { List pos = (List)params.get("position"); this.cx = asFloat(pos.get(0)); @@ -94,15 +93,18 @@ void setEffectiveMotorSpeed (float speed) { joint.setMotorSpeed(speed); } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return flipperBodySet; } - @Override public boolean shouldCallTick () { + @Override + public boolean shouldCallTick () { return true; } - @Override public void tick (Field field) { + @Override + public void tick (Field field) { super.tick(field); // if angle is at maximum, reduce speed so that the ball won't fly off when it hits @@ -138,7 +140,8 @@ public Body getAnchorBody () { return anchorBody; } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { // draw single line segment from anchor point Vector2 position = anchorBody.getPosition(); float angle = joint.getJointAngle(); diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/RolloverGroupElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/RolloverGroupElement.java index 14869885a32..228558e3db4 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/RolloverGroupElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/RolloverGroupElement.java @@ -15,13 +15,11 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * This class represents a collection of rollover elements, such as the rollovers in the top lanes. They are activated (and +/** This class represents a collection of rollover elements, such as the rollovers in the top lanes. They are activated (and * optionally deactivated) when a ball passes over them. Individual rollovers in the group are represented by instances of the * Rollover nested class, which specify center, radius, and color. Parameters at the collection level control whether the * rollovers should cycle when flippers are activated, and whether rollovers can toggle from on to off. - * @author brian - */ + * @author brian */ public class RolloverGroupElement extends FieldElement { @@ -44,7 +42,8 @@ static class Rollover { List rolloversHitOnPreviousTick = new ArrayList(); - @Override public void finishCreate (Map params, World world) { + @Override + public void finishCreate (Map params, World world) { this.canToggleOff = Boolean.TRUE.equals(params.get("toggleOff")); this.cycleOnFlipper = Boolean.TRUE.equals(params.get("cycleOnFlipper")); this.ignoreBall = Boolean.TRUE.equals(params.get("ignoreBall")); @@ -69,7 +68,8 @@ static class Rollover { } } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return Collections.EMPTY_SET; } @@ -106,9 +106,7 @@ public boolean allRolloversActive () { return activeRollovers.size() == rollovers.size(); } - /** - * Activates the first unactivated rollover in the group. Has no effect if all are active. - */ + /** Activates the first unactivated rollover in the group. Has no effect if all are active. */ public void activateFirstUnactivatedRollover () { int len = rollovers.size(); for (int i = 0; i < len; i++) { @@ -120,12 +118,14 @@ public void activateFirstUnactivatedRollover () { } } - @Override public boolean shouldCallTick () { + @Override + public boolean shouldCallTick () { return true; } - @Override public void tick (Field field) { + @Override + public void tick (Field field) { if (this.ignoreBall) return; boolean allActivePrevious = this.allRolloversActive(); @@ -164,7 +164,8 @@ public void run () { } } - @Override public void flipperActivated (Field field) { + @Override + public void flipperActivated (Field field) { if (this.cycleOnFlipper) { this.cycleRollovers(); } @@ -172,11 +173,9 @@ public void run () { List newActiveRollovers = new ArrayList(); - /** - * Cycles the states of all rollover elements by "rotating" right. For example, if this group has three rollovers whose states + /** Cycles the states of all rollover elements by "rotating" right. For example, if this group has three rollovers whose states * are (on, on, off), after calling this method the states will be (off, on, on). The state of the last rollover wraps around - * to the first, so (off, off, on) -> (on, off, off). - */ + * to the first, so (off, off, on) -> (on, off, off). */ public void cycleRollovers () { newActiveRollovers.clear(); for (int i = 0; i < this.rollovers.size(); i++) { @@ -189,9 +188,7 @@ public void cycleRollovers () { this.activeRollovers.addAll(newActiveRollovers); } - /** - * Sets all rollovers to be active or inactive according to the boolean argument. - */ + /** Sets all rollovers to be active or inactive according to the boolean argument. */ public void setAllRolloversActivated (boolean active) { activeRollovers.clear(); if (active) { @@ -199,7 +196,8 @@ public void setAllRolloversActivated (boolean active) { } } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { // default color defined at the group level int defaultRed = this.redColorComponent(0); int defaultGreen = this.greenColorComponent(255); diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/SensorElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/SensorElement.java index acc44340577..d321151c523 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/SensorElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/SensorElement.java @@ -14,15 +14,12 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * This FieldElement subclass is used to identify areas on the table that should cause custom behavior when the ball enters. +/** This FieldElement subclass is used to identify areas on the table that should cause custom behavior when the ball enters. * SensorElements have no bodies and don't draw anything. The area they monitor can be a rectangle defined by the "rect" parameter * as a [xmin,ymin,xmax,ymax] list, a circle defined by the "center" and "radius" parameters. During every tick() invocation, a * sensor determines if any of the field's balls are within its area, and if so calls the field delegate's ballInSensorRange * method. - * @author brian - * - */ + * @author brian */ public class SensorElement extends FieldElement { @@ -31,7 +28,8 @@ public class SensorElement extends FieldElement { float cx, cy; // center for circular areas float radiusSquared; - @Override public void finishCreate (Map params, World world) { + @Override + public void finishCreate (Map params, World world) { if (params.containsKey("center") && params.containsKey("radius")) { this.circular = true; List centerPos = (List)params.get("center"); @@ -53,7 +51,8 @@ public class SensorElement extends FieldElement { } } - @Override public boolean shouldCallTick () { + @Override + public boolean shouldCallTick () { return true; } @@ -71,7 +70,8 @@ boolean ballInRange (Body ball) { return true; } - @Override public void tick (Field field) { + @Override + public void tick (Field field) { int len = field.getBalls().size(); for (int i = 0; i < len; i++) { Body ball = field.getBalls().get(i); @@ -82,11 +82,13 @@ boolean ballInRange (Body ball) { } } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return Collections.EMPTY_SET; } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { // no UI } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallArcElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallArcElement.java index 1f99cd7b449..b77a4caeecc 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallArcElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallArcElement.java @@ -12,8 +12,7 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * This FieldElement subclass approximates a circular wall with a series of straight wall segments whose endpoints lie on a circle +/** This FieldElement subclass approximates a circular wall with a series of straight wall segments whose endpoints lie on a circle * or ellipse. These elements are defined in the layout JSON as follows: { "class": "WallArcElement", "center": [5.5, 10], // * center of circle or ellipse "xradius": 2.5, // radius in the horizontal direction "yradius": 2, // radius in the y direction * "minangle": 45, // starting angle in degrees, 0 is to the right of the center, 90 is up. "maxangle": 135, // ending angle in @@ -22,8 +21,7 @@ * * For circular walls, the "radius" attribute can be used instead of xradius and yradius. * - * @author brian - */ + * @author brian */ public class WallArcElement extends FieldElement { @@ -64,11 +62,13 @@ public void finishCreate (Map params, World world) { } } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return wallBodies; } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { int len = lineSegments.size(); for (int i = 0; i < len; i++) { float[] segment = lineSegments.get(i); diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallElement.java index d3011841752..93eeeaa6316 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallElement.java @@ -14,8 +14,7 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * FieldElement subclass that represents a straight wall. Its position is specified by the "position" parameter with 4 values, +/** FieldElement subclass that represents a straight wall. Its position is specified by the "position" parameter with 4 values, * which are [start x, start y, end x, end y]. There are several optional parameters to customize the wall's behavior: "kick": * impulse to apply when a ball hits the wall, used for kickers and ball savers. "kill": if true, the ball is lost when it hits * the wall. Used for invisible wall below the flippers. "retractWhenHit": if true, the wall is removed when hit by a ball. Used @@ -24,9 +23,7 @@ * * Walls can be removed from the field by calling setRetracted(field, true), and restored with setRetracted(field, false). * - * @author brian - * - */ + * @author brian */ public class WallElement extends FieldElement { @@ -38,7 +35,8 @@ public class WallElement extends FieldElement { boolean killBall; boolean retractWhenHit; - @Override public void finishCreate (Map params, World world) { + @Override + public void finishCreate (Map params, World world) { List pos = (List)params.get("position"); this.x1 = asFloat(pos.get(0)); this.y1 = asFloat(pos.get(1)); @@ -69,11 +67,13 @@ public void setRetracted (boolean retracted) { } } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return bodySet; } - @Override public boolean shouldCallTick () { + @Override + public boolean shouldCallTick () { // tick() only needs to be called if this wall provides a kick which makes it flash return (this.kick > 0.01f); } @@ -99,7 +99,8 @@ Vector2 impulseForBall (Body ball) { return new Vector2(ix, iy); } - @Override public void handleCollision (Body ball, Body bodyHit, Field field) { + @Override + public void handleCollision (Body ball, Body bodyHit, Field field) { if (retractWhenHit) { this.setRetracted(true); } @@ -115,7 +116,8 @@ Vector2 impulseForBall (Body ball) { } } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { if (isRetracted()) return; renderer.drawLine(x1, y1, x2, y2, redColorComponent(DEFAULT_WALL_RED), greenColorComponent(DEFAULT_WALL_GREEN), blueColorComponent(DEFAULT_WALL_BLUE)); diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallPathElement.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallPathElement.java index 5309933d536..01b43e95adb 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallPathElement.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/elements/WallPathElement.java @@ -12,12 +12,10 @@ import static com.dozingcatsoftware.bouncy.util.MathUtils.*; -/** - * FieldElement subclass which represents a series of wall segments. The segments are defined in the "positions" parameter as a +/** FieldElement subclass which represents a series of wall segments. The segments are defined in the "positions" parameter as a * list of [x,y] values, for example: { "class": "WallPathElement", "positions": [[5,5], [5,10], [8,10], [5, 15]] } * - * @author brian - */ + * @author brian */ public class WallPathElement extends FieldElement { @@ -40,11 +38,13 @@ public void finishCreate (Map params, World world) { } } - @Override public Collection getBodies () { + @Override + public Collection getBodies () { return wallBodies; } - @Override public void draw (IFieldRenderer renderer) { + @Override + public void draw (IFieldRenderer renderer) { int len = lineSegments.size(); for (int i = 0; i < len; i++) { float[] segment = lineSegments.get(i); diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/fields/Field1Delegate.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/fields/Field1Delegate.java index cc0c8e99167..125b5775435 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/fields/Field1Delegate.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/fields/Field1Delegate.java @@ -10,7 +10,8 @@ public class Field1Delegate extends BaseFieldDelegate { - @Override public void allRolloversInGroupActivated (Field field, RolloverGroupElement rolloverGroup) { + @Override + public void allRolloversInGroupActivated (Field field, RolloverGroupElement rolloverGroup) { // rollover groups increment field multiplier when all rollovers are activated, also reset to inactive rolloverGroup.setAllRolloversActivated(false); field.getGameState().incrementScoreMultiplier(); @@ -28,7 +29,8 @@ public class Field1Delegate extends BaseFieldDelegate { } - @Override public void allDropTargetsInGroupHit (Field field, DropTargetGroupElement targetGroup) { + @Override + public void allDropTargetsInGroupHit (Field field, DropTargetGroupElement targetGroup) { // activate ball saver for left and right groups String id = targetGroup.getElementID(); if ("DropTargetLeftSave".equals(id)) { @@ -54,18 +56,21 @@ void setLaunchBarrierEnabled (Field field, boolean enabled) { barrier.setRetracted(!enabled); } - @Override public void ballInSensorRange (Field field, SensorElement sensor) { + @Override + public void ballInSensorRange (Field field, SensorElement sensor) { // enable launch barrier if ("LaunchBarrierSensor".equals(sensor.getElementID())) { setLaunchBarrierEnabled(field, true); } } - @Override public void gameStarted (Field field) { + @Override + public void gameStarted (Field field) { setLaunchBarrierEnabled(field, false); } - @Override public void ballLost (Field field) { + @Override + public void ballLost (Field field) { setLaunchBarrierEnabled(field, false); } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONArray.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONArray.java index 1c63998d9f6..2fa3ec3d198 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONArray.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONArray.java @@ -1,28 +1,29 @@ + package com.dozingcatsoftware.bouncy.util; /* -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; @@ -32,885 +33,648 @@ of this software and associated documentation files (the "Software"), to deal 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 2010-12-28 - */ + * @version 2010-12-28 */ public class JSONArray { + /** The arrayList where the JSONArray's properties are kept. */ + private ArrayList myArrayList; - /** - * The arrayList where the JSONArray's properties are kept. - */ - private ArrayList myArrayList; - - - /** - * Construct an empty JSONArray. - */ - public JSONArray() { - this.myArrayList = new ArrayList(); - } - - /** - * Construct a JSONArray from a JSONTokener. - * @param x A JSONTokener - * @throws JSONException If there is a syntax error. - */ - public JSONArray(JSONTokener x) throws JSONException { - this(); - if (x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if (x.nextClean() != ']') { - x.back(); - for (;;) { - if (x.nextClean() == ',') { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == ']') { - return; - } - x.back(); - break; - case ']': - 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. - */ - public JSONArray(Collection collection) { + /** Construct an empty JSONArray. */ + public JSONArray () { + this.myArrayList = new ArrayList(); + } + + /** Construct a JSONArray from a JSONTokener. + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. */ + public JSONArray (JSONTokener x) throws JSONException { + this(); + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() != ']') { + x.back(); + for (;;) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': + 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. */ + public JSONArray (Collection collection) { this.myArrayList = new ArrayList(); if (collection != null) { Iterator iter = collection.iterator(); while (iter.hasNext()) { - this.myArrayList.add(JSONObject.wrap(iter.next())); + this.myArrayList.add(JSONObject.wrap(iter.next())); + } + } + } + + /** 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 object = opt(index); + if (object == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } + + /** 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 convertible to boolean. */ + public boolean getBoolean (int index) throws JSONException { + Object object = get(index); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).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 object = get(index); + try { + return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); + } 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 is not a number. */ + public int getInt (int index) throws JSONException { + Object object = get(index); + try { + return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + /** 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 object = get(index); + if (object instanceof JSONArray) { + return (JSONArray)object; + } + 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 object = get(index); + if (object instanceof JSONObject) { + return (JSONObject)object; + } + 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 object = get(index); + try { + return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + /** 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 { + Object object = get(index); + return object == JSONObject.NULL ? null : object.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 object = opt(index); + return object != null ? object.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. */ + 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. */ + 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. */ + 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. */ + 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. */ + 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. */ + 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 object = opt(index); - if (object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } - - - /** - * 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 convertible to boolean. - */ - public boolean getBoolean(int index) throws JSONException { - Object object = get(index); - if (object.equals(Boolean.FALSE) || - (object instanceof String && - ((String)object).equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) || - (object instanceof String && - ((String)object).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 object = get(index); - try { - return object instanceof Number ? - ((Number)object).doubleValue() : - Double.parseDouble((String)object); - } 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 is not a number. - */ - public int getInt(int index) throws JSONException { - Object object = get(index); - try { - return object instanceof Number ? - ((Number)object).intValue() : - Integer.parseInt((String)object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - - /** - * 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 object = get(index); - if (object instanceof JSONArray) { - return (JSONArray)object; - } - 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 object = get(index); - if (object instanceof JSONObject) { - return (JSONObject)object; - } - 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 object = get(index); - try { - return object instanceof Number ? - ((Number)object).longValue() : - Long.parseLong((String)object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - - /** - * 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 { - Object object = get(index); - return object == JSONObject.NULL ? null : object.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 object = opt(index); - return object != null ? object.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. - */ - 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. - */ - 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. - */ - 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. - */ - 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. - */ - 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. - */ - 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/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONException.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONException.java index 7483d0bbbb9..58514f06185 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONException.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONException.java @@ -1,28 +1,25 @@ + package com.dozingcatsoftware.bouncy.util; -/** - * The JSONException is thrown by the JSON.org classes when things are amiss. +/** The JSONException is thrown by the JSON.org classes when things are amiss. * @author JSON.org - * @version 2010-12-24 - */ + * @version 2010-12-24 */ 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 cause) { - super(cause.getMessage()); - this.cause = cause; - } + public JSONException (Throwable cause) { + super(cause.getMessage()); + this.cause = cause; + } - public Throwable getCause() { - return this.cause; - } + public Throwable getCause () { + return this.cause; + } } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONObject.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONObject.java index de3ffde9f01..519023c5b3d 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONObject.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONObject.java @@ -1,34 +1,35 @@ + package com.dozingcatsoftware.bouncy.util; /* -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.Enumeration; import java.util.HashMap; @@ -37,1584 +38,1238 @@ of this software and associated documentation files (the "Software"), to deal import java.util.Map; import java.util.ResourceBundle; -/** - * 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 opt methods differ from the get methods in that they - * do not throw. Instead, they return a specified value, such as null. + * 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 opt methods + * differ from the get methods in that they do not throw. Instead, they return a specified value, such as null. *

    - * The put methods add or replace values in an object. For example, - *

    myString = new JSONObject().put("JSON", "Hello, World!").toString();
    + * The put methods add or replace values in 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 2011-01-31 - */ + * @version 2011-01-31 */ 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(); - } + /** 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()); + 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(); - Object value = e.getValue(); - if (value != null) { - this.map.put(e.getKey(), wrap(value)); - } - } - } - } - - - /** - * 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)); - } - - - /** - * Construct a JSONObject from a ResourceBundle. - * @param baseName The ResourceBundle base name. - * @param locale The Locale to load the ResourceBundle for. - * @throws JSONException If any JSONExceptions are detected. - */ - public JSONObject(String baseName, Locale locale) throws JSONException { - this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, - Thread.currentThread().getContextClassLoader()); + 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(); + Object value = e.getValue(); + if (value != null) { + this.map.put(e.getKey(), wrap(value)); + } + } + } + } + + /** 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)); + } + + /** Construct a JSONObject from a ResourceBundle. + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. */ + public JSONObject (String baseName, Locale locale) throws JSONException { + this(); + ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. - - Enumeration keys = bundle.getKeys(); - while (keys.hasMoreElements()) { - Object key = keys.nextElement(); - if (key instanceof String) { - -// Go through the path, ensuring that there is a nested JSONObject for each + + Enumeration keys = bundle.getKeys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + if (key instanceof String) { + +// Go through the path, ensuring that there is a nested JSONObject for each // segment except the last. Add the value using the last segment's name into // the deepest nested JSONObject. - - String[] path = ((String)key).split("\\."); - int last = path.length - 1; - JSONObject target = this; - for (int i = 0; i < last; i += 1) { - String segment = path[i]; - JSONObject nextTarget = target.optJSONObject(segment); - if (nextTarget == null) { - nextTarget = new JSONObject(); - target.put(segment, nextTarget); - } - target = nextTarget; - } - target.put(path[last], bundle.getString((String)key)); - } - } - } - - - /** - * 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. - * - * If only one value is accumulated that is not a JSONArray, then the - * result will be the same as using put. But if multiple values are - * accumulated, then the result will be like append. - * @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 object = opt(key); - if (object == null) { - put(key, value instanceof JSONArray ? - new JSONArray().put(value) : value); - } else if (object instanceof JSONArray) { - ((JSONArray)object).put(value); - } else { - put(key, new JSONArray().put(object).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 object = opt(key); - if (object == null) { - put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { - put(key, ((JSONArray)object).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. - */ - public static String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } + + String[] path = ((String)key).split("\\."); + int last = path.length - 1; + JSONObject target = this; + for (int i = 0; i < last; i += 1) { + String segment = path[i]; + JSONObject nextTarget = target.optJSONObject(segment); + if (nextTarget == null) { + nextTarget = new JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], bundle.getString((String)key)); + } + } + } + + /** 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. + * + * If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if multiple + * values are accumulated, then the result will be like append. + * @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 object = opt(key); + if (object == null) { + put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + } else if (object instanceof JSONArray) { + ((JSONArray)object).put(value); + } else { + put(key, new JSONArray().put(object).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 object = opt(key); + if (object == null) { + put(key, new JSONArray().put(value)); + } else if (object instanceof JSONArray) { + put(key, ((JSONArray)object).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. */ + public static String doubleToString (double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } // Shave off trailing zeros and decimal point, if possible. - String string = Double.toString(d); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && - string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - - /** - * 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 { - if (key == null) { - throw new JSONException("Null key."); - } - Object object = opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + - "] not found."); - } - return object; - } - - - /** - * 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 object = get(key); - if (object.equals(Boolean.FALSE) || - (object instanceof String && - ((String)object).equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) || - (object instanceof String && - ((String)object).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 object = get(key); - try { - return object instanceof Number ? - ((Number)object).doubleValue() : - Double.parseDouble((String)object); - } 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 object = get(key); - try { - return object instanceof Number ? - ((Number)object).intValue() : - Integer.parseInt((String)object); - } 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 object = get(key); - if (object instanceof JSONArray) { - return (JSONArray)object; - } - 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 object = get(key); - if (object instanceof JSONObject) { - return (JSONObject)object; - } - 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 object = get(key); - try { - return object instanceof Number ? - ((Number)object).longValue() : - Long.parseLong((String)object); - } 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 iterator = jo.keys(); - String[] names = new String[length]; - int i = 0; - while (iterator.hasNext()) { - names[i] = (String)iterator.next(); - i += 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 { - Object object = get(key); - return object == NULL ? null : object.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 [" + quote(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 = this.keys(); - while (keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - /** - * Produce a string from a Number. - * @param number A Number - * @return A String. - * @throws JSONException If n is a non-finite number. - */ - public static String numberToString(Number number) - throws JSONException { - if (number == null) { - throw new JSONException("Null pointer"); - } - testValidity(number); + String string = Double.toString(d); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** 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 { + if (key == null) { + throw new JSONException("Null key."); + } + Object object = opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return object; + } + + /** 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 object = get(key); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).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 object = get(key); + try { + return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); + } 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 object = get(key); + try { + return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); + } 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 object = get(key); + if (object instanceof JSONArray) { + return (JSONArray)object; + } + 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 object = get(key); + if (object instanceof JSONObject) { + return (JSONObject)object; + } + 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 object = get(key); + try { + return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); + } 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 iterator = jo.keys(); + String[] names = new String[length]; + int i = 0; + while (iterator.hasNext()) { + names[i] = (String)iterator.next(); + i += 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 { + Object object = get(key); + return object == NULL ? null : object.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 [" + quote(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 = this.keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** Produce a string from a Number. + * @param number A Number + * @return A String. + * @throws JSONException If n is a non-finite number. */ + public static String numberToString (Number number) throws JSONException { + if (number == null) { + throw new JSONException("Null pointer"); + } + testValidity(number); // Shave off trailing zeros and decimal point, if possible. - String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && - string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - - /** - * 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 { - return getDouble(key); - } 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 object = opt(key); - return object instanceof JSONObject ? (JSONObject)object : 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 converted 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 object = opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - - 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); - if (result != 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')) { - hhhh = "000" + Integer.toHexString(c); - sb.append("\\u" + hhhh.substring(hhhh.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); - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * @param string A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) { - if (string.equals("")) { - return string; - } - if (string.equalsIgnoreCase("true")) { - return Boolean.TRUE; - } - if (string.equalsIgnoreCase("false")) { - return Boolean.FALSE; - } - if (string.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 = string.charAt(0); - if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { - if (b == '0' && string.length() > 2 && - (string.charAt(1) == 'x' || string.charAt(1) == 'X')) { - try { - return new Integer(Integer.parseInt(string.substring(2), 16)); - } catch (Exception ignore) { - } - } - try { - if (string.indexOf('.') > -1 || - string.indexOf('e') > -1 || string.indexOf('E') > -1) { - return Double.valueOf(string); - } else { - Long myLong = new Long(string); - if (myLong.longValue() == myLong.intValue()) { - return new Integer(myLong.intValue()); - } else { - return myLong; - } - } - } catch (Exception ignore) { - } - } - return string; - } - - - /** - * Throw an exception if the object is a NaN or infinite number. - * @param o The object to test. - * @throws JSONException If o is a non-finite number. - */ - public 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 = this.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 i; - int length = this.length(); - if (length == 0) { - return "{}"; - } - Iterator keys = this.keys(); - int newindent = indent + indentFactor; - Object object; - StringBuffer sb = new StringBuffer("{"); - if (length == 1) { - object = keys.next(); - sb.append(quote(object.toString())); - sb.append(": "); - sb.append(valueToString(this.map.get(object), indentFactor, - indent)); - } else { - while (keys.hasNext()) { - object = keys.next(); - if (sb.length() > 1) { - sb.append(",\n"); - } else { - sb.append('\n'); - } - for (i = 0; i < newindent; i += 1) { - sb.append(' '); - } - sb.append(quote(object.toString())); - sb.append(": "); - sb.append(valueToString(this.map.get(object), indentFactor, - newindent)); - } - if (sb.length() > 1) { - sb.append('\n'); - for (i = 0; i < indent; i += 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. - */ - public static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { - Object object; - try { - object = ((JSONString)value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (object instanceof String) { - return (String)object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - 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 - */ - public 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 commanate = false; - Iterator keys = this.keys(); - writer.write('{'); - - while (keys.hasNext()) { - if (commanate) { - writer.write(','); - } - Object key = keys.next(); - writer.write(quote(key.toString())); - writer.write(':'); - Object value = this.map.get(key); - if (value instanceof JSONObject) { - ((JSONObject)value).write(writer); - } else if (value instanceof JSONArray) { - ((JSONArray)value).write(writer); - } else { - writer.write(valueToString(value)); - } - commanate = true; - } - writer.write('}'); - return writer; - } catch (IOException exception) { - throw new JSONException(exception); - } - } -} \ No newline at end of file + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** 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 { + return getDouble(key); + } 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 object = opt(key); + return object instanceof JSONObject ? (JSONObject)object : 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 converted 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 object = opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + 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); + if (result != 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')) { + hhhh = "000" + Integer.toHexString(c); + sb.append("\\u" + hhhh.substring(hhhh.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); + } + + /** Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. + * @param string A String. + * @return A simple JSON value. */ + public static Object stringToValue (String string) { + if (string.equals("")) { + return string; + } + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.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 = string.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { + if (b == '0' && string.length() > 2 && (string.charAt(1) == 'x' || string.charAt(1) == 'X')) { + try { + return new Integer(Integer.parseInt(string.substring(2), 16)); + } catch (Exception ignore) { + } + } + try { + if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { + return Double.valueOf(string); + } else { + Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()) { + return new Integer(myLong.intValue()); + } else { + return myLong; + } + } + } catch (Exception ignore) { + } + } + return string; + } + + /** Throw an exception if the object is a NaN or infinite number. + * @param o The object to test. + * @throws JSONException If o is a non-finite number. */ + public 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 = this.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 i; + int length = this.length(); + if (length == 0) { + return "{}"; + } + Iterator keys = this.keys(); + int newindent = indent + indentFactor; + Object object; + StringBuffer sb = new StringBuffer("{"); + if (length == 1) { + object = keys.next(); + sb.append(quote(object.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(object), indentFactor, indent)); + } else { + while (keys.hasNext()) { + object = keys.next(); + if (sb.length() > 1) { + sb.append(",\n"); + } else { + sb.append('\n'); + } + for (i = 0; i < newindent; i += 1) { + sb.append(' '); + } + sb.append(quote(object.toString())); + sb.append(": "); + sb.append(valueToString(this.map.get(object), indentFactor, newindent)); + } + if (sb.length() > 1) { + sb.append('\n'); + for (i = 0; i < indent; i += 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. */ + public static String valueToString (Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + Object object; + try { + object = ((JSONString)value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + if (object instanceof String) { + return (String)object; + } + throw new JSONException("Bad value from toJSONString: " + object); + } + 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 */ + public 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 commanate = false; + Iterator keys = this.keys(); + writer.write('{'); + + while (keys.hasNext()) { + if (commanate) { + writer.write(','); + } + Object key = keys.next(); + writer.write(quote(key.toString())); + writer.write(':'); + Object value = this.map.get(key); + if (value instanceof JSONObject) { + ((JSONObject)value).write(writer); + } else if (value instanceof JSONArray) { + ((JSONArray)value).write(writer); + } else { + writer.write(valueToString(value)); + } + commanate = true; + } + writer.write('}'); + return writer; + } catch (IOException exception) { + throw new JSONException(exception); + } + } +} diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONString.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONString.java index 7c8d30be266..6a68285870c 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONString.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONString.java @@ -1,18 +1,13 @@ + package com.dozingcatsoftware.bouncy.util; -/** - * 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(); + * @return A strictly syntactically correct JSON text. */ + public String toJSONString (); } diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONStringer.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONStringer.java index 6b6b3749809..5248d57d48c 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONStringer.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONStringer.java @@ -1,78 +1,68 @@ + package com.dozingcatsoftware.bouncy.util; /* -Copyright (c) 2006 JSON.org + 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: + 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 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 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. -*/ + 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 - */ + * @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/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONTokener.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONTokener.java index b8e152bee3f..a7e88c5e37b 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONTokener.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONTokener.java @@ -1,3 +1,4 @@ + package com.dozingcatsoftware.bouncy.util; import java.io.BufferedReader; @@ -8,438 +9,366 @@ 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. -*/ - -/** - * 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-12-24 + 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. + * @author JSON.org + * @version 2010-12-24 */ 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 an InputStream. - */ - public JSONTokener(InputStream inputStream) throws JSONException { - this(new InputStreamReader(inputStream)); - } - - - /** - * 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[] chars = new char[n]; - int pos = 0; - - while (pos < n) { - chars[pos] = next(); - if (end()) { - throw syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } - - - /** - * 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 delimiter A delimiter character. - * @return A string. - */ - public String nextTo(char delimiter) throws JSONException { - StringBuffer sb = new StringBuffer(); - for (;;) { - char c = next(); - if (c == delimiter || 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 string; - - switch (c) { - case '"': - case '\'': - return nextString(c); - case '{': - back(); - return new JSONObject(this); - 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(); - - string = sb.toString().trim(); - if (string.equals("")) { - throw syntaxError("Missing value"); - } - return JSONObject.stringToValue(string); - } - - - /** - * 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 an InputStream. */ + public JSONTokener (InputStream inputStream) throws JSONException { + this(new InputStreamReader(inputStream)); + } + + /** 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[] chars = new char[n]; + int pos = 0; + + while (pos < n) { + chars[pos] = next(); + if (end()) { + throw syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } + + /** 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 delimiter A delimiter character. + * @return A string. */ + public String nextTo (char delimiter) throws JSONException { + StringBuffer sb = new StringBuffer(); + for (;;) { + char c = next(); + if (c == delimiter || 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 string; + + switch (c) { + case '"': + case '\'': + return nextString(c); + case '{': + back(); + return new JSONObject(this); + 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(); + + string = sb.toString().trim(); + if (string.equals("")) { + throw syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } + + /** 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/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONUtils.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONUtils.java index aeb632db574..51e2cbc600b 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONUtils.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONUtils.java @@ -9,10 +9,8 @@ public class JSONUtils { - /** - * If argument is a JSONArray or JSONObject, returns the equivalent List or Map. If argument is JSONObject.NULL, returns null. - * Otherwise, returns the argument unchanged. - */ + /** If argument is a JSONArray or JSONObject, returns the equivalent List or Map. If argument is JSONObject.NULL, returns null. + * Otherwise, returns the argument unchanged. */ public static Object objectFromJSONItem (Object jsonItem) { if (jsonItem == JSONObject.NULL) { return null; @@ -26,10 +24,8 @@ public static Object objectFromJSONItem (Object jsonItem) { return jsonItem; } - /** - * Returns a List with the same objects in the same order as jsonArray. Recursively converts nested JSONArray and JSONObject - * values to List and Map objects. - */ + /** Returns a List with the same objects in the same order as jsonArray. Recursively converts nested JSONArray and JSONObject + * values to List and Map objects. */ public static List listFromJSONArray (JSONArray jsonArray) { List result = new ArrayList(); try { @@ -43,10 +39,8 @@ public static List listFromJSONArray (JSONArray jsonArray) { return result; } - /** - * Returns a List with the same keys and values as jsonObject. Recursively converts nested JSONArray and JSONObject values to - * List and Map objects. - */ + /** Returns a List with the same keys and values as jsonObject. Recursively converts nested JSONArray and JSONObject values to + * List and Map objects. */ public static Map mapFromJSONObject (JSONObject jsonObject) { Map result = new HashMap(); try { @@ -61,9 +55,7 @@ public static Map mapFromJSONObject (JSONObject jsonObject) { return result; } - /** - * Returns a List created by parsing the string argument as a JSON array and calling listFromJSONArray. - */ + /** Returns a List created by parsing the string argument as a JSON array and calling listFromJSONArray. */ public static List listFromJSONString (String jsonString) { try { return listFromJSONArray(new JSONArray(jsonString)); @@ -72,9 +64,7 @@ public static List listFromJSONString (String jsonString) { } } - /** - * Returns a Map created by parsing the string argument as a JSON object and calling mapFromJSONObject. - */ + /** Returns a Map created by parsing the string argument as a JSON object and calling mapFromJSONObject. */ public static Map mapFromJSONString (String jsonString) { try { return mapFromJSONObject(new JSONObject(jsonString)); diff --git a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONWriter.java b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONWriter.java index 67572475494..0b2cfdbf787 100644 --- a/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONWriter.java +++ b/demos/vector-pinball/gdx-vectorpinball/src/com/dozingcatsoftware/bouncy/util/JSONWriter.java @@ -1,323 +1,261 @@ + package com.dozingcatsoftware.bouncy.util; import java.io.IOException; import java.io.Writer; /* -Copyright (c) 2006 JSON.org + 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: + 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 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 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. -*/ + 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-12-24 - */ + * @version 2010-12-24 */ 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 string A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if (string == 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(string); - } 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 mode Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char mode, char c) throws JSONException { - if (this.mode != mode) { - throw new JSONException(mode == 'a' ? "Misplaced endArray." : - "Misplaced endObject."); - } - this.pop(mode); - 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 string A string value. + * @return this + * @throws JSONException If the value is out of sequence. */ + private JSONWriter append (String string) throws JSONException { + if (string == 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(string); + } 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 string 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 string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - stack[top - 1].putOnce(string, Boolean.TRUE); - if (this.comma) { - this.writer.write(','); - } - this.writer.write(JSONObject.quote(string)); - 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 mode Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. */ + private JSONWriter end (char mode, char c) throws JSONException { + if (this.mode != mode) { + throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); + } + this.pop(mode); + 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 string 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 string) throws JSONException { + if (string == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + stack[top - 1].putOnce(string, Boolean.TRUE); + if (this.comma) { + this.writer.write(','); + } + this.writer.write(JSONObject.quote(string)); + 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 object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. - * @return this - * @throws JSONException If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException { - return this.append(JSONObject.valueToString(object)); - } + /** Append an object value. + * @param object The object to append. It can be null, or a Boolean, Number, String, JSONObject, or JSONArray, or an object + * that implements JSONString. + * @return this + * @throws JSONException If the value is out of sequence. */ + public JSONWriter value (Object object) throws JSONException { + return this.append(JSONObject.valueToString(object)); + } } diff --git a/demos/very-angry-robots/very-angry-robots-android/src/com/badlydrawngames/veryangryrobots/android/VeryAngryRobotsActivity.java b/demos/very-angry-robots/very-angry-robots-android/src/com/badlydrawngames/veryangryrobots/android/VeryAngryRobotsActivity.java index bfaac804e7b..cb9d149c975 100644 --- a/demos/very-angry-robots/very-angry-robots-android/src/com/badlydrawngames/veryangryrobots/android/VeryAngryRobotsActivity.java +++ b/demos/very-angry-robots/very-angry-robots-android/src/com/badlydrawngames/veryangryrobots/android/VeryAngryRobotsActivity.java @@ -1,3 +1,4 @@ + package com.badlydrawngames.veryangryrobots.android; import android.os.Bundle; @@ -7,15 +8,15 @@ import com.badlydrawngames.veryangryrobots.VeryAngryRobotsGame; public class VeryAngryRobotsActivity extends AndroidApplication { - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); - config.useCompass = false; - config.useAccelerometer = false; - config.useGL20 = false; - VeryAngryRobotsGame game = new VeryAngryRobotsGame(); - initialize(game, config); - } + /** Called when the activity is first created. */ + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); + config.useCompass = false; + config.useAccelerometer = false; + config.useGL20 = false; + VeryAngryRobotsGame game = new VeryAngryRobotsGame(); + initialize(game, config); + } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CameraHelper.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CameraHelper.java index 7a6c10966c6..72e8ffcabae 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CameraHelper.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CameraHelper.java @@ -18,50 +18,46 @@ import com.badlogic.gdx.math.Vector2; public final class CameraHelper { - - private CameraHelper() {} - /** - * Creates an orthographic camera where the "play area" has the given viewport size. The viewport will either be - * stretched to fill the entire window, or it will be scaled to maintain the aspect ratio. + private CameraHelper () { + } + + /** Creates an orthographic camera where the "play area" has the given viewport size. The viewport will either be stretched to + * fill the entire window, or it will be scaled to maintain the aspect ratio. * * @param isStretched true if the "play area" is stretched to fill the entire window. * @param virtualWidth the width of the game screen in virtual pixels. * @param virtualHeight the height of the game screen in virtual pixels. - * @return the new camera. - */ - public static OrthographicCamera createCamera(boolean isStretched, float virtualWidth, float virtualHeight) { + * @return the new camera. */ + public static OrthographicCamera createCamera (boolean isStretched, float virtualWidth, float virtualHeight) { // Get the viewport size. Vector2 viewportSize = viewportSize(isStretched, virtualWidth, virtualHeight); float viewportWidth = viewportSize.x; float viewportHeight = viewportSize.y; - + // Create the camera, placing the origin at the bottom left of the viewport. OrthographicCamera camera = new OrthographicCamera(viewportWidth, viewportHeight); float xOrg = (viewportWidth - virtualWidth) / 2; - float yOrg = (viewportHeight - virtualHeight) / 2; + float yOrg = (viewportHeight - virtualHeight) / 2; camera.position.set(viewportWidth / 2 - xOrg, viewportHeight / 2 - yOrg, 0); camera.update(); return camera; } - /** - * Calculates the dimensions of the viewport required to support the given virtual coordinates. + /** Calculates the dimensions of the viewport required to support the given virtual coordinates. * * @param isStretched true if the viewport should be stretched to fill the entire window. * @param virtualWidth the width of the viewport in virtual units. * @param virtualHeight the height of the viewport in virtual units. - * @return the viewport's dimensions. - */ - public static Vector2 viewportSize(boolean isStretched, float virtualWidth, float virtualHeight) { + * @return the viewport's dimensions. */ + public static Vector2 viewportSize (boolean isStretched, float virtualWidth, float virtualHeight) { float viewportWidth; float viewportHeight; if (isStretched) { // Stretch the camera to fill the entire screen. viewportWidth = virtualWidth; viewportHeight = virtualHeight; - } - else { + } else { // Maintain the aspect ratio by letterboxing. float aspect = virtualWidth / virtualHeight; float physicalWidth = Gdx.graphics.getWidth(); @@ -70,8 +66,7 @@ public static Vector2 viewportSize(boolean isStretched, float virtualWidth, floa // Letterbox left and right. viewportHeight = virtualHeight; viewportWidth = viewportHeight * physicalWidth / physicalHeight; - } - else { + } else { // Letterbox above and below. viewportWidth = virtualWidth; viewportHeight = viewportWidth * physicalHeight / physicalWidth; @@ -79,29 +74,28 @@ public static Vector2 viewportSize(boolean isStretched, float virtualWidth, floa } return new Vector2(viewportWidth, viewportHeight); } - + public static enum ViewportMode { - PIXEL_PERFECT, - STRETCH_TO_ASPECT, - STRETCH_TO_SCREEN + PIXEL_PERFECT, STRETCH_TO_ASPECT, STRETCH_TO_SCREEN } - - public static OrthographicCamera createCamera2(ViewportMode viewportMode, float virtualWidth, float virtualHeight, float density) { + + public static OrthographicCamera createCamera2 (ViewportMode viewportMode, float virtualWidth, float virtualHeight, + float density) { // Get the viewport size. Vector2 viewportSize = sizeToDensity(viewportMode, virtualWidth, virtualHeight, density); float viewportWidth = viewportSize.x; float viewportHeight = viewportSize.y; - + // Create the camera, placing the origin at the bottom left of the viewport. OrthographicCamera camera = new OrthographicCamera(viewportWidth, viewportHeight); float xOrg = (viewportWidth - virtualWidth) / 2; - float yOrg = (viewportHeight - virtualHeight) / 2; + float yOrg = (viewportHeight - virtualHeight) / 2; camera.position.set(viewportWidth / 2 - xOrg, viewportHeight / 2 - yOrg, 0); camera.update(); return camera; } - - public static Vector2 sizeToDensity(ViewportMode viewportMode, float virtualWidth, float virtualHeight, float density) { + + public static Vector2 sizeToDensity (ViewportMode viewportMode, float virtualWidth, float virtualHeight, float density) { float viewportWidth = virtualWidth; float viewportHeight = virtualHeight; float physicalWidth = Gdx.graphics.getWidth(); @@ -111,15 +105,13 @@ public static Vector2 sizeToDensity(ViewportMode viewportMode, float virtualWidt float heightAtDensity = viewportHeight * density; viewportWidth *= (physicalWidth / widthAtDensity); viewportHeight *= (physicalHeight / heightAtDensity); - } - else if (viewportMode == ViewportMode.STRETCH_TO_ASPECT) { + } else if (viewportMode == ViewportMode.STRETCH_TO_ASPECT) { float aspect = virtualWidth / virtualHeight; if (physicalWidth / physicalHeight >= aspect) { // Letterbox left and right. viewportHeight = virtualHeight; viewportWidth = viewportHeight * physicalWidth / physicalHeight; - } - else { + } else { // Letterbox above and below. viewportWidth = virtualWidth; viewportHeight = viewportWidth * physicalHeight / physicalWidth; @@ -127,8 +119,8 @@ else if (viewportMode == ViewportMode.STRETCH_TO_ASPECT) { } return new Vector2(viewportWidth, viewportHeight); } - - public static float bestDensity(float virtualWidth, float virtualHeight, float[] densities) { + + public static float bestDensity (float virtualWidth, float virtualHeight, float[] densities) { // TODO: Spell out that densities is assumed to be in ascending order. float bestDensity = densities[0]; float physicalWidth = Gdx.graphics.getWidth(); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Colliders.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Colliders.java index 8f7c3c06964..ece2a061c7e 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Colliders.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Colliders.java @@ -18,45 +18,38 @@ import com.badlogic.gdx.utils.Pool; import com.badlydrawngames.veryangryrobots.mobiles.GameObject; -/** - * Functions that are useful for collision detection. - * @author Rod - * - */ +/** Functions that are useful for collision detection. + * @author Rod */ public final class Colliders { - + public static interface RemovalHandler { - void onRemove(T t); + void onRemove (T t); } - + public static interface ColliderHandler { - void onCollision(T t, U u); + void onCollision (T t, U u); } - + public static interface SceneryHandler { - void onCollision(T t, Rectangle r); + void onCollision (T t, Rectangle r); } - - private Colliders() {} - - /** - * Returns true if two rectangles intersect. + + private Colliders () { + } + + /** Returns true if two rectangles intersect. * @param a the first rectangle. * @param b the second rectangle. - * @return true if the rectangles intersect, otherwise false. - */ - public static boolean intersects(Rectangle a, Rectangle b) { - return (a.x + a.width > b.x) && (a.x < b.x + b.width) && - (a.y + a.height > b.y) && (a.y < b.y + b.height); + * @return true if the rectangles intersect, otherwise false. */ + public static boolean intersects (Rectangle a, Rectangle b) { + return (a.x + a.width > b.x) && (a.x < b.x + b.width) && (a.y + a.height > b.y) && (a.y < b.y + b.height); } - - /** - * Returns true if a rectangle intersects with any rectangles in an array. + + /** Returns true if a rectangle intersects with any rectangles in an array. * @param a the rectangle. * @param rects the array of rectangles. - * @return true if they intersect, otherwise false. - */ - public static boolean intersects(Rectangle a, Array rects) { + * @return true if they intersect, otherwise false. */ + public static boolean intersects (Rectangle a, Array rects) { for (int i = rects.size - 1; i >= 0; i--) { Rectangle b = rects.get(i); if (intersects(a, b)) { @@ -65,16 +58,18 @@ public static boolean intersects(Rectangle a, Array rects) { } return false; } - - public static void collide(T a, U b, ColliderHandler callback) { + + public static void collide (T a, U b, + ColliderHandler callback) { if (a != b) { if (a.intersects(b)) { callback.onCollision(a, b); } } } - - public static void collide(T go, Array gos, ColliderHandler callback) { + + public static void collide (T go, Array gos, + ColliderHandler callback) { for (int i = gos.size - 1; i >= 0; i--) { U other = gos.get(i); if (go.intersects(other)) { @@ -83,7 +78,7 @@ public static void collide(Array a, ColliderHandler callback) { + public static void collide (Array a, ColliderHandler callback) { for (int i = a.size - 1; i >= 0; i--) { T go = a.get(i); for (int j = i - 1; j >= 0; j--) { @@ -96,26 +91,27 @@ public static void collide(Array a, Colli } @SuppressWarnings("unchecked") - public static void collide(Array a, Array b, ColliderHandler callback) { + public static void collide (Array a, Array b, + ColliderHandler callback) { if (a != b) { for (int i = a.size - 1; i >= 0; i--) { T go = a.get(i); collide(go, b, callback); } - } - else { - collide(a, (ColliderHandler) callback); + } else { + collide(a, (ColliderHandler)callback); } } - public static void collide(Array gos, Array rects, SceneryHandler callback) { + public static void collide (Array gos, Array rects, + SceneryHandler callback) { for (int i = gos.size - 1; i >= 0; i--) { T go = gos.get(i); collide(go, rects, callback); } } - - public static void collide(T go, Array rects, SceneryHandler callback) { + + public static void collide (T go, Array rects, SceneryHandler callback) { for (int i = 0; i < rects.size && !go.inCollision; i++) { Rectangle r = rects.get(i); if (go.intersects(r)) { @@ -123,19 +119,18 @@ public static void collide(T go, Array the base class of the object. - * @param a more specific class of the object. + * @param a more specific class of the object. * @param pool the pool to which the object belongs. * @param gos the array of game objects to check. - * @param handler the collision handler callback. - */ - public static void removeMarkedCollisions(Pool pool, Array gos, RemovalHandler handler) { + * @param handler the collision handler callback. */ + public static void removeMarkedCollisions (Pool pool, Array gos, + RemovalHandler handler) { // The "U extends T" allows for shotHandler to cope with both PlayerShot and RobotShot, because they both // extend BaseShot. for (int i = gos.size - 1; i >= 0; i--) { @@ -148,14 +143,12 @@ public static void removeMarkedCollisions(Po } } - /** - * Removes game objects that are outside of the given rectangular bounds. + /** Removes game objects that are outside of the given rectangular bounds. * @param the object's class. * @param pool the pool to which the object belongs. * @param gos the array of game objects to check. - * @param bounds the rectangular bounds. - */ - public static void removeOutOfBounds(Pool pool, Array gos, Rectangle bounds) { + * @param bounds the rectangular bounds. */ + public static void removeOutOfBounds (Pool pool, Array gos, Rectangle bounds) { float minX = bounds.x; float maxX = minX + bounds.width; float minY = bounds.y; diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CollisionGeometry.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CollisionGeometry.java index c337e3d3ebd..15483149fbb 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CollisionGeometry.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/CollisionGeometry.java @@ -13,32 +13,28 @@ package com.badlydrawngames.general; -import static com.badlydrawngames.general.Rectangles.setRectangle; - import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Array; +import static com.badlydrawngames.general.Rectangles.*; + public class CollisionGeometry { private final Array runs; private final Rectangle r; - /** - * Creates this collision geometry. - * @param runs the model-space rectangles that make up this object's collision geometry. - */ - public CollisionGeometry(Array runs) { + /** Creates this collision geometry. + * @param runs the model-space rectangles that make up this object's collision geometry. */ + public CollisionGeometry (Array runs) { this.runs = runs; r = new Rectangle(); } - /** - * Tests if this collision geometry would collide with a rectangle if it was at the given coordinates. + /** Tests if this collision geometry would collide with a rectangle if it was at the given coordinates. * @param other the rectangle to test against. * @param x the x coordinate of this collision geometry. * @param y the y coordinate of this collision geometry. - * @return true if in collision otherwise false. - */ - public boolean intersects(Rectangle other, float x, float y) { + * @return true if in collision otherwise false. */ + public boolean intersects (Rectangle other, float x, float y) { boolean result = false; for (int i = 0; i < runs.size; i++) { Rectangle run = runs.get(i); @@ -51,16 +47,14 @@ public boolean intersects(Rectangle other, float x, float y) { return result; } - /** - * Tests if this collision geometry is in collision with another. + /** Tests if this collision geometry is in collision with another. * @param x this collision geometry's x coordinate. * @param y this collision geometry's y coordinate. * @param other the other collision geometry. * @param otherX the other collision geometry's x coordinate. * @param otherY the other collision geometry's y coordinate. - * @return true if in collision otherwise false. - */ - public boolean intersects(float x, float y, CollisionGeometry other, float otherX, float otherY) { + * @return true if in collision otherwise false. */ + public boolean intersects (float x, float y, CollisionGeometry other, float otherX, float otherY) { boolean result = false; for (int i = 0; i < runs.size; i++) { Rectangle run = runs.get(i); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Config.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Config.java index 14df248eabb..f575059a90c 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Config.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Config.java @@ -20,54 +20,50 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; -/** - * Provides a simple way to tweak the game configuration via attributes. Ideally this would be backed with a +/** Provides a simple way to tweak the game configuration via attributes. Ideally this would be backed with a * ConfigProvider or similar. - * @author Rod - * - */ + * @author Rod */ public class Config { - + private static final String PROPERTIES_FILE = "data/veryangryrobots.properties"; private static Properties properties; - - private Config() {} - - private static Properties instance() { + + private Config () { + } + + private static Properties instance () { if (null == properties) { properties = new Properties(); - FileHandle fh = Gdx.files.internal(PROPERTIES_FILE); + FileHandle fh = Gdx.files.internal(PROPERTIES_FILE); InputStream inStream = fh.read(); try { properties.load(inStream); inStream.close(); - } - catch (IOException e) { + } catch (IOException e) { if (inStream != null) { try { - inStream.close(); - } - catch (IOException ex) { + inStream.close(); + } catch (IOException ex) { } } } } return properties; } - - public static int asInt(String name, int fallback) { + + public static int asInt (String name, int fallback) { String v = instance().getProperty(name); if (v == null) return fallback; return Integer.parseInt(v); } - public static float asFloat(String name, float fallback) { + public static float asFloat (String name, float fallback) { String v = instance().getProperty(name); if (v == null) return fallback; return Float.parseFloat(v); } - - public static String asString(String name, String fallback) { + + public static String asString (String name, String fallback) { String v = instance().getProperty(name); if (v == null) return fallback; return v; diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/GameScreen.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/GameScreen.java index a882827d86c..f3e6c1581ca 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/GameScreen.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/GameScreen.java @@ -17,36 +17,36 @@ public class GameScreen implements Screen { protected T game; - - public GameScreen(T game) { + + public GameScreen (T game) { this.game = game; } @Override - public void dispose() { + public void dispose () { } @Override - public void hide() { + public void hide () { } @Override - public void pause() { + public void pause () { } @Override - public void render(float delta) { + public void render (float delta) { } @Override - public void resize(int width, int height) { + public void resize (int width, int height) { } @Override - public void resume() { + public void resume () { } @Override - public void show() { + public void show () { } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Grid.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Grid.java index b5d06e8fffc..bfa7820b754 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Grid.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Grid.java @@ -13,12 +13,11 @@ package com.badlydrawngames.general; -import static com.badlydrawngames.general.MathUtils.max; -import static com.badlydrawngames.general.MathUtils.min; - import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Array; +import static com.badlydrawngames.general.MathUtils.*; + public class Grid { private final int cols; @@ -28,7 +27,7 @@ public class Grid { private final Array> grid; private Array result; - public Grid(int cols, int rows, float width, float height) { + public Grid (int cols, int rows, float width, float height) { this.cols = cols; this.rows = rows; this.cellWidth = width / cols; @@ -39,14 +38,14 @@ public Grid(int cols, int rows, float width, float height) { } this.result = new Array(); } - - public void clear() { + + public void clear () { for (Array v : grid) { v.clear(); } } - - public void add(Rectangle r) { + + public void add (Rectangle r) { int minX = max(0, cellX(r.x)); int maxX = min(cols - 1, cellX(r.x + r.width)); int minY = max(0, cellY(r.y)); @@ -59,8 +58,8 @@ public void add(Rectangle r) { } } } - - public Array get(Rectangle r) { + + public Array get (Rectangle r) { result.clear(); int minX = max(0, cellX(r.x)); int maxX = min(cols - 1, cellX(r.x + r.width)); @@ -74,16 +73,16 @@ public Array get(Rectangle r) { } return result; } - - private int cellX(float x) { - return (int) (x / cellWidth); + + private int cellX (float x) { + return (int)(x / cellWidth); } - - private int cellY(float y) { - return (int) (y / cellHeight); + + private int cellY (float y) { + return (int)(y / cellHeight); } - - private int getGridCell(int x, int y) { + + private int getGridCell (int x, int y) { return x + y * cols; } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/MathUtils.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/MathUtils.java index a9a93bd1910..44f9c62ca76 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/MathUtils.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/MathUtils.java @@ -14,11 +14,11 @@ package com.badlydrawngames.general; public class MathUtils { - public static float abs(float n) { + public static float abs (float n) { return (n >= 0.0f) ? n : -n; } - - public static float sgn(float n) { + + public static float sgn (float n) { if (n > 0.0f) return 1.0f; else if (n < 0.0f) @@ -27,19 +27,19 @@ else if (n < 0.0f) return 0.0f; } - public static float min(float a, float b) { + public static float min (float a, float b) { return (a < b) ? a : b; } - - public static float max(float a, float b) { + + public static float max (float a, float b) { return (a > b) ? a : b; } - - public static int min(int a, int b) { + + public static int min (int a, int b) { return (a < b) ? a : b; } - - public static int max(int a, int b) { + + public static int max (int a, int b) { return (a > b) ? a : b; } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Particle.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Particle.java index d5d8a785eb9..b031126984b 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Particle.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Particle.java @@ -13,21 +13,17 @@ package com.badlydrawngames.general; -import static com.badlogic.gdx.math.MathUtils.PI; -import static com.badlogic.gdx.math.MathUtils.cos; -import static com.badlogic.gdx.math.MathUtils.random; -import static com.badlogic.gdx.math.MathUtils.sin; -import static com.badlydrawngames.general.MathUtils.max; -import static com.badlydrawngames.general.MathUtils.min; - import com.badlogic.gdx.graphics.Color; +import static com.badlogic.gdx.math.MathUtils.*; +import static com.badlydrawngames.general.MathUtils.*; + public class Particle { - + private final float MIN_SPEED = 3.125f; private final float MAX_SPEED = 6.25f; private final float DECAY = 2.0f; - + public boolean active; public float x; public float y; @@ -41,13 +37,13 @@ public class Particle { float b; float a; - public Particle(float size) { + public Particle (float size) { this.color = new Color(); this.size = size; this.halfSize = size / 2; } - - public void spawn(Color c, float x, float y) { + + public void spawn (Color c, float x, float y) { this.active = true; this.x = x - halfSize; this.y = y - halfSize; @@ -56,13 +52,13 @@ public void spawn(Color c, float x, float y) { g = c.g; b = c.b; a = 3.0f; - float direction = random((float) -PI, PI); + float direction = random((float)-PI, PI); float speed = random(MIN_SPEED, MAX_SPEED); dx = cos(direction) * speed; dy = sin(direction) * speed; } - - public void update(float delta) { + + public void update (float delta) { x += dx * delta; y += dy * delta; dx *= (1.0 - DECAY * delta * 0.5f); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ParticleManager.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ParticleManager.java index 8291d7de4dc..ab9fab75aec 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ParticleManager.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ParticleManager.java @@ -17,12 +17,12 @@ import com.badlogic.gdx.utils.Array; public class ParticleManager { - + private final Array particles; private final int maxParticles; private int index; - public ParticleManager(int maxParticles, float size) { + public ParticleManager (int maxParticles, float size) { particles = new Array(maxParticles); this.maxParticles = maxParticles; for (int i = 0; i < maxParticles; i++) { @@ -31,17 +31,17 @@ public ParticleManager(int maxParticles, float size) { index = 0; } - public Array getParticles() { + public Array getParticles () { return particles; } - - public void clear() { + + public void clear () { for (Particle particle : particles) { particle.active = false; } } - public void add(float x, float y, int n, Color c) { + public void add (float x, float y, int n, Color c) { for (int i = 0; i < n; i++) { particles.get(index).spawn(c, x, y); if (++index == maxParticles) { @@ -49,8 +49,8 @@ public void add(float x, float y, int n, Color c) { } } } - - public void update(float delta) { + + public void update (float delta) { for (Particle particle : particles) { if (particle.active) { particle.update(delta); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Pools.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Pools.java index 1858621098e..3a8ab8b97de 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Pools.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Pools.java @@ -16,42 +16,35 @@ import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pool; -/** - * Pool helper functions. - * @author Rod - * - */ +/** Pool helper functions. + * @author Rod */ public class Pools { - private Pools() {}; - - /** - * Frees the items in an array to a pool. + private Pools () { + }; + + /** Frees the items in an array to a pool. * @param the type of item allocated in the array. * @param array the array of items to free. - * @param pool the pool that the items are to be released to. - */ - public static void freeArrayToPool(Array array, Pool pool) { + * @param pool the pool that the items are to be released to. */ + public static void freeArrayToPool (Array array, Pool pool) { pool.free(array); array.clear(); } - - /** - * Creates an array from a pool, freeing its items if it already exists. + + /** Creates an array from a pool, freeing its items if it already exists. * @param the type of item allocated in the array. * @param array the array of items to (re)create. * @param pool the pool that the items are to be allocated from / released to. * @param size the array's capacity. - * @return - */ + * @return */ @SuppressWarnings("unchecked") - public static Array makeArrayFromPool(Array array, Pool pool, int size) { + public static Array makeArrayFromPool (Array array, Pool pool, int size) { if (array == null) { // Do this so that array.items can be used. T t = pool.obtain(); - array = new Array(false, size, (Class) t.getClass()); + array = new Array(false, size, (Class)t.getClass()); pool.free(t); - } - else { + } else { freeArrayToPool(array, pool); } return array; diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Rectangles.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Rectangles.java index 60e0a0deed9..5a5d277db0f 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Rectangles.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/Rectangles.java @@ -13,23 +13,23 @@ package com.badlydrawngames.general; -import static com.badlydrawngames.general.MathUtils.max; -import static com.badlydrawngames.general.MathUtils.min; - import com.badlogic.gdx.math.Rectangle; +import static com.badlydrawngames.general.MathUtils.*; + public class Rectangles { - - private Rectangles() {} - - public static void setRectangle(Rectangle r, float x, float y, float w, float h) { + + private Rectangles () { + } + + public static void setRectangle (Rectangle r, float x, float y, float w, float h) { r.x = x; r.y = y; r.width = w; r.height = h; } - - public static Rectangle union(Rectangle a, Rectangle b, Rectangle result) { + + public static Rectangle union (Rectangle a, Rectangle b, Rectangle result) { result.x = min(a.x, b.x); result.y = min(a.y, b.y); result.width = max(a.x + a.width, b.x + b.width) - result.x; diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ScoreString.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ScoreString.java index d180152e563..cf9864e5c4d 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ScoreString.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/ScoreString.java @@ -13,26 +13,23 @@ package com.badlydrawngames.general; -/** - * A ScoreString exists to prevent calls to {@link String#format(String, Object...)} as this seems to be - * rather profligate at allocating memory, which in turns leads to garbage collection. Given that we can't manage that - * directly we do our own thing. +/** A ScoreString exists to prevent calls to {@link String#format(String, Object...)} as this seems to be rather + * profligate at allocating memory, which in turns leads to garbage collection. Given that we can't manage that directly we do our + * own thing. * - * @author Rod - * - */ + * @author Rod */ public class ScoreString implements CharSequence { public static final int DEFAULT_CHARS = 6; - + private final char[] score; private final int start; - - public ScoreString() { + + public ScoreString () { this(DEFAULT_CHARS); } - - public ScoreString(int numChars) { + + public ScoreString (int numChars) { score = new char[numChars]; int n = 1; for (int i = 0; i < numChars - 1; i++) { @@ -40,32 +37,30 @@ public ScoreString(int numChars) { } start = n; } - + @Override - public char charAt(int index) { + public char charAt (int index) { return score[index]; } @Override - public int length() { + public int length () { return score.length; } @Override - public CharSequence subSequence(int start, int end) { + public CharSequence subSequence (int start, int end) { // Don't care. Call at your own risk. - return null; + return null; } - /** - * Sets this ScoreString to hold the given integer value. + /** Sets this ScoreString to hold the given integer value. * - * @param v the value that the ScoreString will hold. - */ - public void setScore(int v) { + * @param v the value that the ScoreString will hold. */ + public void setScore (int v) { for (int n = start, i = 0; i < score.length; n /= 10, i++) { int j = (v / n) % 10; - score[i] = (char) ('0' + j); + score[i] = (char)('0' + j); } } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/SimpleButton.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/SimpleButton.java index 61440822bb9..2b916fa7d86 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/SimpleButton.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/general/SimpleButton.java @@ -15,9 +15,9 @@ import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; -import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; +import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlydrawngames.veryangryrobots.Assets; public class SimpleButton { @@ -33,8 +33,8 @@ public class SimpleButton { private BitmapFont font; private float textWidth; private float textHeight; - - public SimpleButton(String text, BitmapFont font) { + + public SimpleButton (String text, BitmapFont font) { this.text = text; this.wasPressed = false; this.activated = false; @@ -47,54 +47,50 @@ public SimpleButton(String text, BitmapFont font) { h = bounds.height * 2; alignment = HAlignment.CENTER; } - - public void setWidth(float width) { + + public void setWidth (float width) { w = width; } - - public void setHeight(float height) { + + public void setHeight (float height) { h = height; } - - public void setAlignment(HAlignment alignment) { + + public void setAlignment (HAlignment alignment) { this.alignment = alignment; } - - public void update(float delta, boolean justTouched, boolean isTouched, boolean justReleased, float x, float y) { + + public void update (float delta, boolean justTouched, boolean isTouched, boolean justReleased, float x, float y) { wasPressed = false; if (justTouched && inBounds(x, y)) { activated = true; down = true; - } - else if (isTouched) { + } else if (isTouched) { down = activated && inBounds(x, y); - } - else if (justReleased) { + } else if (justReleased) { wasPressed = activated && inBounds(x, y); activated = false; down = false; - } - else { + } else { activated = false; } } - - private boolean inBounds(float x, float y) { + + private boolean inBounds (float x, float y) { return x >= this.x && x < this.x + this.w && y >= this.y && y < this.y + this.h; } - - public void draw(SpriteBatch spriteBatch) { + + public void draw (SpriteBatch spriteBatch) { Color oldColor = font.getColor(); if (down) { spriteBatch.setColor(Color.RED); - } - else { + } else { spriteBatch.setColor(Color.BLUE); } spriteBatch.draw(Assets.pureWhiteTextureRegion, x, y, w, h); spriteBatch.setColor(Color.WHITE); if (down) { - font.setColor(oldColor.r/2, oldColor.g/2, oldColor.b/2, oldColor.a); + font.setColor(oldColor.r / 2, oldColor.g / 2, oldColor.b / 2, oldColor.a); } float textX = x; float textY = y + h; @@ -102,32 +98,32 @@ public void draw(SpriteBatch spriteBatch) { font.drawWrapped(spriteBatch, text, textX, textY, w, alignment); font.setColor(oldColor); } - - public boolean wasPressed() { + + public boolean wasPressed () { return this.wasPressed; } - - public void rightOn(float right) { + + public void rightOn (float right) { x = right - w; } - - public void leftOn(float left) { + + public void leftOn (float left) { x = left; } - - public void centerHorizontallyOn(float centerX) { - x = centerX - w/2; + + public void centerHorizontallyOn (float centerX) { + x = centerX - w / 2; } - - public void bottomOn(float bottom) { + + public void bottomOn (float bottom) { y = bottom; } - - public void topOn(float top) { + + public void topOn (float top) { y = top - h; } - - public void centerVerticallyOn(float centerY) { - y = centerY - h/2; + + public void centerVerticallyOn (float centerY) { + y = centerY - h / 2; } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsListener.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsListener.java index 698211ba1ef..37012d19aac 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsListener.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsListener.java @@ -16,5 +16,5 @@ import com.badlydrawngames.veryangryrobots.StatusManager.Achievements; public interface AchievementsListener { - void onAttained(Achievements achievement); + void onAttained (Achievements achievement); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsNotifier.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsNotifier.java index f4506f43999..183c8d44b74 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsNotifier.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/AchievementsNotifier.java @@ -19,17 +19,17 @@ public class AchievementsNotifier implements AchievementsListener { private final Array listeners; - - public AchievementsNotifier() { + + public AchievementsNotifier () { this.listeners = new Array(); } - public void addListener(AchievementsListener listener) { + public void addListener (AchievementsListener listener) { listeners.add(listener); } - + @Override - public void onAttained(Achievements achievement) { + public void onAttained (Achievements achievement) { for (AchievementsListener listener : listeners) { listener.onAttained(achievement); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Assets.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Assets.java index eed411e5f66..4ee79b0e6ed 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Assets.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Assets.java @@ -13,8 +13,6 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlydrawngames.general.Rectangles.setRectangle; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.files.FileHandle; @@ -29,29 +27,31 @@ import com.badlydrawngames.general.CollisionGeometry; import com.badlydrawngames.general.Config; +import static com.badlydrawngames.general.Rectangles.*; + public class Assets { private static final String FLYUP_FONT = Config.asString("Global.flyupFont", "ocr_a_small.fnt"); private static final String SCORE_FONT = Config.asString("Global.scoreFont", "wellbutrin.fnt"); private static final String TEXT_FONT = Config.asString("Global.textFont", "ocr_a.fnt"); - + private static final float PLAYER_BORDER_WIDTH = Config.asFloat("Player.borderWidthPercent", 25.0f); private static final float PLAYER_BORDER_HEIGHT = Config.asFloat("Player.borderHeightPercent", 6.7f); private static final float PLAYER_FRAME_DURATION = Config.asFloat("Player.frameDuration", 0.2f); - private static final float ROBOT_FRAME_DURATION = Config.asFloat("Robot.frameDuration", 0.1f); + private static final float ROBOT_FRAME_DURATION = Config.asFloat("Robot.frameDuration", 0.1f); private static final float CAPTAIN_BORDER_WIDTH = Config.asFloat("Captain.borderWidthPercent", 16.7f); private static final float CAPTAIN_BORDER_HEIGHT = Config.asFloat("Captain.borderHeightPercent", 16.7f); private static final float CAPTAIN_FRAME_DURATION = Config.asFloat("Captain.frameDuration", 0.1f); - + private static final float PARTICLE_SIZE = Config.asFloat("particle.size", 0.1875f); - + private static TextureAtlas atlas; public static final float VIRTUAL_WIDTH = 30.0f; public static final float VIRTUAL_HEIGHT = 20.0f; - + public static TextureRegion pureWhiteTextureRegion; public static TextureRegion playerWalkingRight1; public static TextureRegion playerWalkingRight2; @@ -74,20 +74,20 @@ public class Assets { public static TextureRegion nemesis1; public static TextureRegion nemesis2; public static TextureRegion pauseButton; - + public static Animation playerWalkingRightAnimation; public static Animation playerWalkingLeftAnimation; public static Animation robotWalkingLeftAnimation; public static Animation robotWalkingRightAnimation; public static Animation robotScanningAnimation; - + public static Animation nemesisAnimation; public static BitmapFont scoreFont; public static BitmapFont textFont; public static BitmapFont flyupFont; - + public static Sound[] chickenTaunts; public static Sound[] standardTaunts; public static Sound extraLifeSound; @@ -117,15 +117,15 @@ public class Assets { public static float robotShotHeight; public static float particleWidth; public static float particleHeight; - + public static CollisionGeometry playerGeometry; public static CollisionGeometry captainGeometry; - + public static float pixelDensity; - - public static void load() { + + public static void load () { pixelDensity = calculatePixelDensity(); - String textureDir = "data/textures/" + (int) pixelDensity; + String textureDir = "data/textures/" + (int)pixelDensity; String textureFile = textureDir + "/pack"; atlas = new TextureAtlas(Gdx.files.internal(textureFile), Gdx.files.internal(textureDir)); loadTextures(); @@ -134,8 +134,8 @@ public static void load() { loadSounds(); initialiseGeometries(); } - - private static void loadTextures() { + + private static void loadTextures () { pureWhiteTextureRegion = atlas.findRegion("8x8"); playerWalkingRight1 = atlas.findRegion("HeroRight1"); playerWalkingRight2 = atlas.findRegion("HeroRight2"); @@ -160,7 +160,7 @@ private static void loadTextures() { pauseButton = atlas.findRegion("pause"); } - private static float calculatePixelDensity() { + private static float calculatePixelDensity () { FileHandle textureDir = Gdx.files.internal("data/textures"); FileHandle[] availableDensities = textureDir.list(); FloatArray densities = new FloatArray(availableDensities.length); @@ -171,51 +171,34 @@ private static float calculatePixelDensity() { densities.sort(); return CameraHelper.bestDensity(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, densities.items); } - - private static void createAnimations() { + + private static void createAnimations () { playerWalkingRightAnimation = new Animation(PLAYER_FRAME_DURATION, Assets.playerWalkingRight1, Assets.playerWalkingRight2); playerWalkingLeftAnimation = new Animation(PLAYER_FRAME_DURATION, Assets.playerWalkingLeft1, Assets.playerWalkingLeft2); - - robotWalkingLeftAnimation = new Animation(ROBOT_FRAME_DURATION, - robotLeft1, - robotLeft2, - robotLeft3, - robotLeft4, - robotLeft3, - robotLeft2); - robotWalkingRightAnimation = new Animation(ROBOT_FRAME_DURATION, - robotRight1, - robotRight2, - robotRight3, - robotRight4, - robotRight3, - robotRight2); - robotScanningAnimation = new Animation(ROBOT_FRAME_DURATION, - robotScan1, - robotScan2, - robotScan3, - robotScan4, - robotScan3, - robotScan2); - - nemesisAnimation = new Animation(CAPTAIN_FRAME_DURATION, - nemesis1, - nemesis2); + + robotWalkingLeftAnimation = new Animation(ROBOT_FRAME_DURATION, robotLeft1, robotLeft2, robotLeft3, robotLeft4, robotLeft3, + robotLeft2); + robotWalkingRightAnimation = new Animation(ROBOT_FRAME_DURATION, robotRight1, robotRight2, robotRight3, robotRight4, + robotRight3, robotRight2); + robotScanningAnimation = new Animation(ROBOT_FRAME_DURATION, robotScan1, robotScan2, robotScan3, robotScan4, robotScan3, + robotScan2); + + nemesisAnimation = new Animation(CAPTAIN_FRAME_DURATION, nemesis1, nemesis2); } - - private static void loadFonts() { - String fontDir = "data/fonts/" + (int) pixelDensity + "/"; + + private static void loadFonts () { + String fontDir = "data/fonts/" + (int)pixelDensity + "/"; scoreFont = new BitmapFont(Gdx.files.internal(fontDir + SCORE_FONT), false); textFont = new BitmapFont(Gdx.files.internal(fontDir + TEXT_FONT), false); flyupFont = new BitmapFont(Gdx.files.internal(fontDir + FLYUP_FONT), false); - + scoreFont.setScale(1.0f / pixelDensity); textFont.setScale(1.0f / pixelDensity); flyupFont.setScale(1.0f / pixelDensity); } - private static void loadSounds() { + private static void loadSounds () { standardTaunts = loadSounds("standard_taunts"); chickenTaunts = loadSounds("chicken_taunts"); achievementSound = loadSound("achievement.ogg"); @@ -232,8 +215,8 @@ private static void loadSounds() { killLastRobotSound = loadSound("hit03.ogg"); extraLifeSound = loadSound("pickup.ogg"); } - - private static Sound[] loadSounds(String dir) { + + private static Sound[] loadSounds (String dir) { FileHandle dh = Gdx.files.internal("data/sounds/" + dir); FileHandle[] fhs = dh.list(); Sound[] sounds = new Sound[fhs.length]; @@ -242,16 +225,16 @@ private static Sound[] loadSounds(String dir) { } return sounds; } - - private static Sound loadSound(String filename) { + + private static Sound loadSound (String filename) { return Gdx.audio.newSound(Gdx.files.internal("data/sounds/" + filename)); } - - private static void initialiseGeometries() { + + private static void initialiseGeometries () { playerWidth = toWidth(playerWalkingRight1); playerHeight = toHeight(playerWalkingRight1); - robotWidth = toWidth(robotRight1); + robotWidth = toWidth(robotRight1); robotHeight = toHeight(robotRight1); captainWidth = toWidth(nemesis1); captainHeight = toHeight(nemesis1); @@ -261,11 +244,11 @@ private static void initialiseGeometries() { robotShotHeight = toHeight(robotShot); particleWidth = PARTICLE_SIZE; particleHeight = PARTICLE_SIZE; - + // TODO: The below is a complete hack just to provide the player and captain with some collision geometry // so that he doesn't die when he's clearly not in contact with a wall, bullet or enemy. Ideally it would // be generated from the bitmap, or loaded. - + // Configure player collision geometry. Array playerRectangles = new Array(); Rectangle r = new Rectangle(); @@ -276,7 +259,7 @@ private static void initialiseGeometries() { setRectangle(r, x, y, w, h); playerRectangles.add(r); playerGeometry = new CollisionGeometry(playerRectangles); - + // Configure "captain" collision geometry. Array captainRectangles = new Array(); r = new Rectangle(); @@ -289,15 +272,15 @@ private static void initialiseGeometries() { captainGeometry = new CollisionGeometry(captainRectangles); } - private static float toWidth(TextureRegion region) { + private static float toWidth (TextureRegion region) { return region.getRegionWidth() / pixelDensity; } - - private static float toHeight(TextureRegion region) { + + private static float toHeight (TextureRegion region) { return region.getRegionHeight() / pixelDensity; } - - public static void playSound(Sound sound) { + + public static void playSound (Sound sound) { sound.play(1); } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DesktopStarter.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DesktopStarter.java index 5e8f14b4736..4110e94b213 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DesktopStarter.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DesktopStarter.java @@ -19,8 +19,8 @@ public class DesktopStarter { private final static int WINDOW_WIDTH = 800; private final static int WINDOW_HEIGHT = 480; - - public static void main(String[] args) { + + public static void main (String[] args) { new JoglApplication(new VeryAngryRobotsGame(), "Very Angry Robots", WINDOW_WIDTH, WINDOW_HEIGHT, false); } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DifficultyManager.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DifficultyManager.java index c77a60df5e3..e8fe118c69a 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DifficultyManager.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/DifficultyManager.java @@ -16,8 +16,11 @@ import com.badlogic.gdx.graphics.Color; public interface DifficultyManager { - Color getRobotColor(); - int getNumberOfRobots(); - int getNumberOfRobotShots(); - float getRobotShotSpeed(); + Color getRobotColor (); + + int getNumberOfRobots (); + + int getNumberOfRobotShots (); + + float getRobotShotSpeed (); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Flyup.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Flyup.java index 3e97163c03d..f65e3e67d46 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Flyup.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/Flyup.java @@ -1,3 +1,4 @@ + package com.badlydrawngames.veryangryrobots; import com.badlydrawngames.general.Config; @@ -9,24 +10,24 @@ public class Flyup { private static final float X_OFFSET = (Assets.flyupFont.getBounds("888").width / 2) / Assets.pixelDensity; private static final float Y_OFFSET = (Assets.flyupFont.getBounds("888").height) / Assets.pixelDensity; private static final float SPEED = Config.asFloat("flyup.speed", 25.0f); - + public final ScoreString scoreString; public boolean active; public float x; public float y; private float stateTime; - public Flyup() { + public Flyup () { scoreString = new ScoreString(3); } - - public void update(float delta) { + + public void update (float delta) { stateTime += delta; active = stateTime < LIFE_TIME; y += SPEED * delta; } - public void spawn(float x, float y, int points) { + public void spawn (float x, float y, int points) { active = true; stateTime = 0.0f; scoreString.setScore(points); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/FlyupManager.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/FlyupManager.java index 100b23625d0..7873d9522be 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/FlyupManager.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/FlyupManager.java @@ -1,3 +1,4 @@ + package com.badlydrawngames.veryangryrobots; import com.badlogic.gdx.utils.Array; @@ -5,27 +6,27 @@ public class FlyupManager implements ScoringEventListener { private static final int MAX_FLYUPS = 16; - + final Array flyups; private int index; - - public FlyupManager() { + + public FlyupManager () { flyups = new Array(MAX_FLYUPS); for (int i = 0; i < MAX_FLYUPS; i++) { flyups.add(new Flyup()); } index = 0; } - + @Override - public void onScoringEvent(float x, float y, int points) { + public void onScoringEvent (float x, float y, int points) { flyups.get(index).spawn(x, y, points); if (++index == MAX_FLYUPS) { index = 0; } } - public void update(float delta) { + public void update (float delta) { for (Flyup flyup : flyups) { if (flyup.active) { flyup.update(delta); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/IShowScores.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/IShowScores.java index 2582ab4d9f3..04669b5193d 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/IShowScores.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/IShowScores.java @@ -1,5 +1,6 @@ + package com.badlydrawngames.veryangryrobots; public interface IShowScores { - void showScores(); + void showScores (); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ISubmitScores.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ISubmitScores.java index 9a70f35157c..b054e4eb029 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ISubmitScores.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ISubmitScores.java @@ -1,5 +1,6 @@ + package com.badlydrawngames.veryangryrobots; public interface ISubmitScores { - void submitScore(final int score); + void submitScore (final int score); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MainMenuScreen.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MainMenuScreen.java index c5f851eab48..ac2df75b7ba 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MainMenuScreen.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MainMenuScreen.java @@ -13,9 +13,6 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_HEIGHT; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_WIDTH; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Color; @@ -29,6 +26,8 @@ import com.badlydrawngames.general.GameScreen; import com.badlydrawngames.general.SimpleButton; +import static com.badlydrawngames.veryangryrobots.Assets.*; + public class MainMenuScreen extends GameScreen { final String TITLE = "VERY ANGRY ROBOTS"; @@ -39,8 +38,8 @@ public class MainMenuScreen extends GameScreen { private SimpleButton scoresButton; private Vector3 touchPoint; private boolean wasTouched; - - public MainMenuScreen(VeryAngryRobotsGame game) { + + public MainMenuScreen (VeryAngryRobotsGame game) { super(game); menuCam = CameraHelper.createCamera2(ViewportMode.PIXEL_PERFECT, VIRTUAL_WIDTH, VIRTUAL_HEIGHT, Assets.pixelDensity); spriteBatch = new SpriteBatch(); @@ -49,72 +48,70 @@ public MainMenuScreen(VeryAngryRobotsGame game) { createButtons(); } - private void createButtons() { + private void createButtons () { playButton = createPlayButton(); - playButton.setWidth(VIRTUAL_WIDTH/4); - playButton.setHeight(VIRTUAL_HEIGHT/4); + playButton.setWidth(VIRTUAL_WIDTH / 4); + playButton.setHeight(VIRTUAL_HEIGHT / 4); if (game.canShowScores()) { scoresButton = createShowScoresButton(); - scoresButton.setWidth(VIRTUAL_WIDTH/4); - scoresButton.setHeight(VIRTUAL_HEIGHT/4); + scoresButton.setWidth(VIRTUAL_WIDTH / 4); + scoresButton.setHeight(VIRTUAL_HEIGHT / 4); scoresButton.rightOn(VIRTUAL_WIDTH); scoresButton.bottomOn(1.0f); playButton.leftOn(0); playButton.bottomOn(1.0f); - } - else { + } else { playButton.bottomOn(1.0f); playButton.centerHorizontallyOn(VIRTUAL_WIDTH / 2); } } - - private SimpleButton createPlayButton() { - return new SimpleButton("Play", Assets.textFont); + + private SimpleButton createPlayButton () { + return new SimpleButton("Play", Assets.textFont); } - private SimpleButton createShowScoresButton() { + private SimpleButton createShowScoresButton () { return new SimpleButton("Scores", Assets.textFont); } @Override - public void render(float delta) { + public void render (float delta) { updateButtons(delta); - + if (playButton.wasPressed()) { playButtonSound(); startGame(); - } - else if (game.canShowScores() && scoresButton.wasPressed()) { + } else if (game.canShowScores() && scoresButton.wasPressed()) { playButtonSound(); showScores(); - } - else { + } else { Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); spriteBatch.begin(); Assets.scoreFont.setColor(Color.WHITE); float y = VIRTUAL_HEIGHT - Assets.scoreFont.getCapHeight() / 2.0f; Assets.scoreFont.drawWrapped(spriteBatch, TITLE, 0, y, VIRTUAL_WIDTH, HAlignment.CENTER); - Assets.textFont.drawWrapped(spriteBatch, JIBBER_JABBER, VIRTUAL_WIDTH / 8, 3 * VIRTUAL_HEIGHT / 4, 3 * VIRTUAL_WIDTH / 4, HAlignment.CENTER); + Assets.textFont.drawWrapped(spriteBatch, JIBBER_JABBER, VIRTUAL_WIDTH / 8, 3 * VIRTUAL_HEIGHT / 4, + 3 * VIRTUAL_WIDTH / 4, HAlignment.CENTER); drawButtons(); spriteBatch.end(); } } - private void playButtonSound() { + private void playButtonSound () { Sound buttonPressedSound = Assets.buttonSound; Assets.playSound(buttonPressedSound); } - - private void startGame() { + + private void startGame () { game.setScreen(game.playingScreen); } - - private void showScores() { + + private void showScores () { game.showScores(); } - private void updateButtons(float delta) { + private void updateButtons (float delta) { touchPoint = screenToViewport(Gdx.input.getX(), Gdx.input.getY()); boolean justTouched = Gdx.input.justTouched(); boolean isTouched = Gdx.input.isTouched(); @@ -125,15 +122,15 @@ private void updateButtons(float delta) { scoresButton.update(delta, justTouched, isTouched, justReleased, touchPoint.x, touchPoint.y); } } - - private void drawButtons() { + + private void drawButtons () { playButton.draw(spriteBatch); if (game.canShowScores()) { scoresButton.draw(spriteBatch); } } - private Vector3 screenToViewport(float x, float y) { + private Vector3 screenToViewport (float x, float y) { menuCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); return touchPoint; } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MazeGenerator.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MazeGenerator.java index 926997ab2c1..8ab5b33483e 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MazeGenerator.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/MazeGenerator.java @@ -13,25 +13,22 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlogic.gdx.math.MathUtils.random; - import com.badlogic.gdx.utils.IntArray; +import static com.badlogic.gdx.math.MathUtils.*; -/** - * This class makes a maze using the recursive division method described on Wikipedia. - * {@link http://en.wikipedia.org/wiki/Maze_generation_algorithm} - */ +/** This class makes a maze using the recursive division method described on Wikipedia. {@link http + * ://en.wikipedia.org/wiki/Maze_generation_algorithm} */ public final class MazeGenerator { - + private int width; private int height; private int doorPos; - + private IntArray walls; private IntArray doors; - public MazeGenerator(int width, int height) { + public MazeGenerator (int width, int height) { // Pre: width is odd // Pre: height is odd // Pre: width > 2 @@ -42,33 +39,33 @@ public MazeGenerator(int width, int height) { doors = new IntArray(); } - public MazeGenerator rebuild(int doorPos) { + public MazeGenerator rebuild (int doorPos) { createMaze(doorPos); this.doorPos = doorPos; return this; } - - public int getWidth() { + + public int getWidth () { return width; } - - public int getHeight() { + + public int getHeight () { return height; } - - public int getDoorPos() { + + public int getDoorPos () { return doorPos; } - - public IntArray getWalls() { + + public IntArray getWalls () { return walls; } - public IntArray getDoors() { + public IntArray getDoors () { return doors; } - - private void createMaze(int doorPos) { + + private void createMaze (int doorPos) { walls.clear(); doors.clear(); addOuterWalls(); @@ -76,36 +73,36 @@ private void createMaze(int doorPos) { subdivideChamber(0, 0, width, height); } - private void addOuterWalls() { - addHWall(0, width/2, 0); - addHWall(width/2+1, width, 0); - addHWall(0, width/2, height); - addHWall(width/2+1, width, height); - addVWall(0, 0, height/2); - addVWall(0, height/2+1, height); - addVWall(width, 0, height/2); - addVWall(width, height/2+1, height); + private void addOuterWalls () { + addHWall(0, width / 2, 0); + addHWall(width / 2 + 1, width, 0); + addHWall(0, width / 2, height); + addHWall(width / 2 + 1, width, height); + addVWall(0, 0, height / 2); + addVWall(0, height / 2 + 1, height); + addVWall(width, 0, height / 2); + addVWall(width, height / 2 + 1, height); } - private void subdivideChamber(int x1, int y1, int x2, int y2) { + private void subdivideChamber (int x1, int y1, int x2, int y2) { // Get the size of the chamber and bail if it is too small to divide. int w = x2 - x1; int h = y2 - y1; if (w < 2 || h < 2) return; - + // Pick a point in the middle of the chamber. int cx = random(x1 + 1, x2 - 1); int cy = random(y1 + 1, y2 - 1); - + // Choose the solid wall. int solid = random(0, 3); - + // Add the internal walls. addHWall(x1, cx, cy, solid == 0); addHWall(cx, x2, cy, solid == 1); addVWall(cx, y1, cy, solid == 2); addVWall(cx, cy, y2, solid == 3); - + // Create the subchambers. subdivideChamber(x1, y1, cx, cy); subdivideChamber(cx, y1, x2, cy); @@ -113,73 +110,71 @@ private void subdivideChamber(int x1, int y1, int x2, int y2) { subdivideChamber(cx, cy, x2, y2); } - private void addHWall(int x1, int x2, int y, boolean solid) { + private void addHWall (int x1, int x2, int y, boolean solid) { int length = x2 - x1; if (length < 2) return; if (!solid) { int x = random(x1, x2 - 1); addHWall(x1, x, y); addHWall(x + 1, x2, y); - } - else { + } else { addHWall(x1, x2, y); } } - private void addHWall(int x1, int x2, int y) { + private void addHWall (int x1, int x2, int y) { if (x2 <= x1) return; addWall(x1, y, x2, y); } - private void addVWall(int x, int y1, int y2, boolean solid) { + private void addVWall (int x, int y1, int y2, boolean solid) { int length = y2 - y1; if (length < 2) return; if (!solid) { int y = random(y1, y2 - 1); addVWall(x, y1, y); addVWall(x, y + 1, y2); - } - else { + } else { addVWall(x, y1, y2); } } - private void addVWall(int x, int y1, int y2) { + private void addVWall (int x, int y1, int y2) { if (y2 <= y1) return; addWall(x, y1, x, y2); } - private void addWall(int x1, int y1, int x2, int y2) { + private void addWall (int x1, int y1, int x2, int y2) { walls.add(x1); walls.add(y1); walls.add(x2); walls.add(y2); } - - private void addDoors(int doorPos) { + + private void addDoors (int doorPos) { if ((doorPos & DoorPositions.MIN_Y) == DoorPositions.MIN_Y) { - addHDoor(width/2, 0); + addHDoor(width / 2, 0); } if ((doorPos & DoorPositions.MAX_Y) == DoorPositions.MAX_Y) { - addHDoor(width/2, height); + addHDoor(width / 2, height); } if ((doorPos & DoorPositions.MIN_X) == DoorPositions.MIN_X) { - addVDoor(0, height/2); + addVDoor(0, height / 2); } if ((doorPos & DoorPositions.MAX_X) == DoorPositions.MAX_X) { - addVDoor(width, height/2); + addVDoor(width, height / 2); } } - private void addHDoor(int x, int y) { + private void addHDoor (int x, int y) { addDoor(x, y, x + 1, y); } - private void addVDoor(int x, int y) { + private void addVDoor (int x, int y) { addDoor(x, y, x, y + 1); } - - private void addDoor(int x1, int y1, int x2, int y2) { + + private void addDoor (int x1, int y1, int x2, int y2) { doors.add(x1); doors.add(y1); doors.add(x2); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ParticleAdapter.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ParticleAdapter.java index 0fdfcbd1df4..293249c4ae2 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ParticleAdapter.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ParticleAdapter.java @@ -22,33 +22,33 @@ class ParticleAdapter implements WorldListener { final int PARTICLES = 32; - + final private World world; final private ParticleManager particleManager; private Color robotColor; private Color shotExplosionColor; - - public ParticleAdapter(World world, ParticleManager particleManager) { + + public ParticleAdapter (World world, ParticleManager particleManager) { this.world = world; this.particleManager = particleManager; shotExplosionColor = new Color(1.0f, 0.5f, 0.0f, 1.0f); } - - public void setRobotColor(Color color) { + + public void setRobotColor (Color color) { this.robotColor = color; } - public void update(float delta) { + public void update (float delta) { particleManager.update(delta); } - + @Override - public void onEnteredRoom(float time, int robots) { + public void onEnteredRoom (float time, int robots) { particleManager.clear(); } @Override - public void onPlayerHit() { + public void onPlayerHit () { Player player = world.getPlayer(); float x = player.x + player.width / 2; float y = player.y + player.height / 2; @@ -56,45 +56,45 @@ public void onPlayerHit() { } @Override - public void onRobotDestroyed(Robot robot) { + public void onRobotDestroyed (Robot robot) { float x = robot.x + robot.width / 2; float y = robot.y + robot.height / 2; particleManager.add(x, y, PARTICLES, robotColor); } - + @Override - public void onShotDestroyed(BaseShot shot) { + public void onShotDestroyed (BaseShot shot) { float x = shot.x + shot.width / 2; float y = shot.y + shot.height / 2; particleManager.add(x, y, PARTICLES / 8, shotExplosionColor); } @Override - public void onCaptainActivated(float time) { + public void onCaptainActivated (float time) { } @Override - public void onExitedRoom(float time, int robots) { + public void onExitedRoom (float time, int robots) { } @Override - public void onPlayerFired() { + public void onPlayerFired () { } @Override - public void onPlayerSpawned() { + public void onPlayerSpawned () { } @Override - public void onRobotFired(Robot robot) { + public void onRobotFired (Robot robot) { } @Override - public void onRobotHit(Robot robot) { + public void onRobotHit (Robot robot) { } @Override - public void onWorldReset() { + public void onWorldReset () { } - + } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/RoomBuilder.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/RoomBuilder.java index 6556e38fdb7..6213c04efe4 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/RoomBuilder.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/RoomBuilder.java @@ -27,45 +27,45 @@ public class RoomBuilder { private static final int MAX_RECTANGLES = 256; private static final int MAX_DOORS = 4; private static final int MAX_WALLS = MAX_RECTANGLES - MAX_DOORS; - + private final MazeGenerator mazeGenerator; private final Pool rectanglePool; private Array doorRects; private Array wallRects; private final int hcells; private final int vcells; - - public RoomBuilder(int hcells, int vcells) { + + public RoomBuilder (int hcells, int vcells) { this.hcells = hcells; this.vcells = vcells; mazeGenerator = new MazeGenerator(hcells, vcells); rectanglePool = new Pool(MAX_RECTANGLES) { @Override - protected Rectangle newObject() { + protected Rectangle newObject () { return new Rectangle(); } }; } - public void build(int doorPosition) { + public void build (int doorPosition) { mazeGenerator.rebuild(doorPosition); createWallsAndDoors(); } - - public Array getWalls() { + + public Array getWalls () { return wallRects; } - - public Array getDoors() { + + public Array getDoors () { return doorRects; } - - private void createWallsAndDoors() { + + private void createWallsAndDoors () { createWalls(); createDoors(); } - private void createWalls() { + private void createWalls () { IntArray wallDefs = mazeGenerator.getWalls(); int n = wallDefs.size / 4; wallRects = Pools.makeArrayFromPool(wallRects, rectanglePool, MAX_WALLS); @@ -75,17 +75,17 @@ private void createWalls() { } } - private void createDoors() { + private void createDoors () { IntArray doorDefs = mazeGenerator.getDoors(); - int n = doorDefs.size/ 4; + int n = doorDefs.size / 4; doorRects = Pools.makeArrayFromPool(doorRects, rectanglePool, MAX_DOORS); for (int i = 0, j = 0; i < n; i++, j += 4) { - Rectangle doorRect = createDoor(doorDefs, j); + Rectangle doorRect = createDoor(doorDefs, j); doorRects.add(doorRect); } } - private Rectangle createWall(IntArray wallDefs, int i) { + private Rectangle createWall (IntArray wallDefs, int i) { int x1 = wallDefs.get(i); int y1 = wallDefs.get(i + 1); int x2 = wallDefs.get(i + 2); @@ -93,7 +93,7 @@ private Rectangle createWall(IntArray wallDefs, int i) { return (x1 == x2) ? createVWall(x1, y1, y2) : createHWall(x1, x2, y1); } - private Rectangle createHWall(int x1, int x2, int y1) { + private Rectangle createHWall (int x1, int x2, int y1) { float x = coordMinusHalfHeight(x1, hcells); float y = coordMinusHalfHeight(y1, vcells); float t = coordMinusHalfHeight(x2, hcells); @@ -101,8 +101,8 @@ private Rectangle createHWall(int x1, int x2, int y1) { float h = WALL_HEIGHT; return newRectangle(x, y, w, h); } - - private Rectangle createVWall(int x1, int y1, int y2) { + + private Rectangle createVWall (int x1, int y1, int y2) { float x = coordMinusHalfHeight(x1, hcells); float y = coordMinusHalfHeight(y1, vcells); float t = coordMinusHalfHeight(y2, vcells); @@ -110,62 +110,58 @@ private Rectangle createVWall(int x1, int y1, int y2) { float h = (t - y) + WALL_HEIGHT; return newRectangle(x, y, w, h); } - - private Rectangle createDoor(IntArray doorDefs, int i) { + + private Rectangle createDoor (IntArray doorDefs, int i) { int x1 = doorDefs.get(i); int y1 = doorDefs.get(i + 1); int x2 = doorDefs.get(i + 2); return (x1 == x2) ? createVDoor(x1, y1) : createHDoor(x1, y1); } - - private Rectangle createHDoor(int x1, int y1) { + + private Rectangle createHDoor (int x1, int y1) { float x = coordPlusHalfHeight(x1, hcells); float y = coordMinusHalfHeight(y1, vcells); float w = WALL_WIDTH - WALL_HEIGHT; float h = WALL_HEIGHT; return newRectangle(x, y, w, h); } - - private Rectangle createVDoor(int x1, int y1) { + + private Rectangle createVDoor (int x1, int y1) { float x = coordMinusHalfHeight(x1, hcells); float y = coordPlusHalfHeight(y1, vcells); float w = WALL_HEIGHT; float h = WALL_WIDTH - WALL_HEIGHT; return newRectangle(x, y, w, h); } - - private float coordPlusHalfHeight(int c, int limit) { + + private float coordPlusHalfHeight (int c, int limit) { float n = ADJUSTMENT; if (c == 0) { - return n + HALF_HEIGHT; - } - else if (c < limit) { + return n + HALF_HEIGHT; + } else if (c < limit) { return n + WALL_WIDTH - ADJUSTMENT + ((c - 1) * WALL_WIDTH) + HALF_HEIGHT; - } - else { + } else { return n + 2 * (WALL_WIDTH - ADJUSTMENT) + ((c - 2) * WALL_WIDTH) + HALF_HEIGHT; } } - - private float coordMinusHalfHeight(int c, int limit) { + + private float coordMinusHalfHeight (int c, int limit) { float n = ADJUSTMENT; if (c == 0) { - return n - HALF_HEIGHT; - } - else if (c < limit) { + return n - HALF_HEIGHT; + } else if (c < limit) { return n + WALL_WIDTH - ADJUSTMENT + ((c - 1) * WALL_WIDTH) - HALF_HEIGHT; - } - else { + } else { return n + 2 * (WALL_WIDTH - ADJUSTMENT) + ((c - 2) * WALL_WIDTH) - HALF_HEIGHT; } } - - private Rectangle newRectangle(float x, float y, float w, float h) { + + private Rectangle newRectangle (float x, float y, float w, float h) { Rectangle r = rectanglePool.obtain(); r.x = x; r.y = y; r.width = w; r.height = h; return r; - } + } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreBasedDifficultyManager.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreBasedDifficultyManager.java index 8bc0fe7f52b..a03fe76b00c 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreBasedDifficultyManager.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreBasedDifficultyManager.java @@ -21,11 +21,11 @@ public class ScoreBasedDifficultyManager implements DifficultyManager, ScoreList // Robot numbers. private static final int MAX_ROBOTS = Config.asInt("Global.maxRobots", 12); private static final int INITIAL_ROBOTS = Config.asInt("Global.initialRobots", 6); - + // Shot speeds. private static final float SLOW_SHOT_SPEED = Config.asFloat("RobotShot.slowSpeed", 75.0f); private static final float FAST_SHOT_SPEED = Config.asFloat("RobotShot.fastSpeed", 125.0f); - + // Level progression. private static final int ROBOT_INCREMENT = Config.asInt("Level.robotIncrement", 3); private static final int LEVEL_0_ROBOT_SHOTS = Config.asInt("Level.0.robotShots", 0); @@ -62,109 +62,98 @@ public class ScoreBasedDifficultyManager implements DifficultyManager, ScoreList private static final Color WHITE = Color.WHITE; private static final Color LIGHT_PURPLE = new Color(1.0f, 0.0f, 1.0f, 1.0f); private static final Color GREY = new Color(0.75f, 0.75f, 0.75f, 1.0f); - + private boolean dirty; private int score; private Color robotColor; private int numRobots; private int numRobotShots; private float robotShotSpeed; - + @Override - public Color getRobotColor() { + public Color getRobotColor () { updateIfDirty(); return robotColor; } @Override - public int getNumberOfRobots() { + public int getNumberOfRobots () { updateIfDirty(); return numRobots; } @Override - public int getNumberOfRobotShots() { + public int getNumberOfRobotShots () { updateIfDirty(); return numRobotShots; } - + @Override - public float getRobotShotSpeed() { + public float getRobotShotSpeed () { updateIfDirty(); return robotShotSpeed; } @Override - public void onScoreChanged(int score) { + public void onScoreChanged (int score) { dirty = true; this.score = score; } @Override - public void onLivesChanged(int lives) { + public void onLivesChanged (int lives) { } - - private void updateIfDirty() { + + private void updateIfDirty () { if (!dirty) return; dirty = false; - + Color lastRobotColor = robotColor; if (score < LEVEL_1_SCORE) { robotColor = DARK_YELLOW; numRobotShots = LEVEL_0_ROBOT_SHOTS; robotShotSpeed = SLOW_SHOT_SPEED; - } - else if (score < LEVEL_2_SCORE) { + } else if (score < LEVEL_2_SCORE) { robotColor = RED; numRobotShots = LEVEL_1_ROBOT_SHOTS; robotShotSpeed = SLOW_SHOT_SPEED; - } - else if (score < LEVEL_3_SCORE) { + } else if (score < LEVEL_3_SCORE) { robotColor = DARK_CYAN; numRobotShots = LEVEL_2_ROBOT_SHOTS; robotShotSpeed = SLOW_SHOT_SPEED; - } - else if (score < LEVEL_4_SCORE) { + } else if (score < LEVEL_4_SCORE) { robotColor = GREEN; numRobotShots = LEVEL_3_ROBOT_SHOTS; robotShotSpeed = SLOW_SHOT_SPEED; - } - else if (score < LEVEL_5_SCORE) { + } else if (score < LEVEL_5_SCORE) { robotColor = DARK_PURPLE; numRobotShots = LEVEL_4_ROBOT_SHOTS; robotShotSpeed = SLOW_SHOT_SPEED; - } - else if (score < LEVEL_6_SCORE) { + } else if (score < LEVEL_6_SCORE) { robotColor = LIGHT_YELLOW; numRobotShots = LEVEL_5_ROBOT_SHOTS; robotShotSpeed = SLOW_SHOT_SPEED; - } - else if (score < LEVEL_7_SCORE) { + } else if (score < LEVEL_7_SCORE) { robotColor = WHITE; numRobotShots = LEVEL_6_ROBOT_SHOTS; robotShotSpeed = FAST_SHOT_SPEED; - } - else if (score < LEVEL_8_SCORE) { + } else if (score < LEVEL_8_SCORE) { robotColor = DARK_CYAN; numRobotShots = LEVEL_7_ROBOT_SHOTS; robotShotSpeed = FAST_SHOT_SPEED; - } - else if (score < LEVEL_9_SCORE) { + } else if (score < LEVEL_9_SCORE) { robotColor = LIGHT_PURPLE; numRobotShots = LEVEL_8_ROBOT_SHOTS; robotShotSpeed = FAST_SHOT_SPEED; - } - else if (score < LEVEL_10_SCORE) { + } else if (score < LEVEL_10_SCORE) { robotColor = GREY; numRobotShots = LEVEL_9_ROBOT_SHOTS; robotShotSpeed = FAST_SHOT_SPEED; - } - else if (score < LEVEL_11_SCORE) { + } else if (score < LEVEL_11_SCORE) { robotColor = DARK_YELLOW; numRobotShots = LEVEL_10_ROBOT_SHOTS; robotShotSpeed = FAST_SHOT_SPEED; - } - else { + } else { robotColor = RED; numRobotShots = LEVEL_11_ROBOT_SHOTS; robotShotSpeed = FAST_SHOT_SPEED; @@ -174,8 +163,7 @@ else if (score < LEVEL_11_SCORE) { if (numRobots < MAX_ROBOTS) { numRobots += ROBOT_INCREMENT; } - } - else { + } else { numRobots = INITIAL_ROBOTS; } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreListener.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreListener.java index 2899bd5677d..b753ea0f896 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreListener.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreListener.java @@ -14,6 +14,7 @@ package com.badlydrawngames.veryangryrobots; public interface ScoreListener { - void onScoreChanged(int score); - void onLivesChanged(int lives); + void onScoreChanged (int score); + + void onLivesChanged (int lives); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreNotifier.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreNotifier.java index 85b52e055c0..21c02363593 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreNotifier.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoreNotifier.java @@ -18,24 +18,24 @@ public class ScoreNotifier implements ScoreListener { private Array listeners; - - public ScoreNotifier() { + + public ScoreNotifier () { listeners = new Array(); } - - public void addListener(ScoreListener listener) { + + public void addListener (ScoreListener listener) { listeners.add(listener); } - + @Override - public void onScoreChanged(int score) { + public void onScoreChanged (int score) { for (ScoreListener listener : listeners) { listener.onScoreChanged(score); } } @Override - public void onLivesChanged(int lives) { + public void onLivesChanged (int lives) { for (ScoreListener listener : listeners) { listener.onLivesChanged(lives); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoresScreen.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoresScreen.java index 2e59e156c06..e52773baef2 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoresScreen.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoresScreen.java @@ -13,9 +13,6 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_HEIGHT; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_WIDTH; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.graphics.Color; @@ -29,14 +26,16 @@ import com.badlydrawngames.general.GameScreen; import com.badlydrawngames.general.ScoreString; +import static com.badlydrawngames.veryangryrobots.Assets.*; + public class ScoresScreen extends GameScreen { - + private static final String LAST_SCORE = "Score:"; private static final String TOP_SCORE = "Best: "; private static final String VERY_ANGRY_ROBOTS = "VeryAngryRobots"; private static final String TOP_SCORE_PREF = "top score"; private static final String TAP_TO_CONTINUE = "Tap to continue"; - + private ScoreString scoreString; private ScoreString topScoreString; private OrthographicCamera scoreCam; @@ -46,7 +45,7 @@ public class ScoresScreen extends GameScreen { private final Preferences preferences; private float stateTime; - public ScoresScreen(VeryAngryRobotsGame game) { + public ScoresScreen (VeryAngryRobotsGame game) { super(game); scoreCam = CameraHelper.createCamera2(ViewportMode.PIXEL_PERFECT, VIRTUAL_WIDTH, VIRTUAL_HEIGHT, Assets.pixelDensity); spriteBatch = new SpriteBatch(); @@ -58,8 +57,8 @@ public ScoresScreen(VeryAngryRobotsGame game) { topScoreString.setScore(topScore); stateTime = 0.0f; } - - public void setScore(int score) { + + public void setScore (int score) { scoreString.setScore(score); if (score > topScore) { topScore = score; @@ -68,18 +67,16 @@ public void setScore(int score) { topScoreString.setScore(score); } } - + @Override - public void render(float delta) { + public void render (float delta) { stateTime += delta; if (Gdx.input.justTouched()) { touched = true; - } - else if (touched && !Gdx.input.isTouched()) { + } else if (touched && !Gdx.input.isTouched()) { touched = false; game.setScreen(game.mainMenuScreen); - } - else { + } else { Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); spriteBatch.begin(); @@ -93,7 +90,7 @@ else if (touched && !Gdx.input.isTouched()) { Assets.scoreFont.setColor(Color.WHITE); Assets.scoreFont.draw(spriteBatch, TOP_SCORE, x, y); Assets.scoreFont.draw(spriteBatch, topScoreString, x + w, y); - + b = Assets.scoreFont.getBounds(TOP_SCORE); w = b.width + Assets.scoreFont.getSpaceWidth(); b = Assets.scoreFont.getBounds(topScoreString); @@ -102,28 +99,28 @@ else if (touched && !Gdx.input.isTouched()) { y += 2 * b.height; Assets.scoreFont.draw(spriteBatch, LAST_SCORE, x, y); Assets.scoreFont.draw(spriteBatch, scoreString, x + w, y); - + if (stateTime % 1.0f < 0.5f) { Assets.textFont.setColor(Color.WHITE); - Assets.textFont.drawWrapped(spriteBatch, TAP_TO_CONTINUE, 0, VIRTUAL_HEIGHT/4, VIRTUAL_WIDTH, HAlignment.CENTER); + Assets.textFont.drawWrapped(spriteBatch, TAP_TO_CONTINUE, 0, VIRTUAL_HEIGHT / 4, VIRTUAL_WIDTH, HAlignment.CENTER); } spriteBatch.end(); } } - + @Override - public void show() { + public void show () { Gdx.input.setCatchBackKey(true); stateTime = 0.0f; } - + @Override - public void hide() { + public void hide () { Gdx.input.setCatchBackKey(false); } - + @Override - public void resume() { + public void resume () { Gdx.input.setCatchBackKey(true); } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventListener.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventListener.java index 7e1c8054eb8..f232c7447a9 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventListener.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventListener.java @@ -14,5 +14,5 @@ package com.badlydrawngames.veryangryrobots; public interface ScoringEventListener { - void onScoringEvent(float x, float y, int points); + void onScoringEvent (float x, float y, int points); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventNotifier.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventNotifier.java index 7dde62b9d49..a7bc2356e8b 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventNotifier.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/ScoringEventNotifier.java @@ -1,3 +1,4 @@ + package com.badlydrawngames.veryangryrobots; import com.badlogic.gdx.utils.Array; @@ -5,17 +6,17 @@ public class ScoringEventNotifier implements ScoringEventListener { private final Array listeners; - - public ScoringEventNotifier() { + + public ScoringEventNotifier () { listeners = new Array(); } - - public void addListener(ScoringEventListener listener) { + + public void addListener (ScoringEventListener listener) { listeners.add(listener); } - + @Override - public void onScoringEvent(float x, float y, int points) { + public void onScoringEvent (float x, float y, int points) { for (ScoringEventListener listener : listeners) { listener.onScoringEvent(x, y, points); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/SoundManager.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/SoundManager.java index 82307e918d0..2ed059bd9db 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/SoundManager.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/SoundManager.java @@ -13,17 +13,17 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlogic.gdx.math.MathUtils.random; - import com.badlogic.gdx.audio.Sound; import com.badlydrawngames.veryangryrobots.StatusManager.Achievements; import com.badlydrawngames.veryangryrobots.mobiles.BaseShot; import com.badlydrawngames.veryangryrobots.mobiles.Robot; +import static com.badlogic.gdx.math.MathUtils.*; + public class SoundManager implements WorldListener, AchievementsListener, ScoreListener { private static final float MIN_TAUNT_INTERVAL = 2.5f; private static final float MAX_TAUNT_INTERVAL = 15.0f; - + private float now; private float nextTauntTime; private float lastRobotFireTime; @@ -34,32 +34,32 @@ public class SoundManager implements WorldListener, AchievementsListener, ScoreL private int lives; @Override - public void onEnteredRoom(float time, int robots) { + public void onEnteredRoom (float time, int robots) { Assets.playSound(Assets.spawnPlayerSound); } - + @Override - public void onExitedRoom(float time, int robots) { - isChicken = robots > 0; + public void onExitedRoom (float time, int robots) { + isChicken = robots > 0; if (isChicken) { Assets.playSound(Assets.exitRoomAsChickenSpeech); } canTaunt = false; } - + @Override - public void onPlayerSpawned() { + public void onPlayerSpawned () { canTaunt = true; scheduleTaunt(); } - + @Override - public void onPlayerFired() { + public void onPlayerFired () { Assets.playSound(Assets.playerShotSound); } @Override - public void onRobotFired(Robot robot) { + public void onRobotFired (Robot robot) { if (lastRobotFireTime != now) { Assets.playSound(Assets.robotShotSound); lastRobotFireTime = now; @@ -67,7 +67,7 @@ public void onRobotFired(Robot robot) { } @Override - public void onPlayerHit() { + public void onPlayerHit () { if (lastPlayerHitTime != now) { canTaunt = false; Assets.playSound(Assets.killPlayerSound); @@ -76,41 +76,41 @@ public void onPlayerHit() { } @Override - public void onRobotDestroyed(Robot robot) { + public void onRobotDestroyed (Robot robot) { if (lastRobotHitTime != now) { Assets.playSound(Assets.killRobotSound); lastRobotHitTime = now; } } - + @Override - public void onCaptainActivated(float time) { + public void onCaptainActivated (float time) { Assets.playSound(Assets.captainEnterRoomSpeech); // We can't do much about any speech going on, but we can make sure nothing else talks over the top of this // one. scheduleTaunt(); } - + @Override - public void onRobotHit(Robot robot) { + public void onRobotHit (Robot robot) { } @Override - public void onShotDestroyed(BaseShot shot) { + public void onShotDestroyed (BaseShot shot) { } @Override - public void onWorldReset() { + public void onWorldReset () { isChicken = false; lives = 0; } @Override - public void onAttained(Achievements achievement) { + public void onAttained (Achievements achievement) { Assets.playSound(Assets.achievementSound); } - - public void update(float delta) { + + public void update (float delta) { now += delta; if (canTaunt && now >= nextTauntTime) { Sound[] sounds = isChicken ? Assets.chickenTaunts : Assets.standardTaunts; @@ -118,17 +118,17 @@ public void update(float delta) { scheduleTaunt(); } } - - private void scheduleTaunt() { + + private void scheduleTaunt () { nextTauntTime = now + random(MIN_TAUNT_INTERVAL, MAX_TAUNT_INTERVAL); } @Override - public void onScoreChanged(int score) { + public void onScoreChanged (int score) { } @Override - public void onLivesChanged(int lives) { + public void onLivesChanged (int lives) { if (lives - 1 == this.lives) { Assets.playSound(Assets.extraLifeSound); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusManager.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusManager.java index 862523d6879..b1bc14ed90c 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusManager.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusManager.java @@ -23,27 +23,30 @@ public class StatusManager implements WorldListener { public enum Achievements { - PERFECTIONIST("Perfectionist", "Clear " + CLEAN_ROOMS + " rooms in a row."), - PERFECT_SHOT("Perfect Shot", "Clear a room by shooting everything."), - PACIFICIST("Pacifist", "Clear a room without shooting anything."), - DAREDEVIL("Daredevil", "Survive for " + DAREDEVIL_SECONDS + " seconds after the captain enters the room."), - COWARD("Coward", "Run from " + CHICKEN_ROOMS + " rooms in a row."), - ADDICT("Addict", "Play " + ADDICT_GAMES + " games."), - LUCKY_JIM("Lucky Jim", "Survive for " + LUCKY_JIM_ROOMS + " rooms without being hit."), - ROBOCIDE("Robocide", "Destroyed " + ROBOCIDE_ROBOTS + " robots"); + PERFECTIONIST("Perfectionist", "Clear " + CLEAN_ROOMS + " rooms in a row."), PERFECT_SHOT("Perfect Shot", + "Clear a room by shooting everything."), PACIFICIST("Pacifist", "Clear a room without shooting anything."), DAREDEVIL( + "Daredevil", "Survive for " + DAREDEVIL_SECONDS + " seconds after the captain enters the room."), COWARD("Coward", + "Run from " + CHICKEN_ROOMS + " rooms in a row."), ADDICT("Addict", "Play " + ADDICT_GAMES + " games."), LUCKY_JIM( + "Lucky Jim", "Survive for " + LUCKY_JIM_ROOMS + " rooms without being hit."), ROBOCIDE("Robocide", "Destroyed " + + ROBOCIDE_ROBOTS + " robots"); private final String summary; private final String text; - - private Achievements(String summary, String text) { + + private Achievements (String summary, String text) { this.summary = summary; this.text = text; } - - public String summary() { return this.summary; } - public String text() { return this.text; } + + public String summary () { + return this.summary; + } + + public String text () { + return this.text; + } } - + // Achievements. private static final int CLEAN_ROOMS = Config.asInt("achievements.cleanRoomsForPerfectionist", 5); private static final int ROBOCIDE_ROBOTS = Config.asInt("achievements.robotsForRobocide", 50); @@ -51,7 +54,7 @@ private Achievements(String summary, String text) { private static final int CHICKEN_ROOMS = Config.asInt("achievements.roomsForChicken", 5); private static final int ADDICT_GAMES = Config.asInt("achievements.gamesForAddict", 5); private static final float DAREDEVIL_SECONDS = Config.asInt("achievements.daredevilSeconds", 10); - + // Lives and scoring. private static final int INITIAL_LIVES = Config.asInt("Player.lives", 3); private static final int ROBOT_SCORE = Config.asInt("Robot.score", 50); @@ -63,55 +66,55 @@ private Achievements(String summary, String text) { private final ScoringEventNotifier scoringEventNotifier; private final AchievementsNotifier achievementsNotifier; private final EnumSet achieved; - + /** The number of lives that the player has. */ private int lives; - + /** The player's score. */ private int score; - + /** The number of games that the player has played. */ private int numGames; - + /** The number of robots that have been shot in this room. */ private int robotsShot; - + /** The number of robots that have been destroyed in this room (including those that have been shot). */ private int robotsDestroyed; - + /** The number of times the player has been hit in this room. */ private int playerHits; /** The number of rooms entered in this game. */ private int gameRoomsEntered; - + /** The number of rooms exited in this game. */ private int gameRoomsExited; - + /** The number of robots that have been shot during this game. */ private int gameRobotsShot; - + /** The number of robots that have been destroyed in this game (including those that have been shot). */ private int gameRobotsDestroyed; - + /** The number of times the player has been hit in this game. */ private int gamePlayerHits; - + /** The number of times the player has cleared a room during this game. */ private int gameCleanRooms; - + /** The number of times the player has cleared a room in a row. */ private int cleanRooms; - + /** The number of rooms that the player has got through without dying. */ private int gameRoomsWithoutDying; - + /** The number of robots in the room. */ private int numRobots; - + /** The number of times the player has fled from a room in a row. */ private int chickenRooms; - + /** The number of times the player has fled from a room during this game. */ private int gameChickenRooms; @@ -122,61 +125,60 @@ private Achievements(String summary, String text) { private boolean isPlayerHit; private float now; - - public StatusManager() { + + public StatusManager () { scoreNotifier = new ScoreNotifier(); achievementsNotifier = new AchievementsNotifier(); scoringEventNotifier = new ScoringEventNotifier(); achieved = EnumSet.noneOf(Achievements.class); } - - public void update(float delta) { + + public void update (float delta) { now += delta; if (daredevilTime != 0.0f && now >= daredevilTime) { achievement(Achievements.DAREDEVIL); daredevilTime = 0.0f; } } - - public void addScoreListener(ScoreListener listener) { + + public void addScoreListener (ScoreListener listener) { scoreNotifier.addListener(listener); } - - public void addAchievementsListener(AchievementsListener listener) { + + public void addAchievementsListener (AchievementsListener listener) { achievementsNotifier.addListener(listener); } - - public void addScoringEventListener(ScoringEventListener listener) { + + public void addScoringEventListener (ScoringEventListener listener) { scoringEventNotifier.addListener(listener); } - private void setLives(int lives) { + private void setLives (int lives) { this.lives = lives; scoreNotifier.onLivesChanged(lives); } - - private void addLives(int inc) { + + private void addLives (int inc) { setLives(lives + inc); } - private void setScore(int newScore) { + private void setScore (int newScore) { this.score = newScore; scoreNotifier.onScoreChanged(newScore); } - - private void addScore(int inc) { + + private void addScore (int inc) { int oldScore = score; setScore(score + inc); if (oldScore < EXTRA_LIFE_SCORE_1 && score >= EXTRA_LIFE_SCORE_1) { addLives(1); - } - else if (oldScore < EXTRA_LIFE_SCORE_2 && score >= EXTRA_LIFE_SCORE_2) { + } else if (oldScore < EXTRA_LIFE_SCORE_2 && score >= EXTRA_LIFE_SCORE_2) { addLives(1); } } @Override - public void onWorldReset() { + public void onWorldReset () { numGames++; achieved.clear(); if (numGames == ADDICT_GAMES) { @@ -199,7 +201,7 @@ public void onWorldReset() { } @Override - public void onEnteredRoom(float time, int robots) { + public void onEnteredRoom (float time, int robots) { robotsShot = 0; robotsDestroyed = 0; playerHits = 0; @@ -209,7 +211,7 @@ public void onEnteredRoom(float time, int robots) { } @Override - public void onExitedRoom(float time, int robots) { + public void onExitedRoom (float time, int robots) { gameRoomsExited++; if (robots == 0) { chickenRooms = 0; @@ -217,12 +219,10 @@ public void onExitedRoom(float time, int robots) { gameCleanRooms++; if (cleanRooms == CLEAN_ROOMS) { achievement(Achievements.PERFECTIONIST); - } - else if (robotsShot == 0) { + } else if (robotsShot == 0) { achievement(Achievements.PACIFICIST); } - } - else { + } else { cleanRooms = 0; chickenRooms++; gameChickenRooms++; @@ -235,24 +235,23 @@ else if (robotsShot == 0) { if (gameRoomsWithoutDying == LUCKY_JIM_ROOMS) { achievement(Achievements.LUCKY_JIM); } - } - else { + } else { gameRoomsWithoutDying = 0; } Gdx.app.log("Metrics", "FPS = " + Gdx.graphics.getFramesPerSecond()); } - + @Override - public void onRobotHit(Robot robot) { + public void onRobotHit (Robot robot) { robotsShot++; gameRobotsShot++; if (robotsShot == numRobots) { achievement(Achievements.PERFECT_SHOT); } } - + @Override - public void onRobotDestroyed(Robot robot) { + public void onRobotDestroyed (Robot robot) { robotsDestroyed++; gameRobotsDestroyed++; int robotScore = ROBOT_SCORE; @@ -265,9 +264,9 @@ public void onRobotDestroyed(Robot robot) { achievement(Achievements.ROBOCIDE); } } - + @Override - public void onPlayerHit() { + public void onPlayerHit () { daredevilTime = 0.0f; playerHits++; gamePlayerHits++; @@ -275,16 +274,16 @@ public void onPlayerHit() { } @Override - public void onCaptainActivated(float time) { + public void onCaptainActivated (float time) { daredevilTime = now + DAREDEVIL_SECONDS; } - + @Override - public void onPlayerFired() { + public void onPlayerFired () { } @Override - public void onPlayerSpawned() { + public void onPlayerSpawned () { if (isPlayerHit) { addLives(-1); isPlayerHit = false; @@ -292,14 +291,14 @@ public void onPlayerSpawned() { } @Override - public void onRobotFired(Robot robot) { + public void onRobotFired (Robot robot) { } @Override - public void onShotDestroyed(BaseShot shot) { + public void onShotDestroyed (BaseShot shot) { } - - private void achievement(Achievements achievement) { + + private void achievement (Achievements achievement) { if (!achieved.contains(achievement)) { achieved.add(achievement); achievementsNotifier.onAttained(achievement); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusView.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusView.java index d5364e3f10e..79b9fb39450 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusView.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/StatusView.java @@ -13,9 +13,6 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_HEIGHT; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_WIDTH; - import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.SpriteBatch; @@ -25,15 +22,17 @@ import com.badlydrawngames.general.ScoreString; import com.badlydrawngames.veryangryrobots.StatusManager.Achievements; +import static com.badlydrawngames.veryangryrobots.Assets.*; + public class StatusView implements ScoreListener, AchievementsListener { - + private static final float ACHIEVEMENT_DISPLAY_TIME = Config.asFloat("status.achievementDisplayTime", 10.0f); private static final float ACHIEVEMENT_FLASH_CYCLE = Config.asFloat("status.achievementFlashCycleLength", 1.0f); private static final float ACHIEVEMENT_FLASH_ON_PERCENT = Config.asFloat("status.achievementFlashOnPercent", 50.0f); private static final float ACHIEVEMENT_FLASH_ON_TIME = ACHIEVEMENT_FLASH_CYCLE * ACHIEVEMENT_FLASH_ON_PERCENT / 100.0f; private static final String RESUME_TEXT = "Tap to resume or press <> to quit"; - + private final World world; private final OrthographicCamera statusCam; private final SpriteBatch spriteBatch; @@ -43,15 +42,15 @@ public class StatusView implements ScoreListener, AchievementsListener { private float achievementTime; private float now; - public StatusView(World world) { + public StatusView (World world) { this.world = world; scoreString = new ScoreString(); statusCam = CameraHelper.createCamera2(ViewportMode.PIXEL_PERFECT, VIRTUAL_WIDTH, VIRTUAL_HEIGHT, Assets.pixelDensity); spriteBatch = new SpriteBatch(); spriteBatch.setProjectionMatrix(statusCam.combined); } - - public void render(float delta) { + + public void render (float delta) { now += delta; spriteBatch.begin(); if (!world.isPaused()) { @@ -59,27 +58,27 @@ public void render(float delta) { drawScore(); drawAchievements(); drawLives(); - } - else { + } else { drawPaused(); } spriteBatch.end(); } - private void drawPauseButton() { + private void drawPauseButton () { float w = Assets.pauseButton.getRegionWidth() / Assets.pixelDensity; float h = Assets.pauseButton.getRegionHeight() / Assets.pixelDensity; float y = VIRTUAL_HEIGHT - h; float x = 0.0f; spriteBatch.draw(Assets.pauseButton, x, y, w, h); } - - private void drawScore() { + + private void drawScore () { Assets.scoreFont.setColor(1.0f, 1.0f, 1.0f, 1.0f); - Assets.scoreFont.draw(spriteBatch, scoreString, 2, VIRTUAL_HEIGHT);; + Assets.scoreFont.draw(spriteBatch, scoreString, 2, VIRTUAL_HEIGHT); + ; } - - private void drawAchievements() { + + private void drawAchievements () { if (achievement != null) { float elapsed = now - achievementTime; if (elapsed < ACHIEVEMENT_DISPLAY_TIME) { @@ -90,25 +89,24 @@ private void drawAchievements() { float y = VIRTUAL_HEIGHT - 1 + Assets.textFont.getCapHeight() / 2; Assets.textFont.drawWrapped(spriteBatch, summary, x, y, w, HAlignment.LEFT); } - } - else { + } else { achievement = null; } } } - - private void drawLives() { + + private void drawLives () { float h = Assets.playerWalkingRight1.getRegionHeight() / Assets.pixelDensity; float y = VIRTUAL_HEIGHT - h; float w = Assets.playerWalkingRight1.getRegionWidth() / Assets.pixelDensity; float x = VIRTUAL_WIDTH - w; - for (int i = 0; i < lives - 1; i++) { + for (int i = 0; i < lives - 1; i++) { spriteBatch.draw(Assets.playerWalkingRight1, x, y, w, h); x -= w; } } - - private void drawPaused() { + + private void drawPaused () { if (world.getPausedTime() % 1.0f < 0.5f) { float y = VIRTUAL_HEIGHT - 1 + Assets.scoreFont.getCapHeight() / 2; Assets.textFont.setColor(1.0f, 1.0f, 1.0f, 1.0f); @@ -117,17 +115,17 @@ private void drawPaused() { } @Override - public void onScoreChanged(int score) { + public void onScoreChanged (int score) { scoreString.setScore(score); } @Override - public void onLivesChanged(int lives) { + public void onLivesChanged (int lives) { this.lives = lives; } @Override - public void onAttained(Achievements achievement) { + public void onAttained (Achievements achievement) { this.achievement = achievement; this.achievementTime = now; } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/VeryAngryRobotsGame.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/VeryAngryRobotsGame.java index 4e01ace7835..f0f3d16da32 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/VeryAngryRobotsGame.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/VeryAngryRobotsGame.java @@ -25,51 +25,49 @@ public class VeryAngryRobotsGame extends Game implements AchievementsListener { IShowScores scoreDisplayer; ISubmitScores scoreSubmitter; AchievementsListener achievementsListener; - - /** - * Creates all the screens that the game will need, then switches to the main menu. - */ + + /** Creates all the screens that the game will need, then switches to the main menu. */ @Override - public void create() { + public void create () { Assets.load(); mainMenuScreen = new MainMenuScreen(this); playingScreen = new WorldPresenter(this); scoresScreen = new ScoresScreen(this); setScreen(mainMenuScreen); } - - public void submitScore(int score) { + + public void submitScore (int score) { if (scoreSubmitter != null) { scoreSubmitter.submitScore(score); } } - - public void showScores() { + + public void showScores () { if (scoreDisplayer != null) { scoreDisplayer.showScores(); } } - + @Override - public void onAttained(Achievements achievement) { + public void onAttained (Achievements achievement) { if (achievementsListener != null) { achievementsListener.onAttained(achievement); } } - - public void setScoreDisplayer(IShowScores scoreDisplayer) { + + public void setScoreDisplayer (IShowScores scoreDisplayer) { this.scoreDisplayer = scoreDisplayer; } - public void setScoreSubmitter(ISubmitScores scoreSubmitter) { + public void setScoreSubmitter (ISubmitScores scoreSubmitter) { this.scoreSubmitter = scoreSubmitter; } - public void setAchievementsListener(AchievementsListener listener) { + public void setAchievementsListener (AchievementsListener listener) { this.achievementsListener = listener; } - public boolean canShowScores() { + public boolean canShowScores () { return scoreDisplayer != null; } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/World.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/World.java index 700a3cc4e97..270b1e34791 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/World.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/World.java @@ -13,9 +13,6 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlogic.gdx.math.MathUtils.random; -import static com.badlydrawngames.general.MathUtils.max; - import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; @@ -36,31 +33,25 @@ import com.badlydrawngames.veryangryrobots.mobiles.Robot; import com.badlydrawngames.veryangryrobots.mobiles.RobotShot; -/** - * The World is the representation of the game world of Very Angry Robots. It knows nothing about - * how it will be displayed, neither does it know about how the player is controlled, particle effects, sounds, nor - * anything else. It purely knows about the {@link Player}, {@link Robot}s and the walls of the room that the player - * is in. +import static com.badlogic.gdx.math.MathUtils.*; +import static com.badlydrawngames.general.MathUtils.*; + +/** The World is the representation of the game world of Very Angry Robots. It knows nothing about how it will + * be displayed, neither does it know about how the player is controlled, particle effects, sounds, nor anything else. It purely + * knows about the {@link Player}, {@link Robot}s and the walls of the room that the player is in. * - * @author Rod - * - */ + * @author Rod */ public class World { - /** - * The FireCommand interface is how the {@link World} is told that a {@link GameObject} wants to - * fire. - */ + /** The FireCommand interface is how the {@link World} is told that a {@link GameObject} wants to fire. */ public static interface FireCommand { - /** - * Tells the {@link World} that a {@link GameObject} wants to fire. Note that dx and - * dy must be normalised. The World does not have to fire just because it is asked to. + /** Tells the {@link World} that a {@link GameObject} wants to fire. Note that dx and dy must be + * normalised. The World does not have to fire just because it is asked to. * * @param firer the {@link GameObject} that wants to fire. * @param dx the horizontal component of the bullet's direction. - * @param dy the vertical component of the bullet's direction. - */ - void fire(GameObject firer, float dx, float dy); + * @param dy the vertical component of the bullet's direction. */ + void fire (GameObject firer, float dx, float dy); } // Maze proportions. @@ -87,13 +78,13 @@ public static interface FireCommand { public static final int ENTERED_ROOM = 2; public static final int PLAYING = 3; public static final int PLAYER_DEAD = 4; - + private final Pool shotPool; private final Pool robotPool; private final Pool robotShotPool; private final Grid roomGrid; private final RoomBuilder roomBuilder; - private final Rectangle roomBounds; + private final Rectangle roomBounds; private final float minX; private final float maxX; private final float minY; @@ -103,7 +94,7 @@ public static interface FireCommand { private long roomSeed; private int roomX; private int roomY; - private float playingTime; + private float playingTime; private float nextFireTime; private int numRobotShots; private float robotShotSpeed; @@ -124,96 +115,94 @@ public static interface FireCommand { private boolean isPaused; private float pausedTime; - public void pause() { + public void pause () { isPaused = true; pausedTime = 0.0f; } - - public void resume() { + + public void resume () { isPaused = false; } - - public boolean isPaused() { + + public boolean isPaused () { return isPaused; } - public float getPausedTime() { + public float getPausedTime () { return pausedTime; } - public int getState() { + public int getState () { return state; } - private void setState(int newState) { + private void setState (int newState) { state = newState; stateTime = 0.0f; } - public float getStateTime() { + public float getStateTime () { return stateTime; } - public Color getRobotColor() { + public Color getRobotColor () { return robotColor; } - public int getDoorPosition() { + public int getDoorPosition () { return doorPosition; } - public Array getDoorRects() { + public Array getDoorRects () { return doorRects; } - public Array getWallRects() { + public Array getWallRects () { return wallRects; } - public Rectangle getRoomBounds() { + public Rectangle getRoomBounds () { return roomBounds; } - public Player getPlayer() { + public Player getPlayer () { return player; } - public Array getPlayerShots() { + public Array getPlayerShots () { return playerShots; } - public Array getRobots() { + public Array getRobots () { return robots; } - public Array getRobotShots() { + public Array getRobotShots () { return robotShots; } - public Captain getCaptain() { + public Captain getCaptain () { return captain; } - /** - * Adds another listener to the {@link World}. + /** Adds another listener to the {@link World}. * - * @param listener the listener. - */ - public void addWorldListener(WorldListener listener) { + * @param listener the listener. */ + public void addWorldListener (WorldListener listener) { notifier.addListener(listener); } public final FireCommand firePlayerShot = new FireCommand() { @Override - public void fire(GameObject firer, float dx, float dy) { + public void fire (GameObject firer, float dx, float dy) { if (now >= nextFireTime) { addPlayerShot(dx, dy); nextFireTime = now + FIRING_INTERVAL; } } }; - - private void addPlayerShot(float dx, float dy) { + + private void addPlayerShot (float dx, float dy) { if (state == PLAYING && playerShots.size < MAX_PLAYER_SHOTS) { PlayerShot shot = shotPool.obtain(); shot.inCollision = false; @@ -224,15 +213,15 @@ private void addPlayerShot(float dx, float dy) { notifier.onPlayerFired(); } } - + public final FireCommand fireRobotShot = new FireCommand() { @Override - public void fire(GameObject firer, float dx, float dy) { + public void fire (GameObject firer, float dx, float dy) { addRobotShot(firer, dx, dy); } }; - - private void addRobotShot(GameObject firer, float dx, float dy) { + + private void addRobotShot (GameObject firer, float dx, float dy) { if (state == PLAYING && robotShots.size < numRobotShots && stateTime >= FIRING_AMNESTY_INTERVAL) { RobotShot shot = robotShotPool.obtain(); shot.inCollision = false; @@ -242,42 +231,42 @@ private void addRobotShot(GameObject firer, float dx, float dy) { float y = firer.y + firer.height / 2 - shot.height / 2; shot.fire(x, y, dx, dy); robotShots.add(shot); - notifier.onRobotFired((Robot) firer); + notifier.onRobotFired((Robot)firer); } } - + private final RemovalHandler robotRemovalHandler = new RemovalHandler() { @Override - public void onRemove(Robot robot) { + public void onRemove (Robot robot) { notifier.onRobotDestroyed(robot); } }; - + private final RemovalHandler shotRemovalHandler = new RemovalHandler() { @Override - public void onRemove(BaseShot shot) { + public void onRemove (BaseShot shot) { notifier.onShotDestroyed(shot); } }; - + private final ColliderHandler gameObjectCollisionHandler = new ColliderHandler() { @Override - public void onCollision(GameObject t, GameObject u) { + public void onCollision (GameObject t, GameObject u) { t.inCollision = true; u.inCollision = true; } }; - + private final ColliderHandler captainGameObjectCollisionHandler = new ColliderHandler() { @Override - public void onCollision(Captain captain, GameObject go) { + public void onCollision (Captain captain, GameObject go) { go.inCollision = true; } }; - + private final ColliderHandler shotRobotCollisionHandler = new ColliderHandler() { @Override - public void onCollision(PlayerShot shot, Robot robot) { + public void onCollision (PlayerShot shot, Robot robot) { if (!robot.inCollision) { notifier.onRobotHit(robot); } @@ -285,34 +274,32 @@ public void onCollision(PlayerShot shot, Robot robot) { robot.inCollision = true; } }; - + private final ColliderHandler robotRobotCollisionHandler = new ColliderHandler() { @Override - public void onCollision(Robot t, Robot u) { + public void onCollision (Robot t, Robot u) { t.inCollision = true; u.inCollision = true; } }; - + private final SceneryHandler playerSceneryHandler = new SceneryHandler() { @Override - public void onCollision(Player player, Rectangle r) { + public void onCollision (Player player, Rectangle r) { player.inCollision = true; } }; - + private final SceneryHandler gameObjectSceneryHandler = new SceneryHandler() { @Override - public void onCollision(GameObject t, Rectangle r) { + public void onCollision (GameObject t, Rectangle r) { t.inCollision = true; } }; - - /** - * Constructs a new {@link World}. - */ - public World(DifficultyManager difficultyManager) { - this.difficultyManager = difficultyManager; + + /** Constructs a new {@link World}. */ + public World (DifficultyManager difficultyManager) { + this.difficultyManager = difficultyManager; notifier = new WorldNotifier(); minX = 0; maxX = WALL_WIDTH * HCELLS; @@ -324,42 +311,38 @@ public World(DifficultyManager difficultyManager) { playerPos = new Vector2(); roomBuilder = new RoomBuilder(HCELLS, VCELLS); roomGrid = new Grid(HCELLS * 2, VCELLS * 2, maxX, maxY); - + shotPool = new Pool(MAX_PLAYER_SHOTS, MAX_PLAYER_SHOTS) { @Override - protected PlayerShot newObject() { + protected PlayerShot newObject () { return new PlayerShot(); } }; - + robotPool = new Pool(MAX_ROBOTS, MAX_ROBOTS) { @Override - protected Robot newObject() { + protected Robot newObject () { return new Robot(); } }; - + robotShotPool = new Pool(MAX_ROBOT_SHOTS, MAX_ROBOT_SHOTS) { @Override - protected RobotShot newObject() { + protected RobotShot newObject () { return new RobotShot(); } }; } - /** - * Resets the {@link World} to its starting state. - */ - public void reset() { + /** Resets the {@link World} to its starting state. */ + public void reset () { setState(RESETTING); } - /** - * Called when the {@link World} is to be updated. - * - * @param delta the time in seconds since the last render. - */ - public void update(float delta) { + /** Called when the {@link World} is to be updated. + * + * @param delta the time in seconds since the last render. */ + public void update (float delta) { if (!isPaused) { now += delta; stateTime += delta; @@ -377,34 +360,33 @@ public void update(float delta) { updatePlayerDead(delta); break; } - } - else { + } else { pausedTime += delta; } } - - private void updateResetting() { + + private void updateResetting () { notifier.onWorldReset(); roomSeed = System.currentTimeMillis(); roomX = 0; roomY = 0; populateRoom(DoorPositions.MIN_Y); } - - private void updateEnteredRoom() { + + private void updateEnteredRoom () { if (stateTime >= ROOM_TRANSITION_TIME) { setState(PLAYING); } } - - private void updatePlaying(float delta) { + + private void updatePlaying (float delta) { player.update(delta); updateMobiles(delta); checkForCollisions(); checkForLeavingRoom(); } - - private void updatePlayerDead(float delta) { + + private void updatePlayerDead (float delta) { updateMobiles(delta); checkForCollisions(); if (now >= playingTime) { @@ -412,8 +394,8 @@ private void updatePlayerDead(float delta) { setState(PLAYING); } } - - private void populateRoom(int doorPos) { + + private void populateRoom (int doorPos) { doorPosition = doorPos; setRandomSeedFromRoom(); createMaze(); @@ -426,7 +408,7 @@ private void populateRoom(int doorPos) { notifier.onEnteredRoom(now, numRobots); } - private void createMaze() { + private void createMaze () { roomBuilder.build(doorPosition); wallRects = roomBuilder.getWalls(); doorRects = roomBuilder.getDoors(); @@ -439,64 +421,64 @@ private void createMaze() { } } - private void setRandomSeedFromRoom() { + private void setRandomSeedFromRoom () { long seed = roomSeed + ((roomX & 0xff) | ((roomY & 0xff) << 8)); random.setSeed(seed); } - - private void placePlayer() { + + private void placePlayer () { player.inCollision = false; - + switch (doorPosition) { - + case DoorPositions.MIN_X: player.x = minX + player.width / 2; player.y = (maxY + minY) / 2 - player.height / 2; break; - + case DoorPositions.MAX_X: player.x = maxX - player.width - player.width / 2; player.y = (maxY + minY) / 2 - player.height / 2; break; - + case DoorPositions.MAX_Y: player.x = (maxX + minX) / 2 - player.width / 2; - player.y = maxY - player.height - player.height / 4; + player.y = maxY - player.height - player.height / 4; break; - + case DoorPositions.MIN_Y: default: player.x = (maxX + minX) / 2 - player.width / 2; - player.y = minY + player.height / 4; + player.y = minY + player.height / 4; break; } - + player.setState(Player.FACING_RIGHT); notifier.onPlayerSpawned(); } - - private void placeCaptain() { + + private void placeCaptain () { captain.inCollision = false; captain.setState(Captain.LURKING); captain.activateAfter(max(CAPTAIN_MIN_DELAY, CAPTAIN_LURK_MULTIPLIER * robots.size)); captain.setPlayer(player); - + switch (doorPosition) { case DoorPositions.MIN_X: captain.x = minX - 2 * captain.width; captain.y = (maxY + minY) / 2 - captain.height / 2; break; - + case DoorPositions.MAX_X: captain.x = maxX + captain.width; captain.y = (maxY + minY) / 2 - captain.height / 2; break; - + case DoorPositions.MAX_Y: captain.x = (maxX + minX) / 2 - captain.width / 2; captain.y = maxY + captain.height; break; - + case DoorPositions.MIN_Y: default: captain.x = (maxX + minX) / 2 - captain.width / 2; @@ -505,12 +487,12 @@ private void placeCaptain() { } } - private void createRobots() { + private void createRobots () { robotColor = difficultyManager.getRobotColor(); numRobots = difficultyManager.getNumberOfRobots(); numRobotShots = difficultyManager.getNumberOfRobotShots(); robotShotSpeed = difficultyManager.getRobotShotSpeed(); - + final float minXSpawn = minX + WALL_HEIGHT; final float minYSpawn = minY + WALL_HEIGHT; final float maxXSpawn = maxX - WALL_HEIGHT; @@ -531,20 +513,20 @@ private void createRobots() { robots.add(robot); } } - - private boolean canSpawnHere(Robot robot) { + + private boolean canSpawnHere (Robot robot) { return !(intersectsWalls(robot) || intersectsDoors(robot) || intersectsRobots(robot) || playerPos.dst(robot.x, robot.y) < WALL_WIDTH); } - - private boolean intersectsWalls(Robot robot) { + + private boolean intersectsWalls (Robot robot) { return Colliders.intersects(robot.bounds(), wallRects); } - private boolean intersectsDoors(Robot robot) { + private boolean intersectsDoors (Robot robot) { return Colliders.intersects(robot.bounds(), doorRects); } - - private boolean intersectsRobots(Robot robot) { + + private boolean intersectsRobots (Robot robot) { for (int i = 0; i < robots.size; i++) { if (robot.boundsIntersect(robots.get(i))) { return true; @@ -553,22 +535,22 @@ private boolean intersectsRobots(Robot robot) { return false; } - private void createPlayerShots() { + private void createPlayerShots () { playerShots = Pools.makeArrayFromPool(playerShots, shotPool, MAX_PLAYER_SHOTS); } - - private void createRobotShots() { + + private void createRobotShots () { robotShots = Pools.makeArrayFromPool(robotShots, robotShotPool, MAX_ROBOT_SHOTS); } - - private void updateMobiles(float delta) { + + private void updateMobiles (float delta) { updateCaptain(delta); update(robots, delta); update(playerShots, delta); update(robotShots, delta); } - - private void resetRoom() { + + private void resetRoom () { placePlayer(); placeCaptain(); for (Robot robot : robots) { @@ -578,20 +560,20 @@ private void resetRoom() { playerShots.clear(); } - private void updateCaptain(float delta) { + private void updateCaptain (float delta) { captain.update(delta); if (captain.stateTime == 0.0f && captain.state == Captain.CHASING) { doCaptainActivated(); } } - - private void update(Array gos, float delta) { + + private void update (Array gos, float delta) { for (GameObject go : gos) { go.update(delta); } } - - private void checkForCollisions() { + + private void checkForCollisions () { checkMobileMobileCollisions(); checkMobileSceneryCollisions(); removeMarkedMobiles(); @@ -600,7 +582,7 @@ private void checkForCollisions() { } } - private void checkMobileMobileCollisions() { + private void checkMobileMobileCollisions () { Colliders.collide(player, robots, gameObjectCollisionHandler); Colliders.collide(player, robotShots, gameObjectCollisionHandler); Colliders.collide(captain, player, captainGameObjectCollisionHandler); @@ -614,21 +596,21 @@ private void checkMobileMobileCollisions() { Colliders.collide(captain, robotShots, captainGameObjectCollisionHandler); } - private void checkMobileSceneryCollisions() { + private void checkMobileSceneryCollisions () { Colliders.collide(player, roomGrid.get(player.bounds()), playerSceneryHandler); markSceneryCollisions(robots, gameObjectSceneryHandler); markSceneryCollisions(playerShots, gameObjectSceneryHandler); markSceneryCollisions(robotShots, gameObjectSceneryHandler); } - private void markSceneryCollisions(Array gos, SceneryHandler handler) { + private void markSceneryCollisions (Array gos, SceneryHandler handler) { for (int i = 0; i < gos.size; i++) { T go = gos.get(i); Colliders.collide(go, roomGrid.get(go.bounds()), handler); } } - - private void removeMarkedMobiles() { + + private void removeMarkedMobiles () { Colliders.removeOutOfBounds(shotPool, playerShots, roomBounds); Colliders.removeOutOfBounds(robotShotPool, robotShots, roomBounds); Colliders.removeMarkedCollisions(shotPool, playerShots, shotRemovalHandler); @@ -636,21 +618,18 @@ private void removeMarkedMobiles() { Colliders.removeMarkedCollisions(robotShotPool, robotShots, shotRemovalHandler); } - private void checkForLeavingRoom() { + private void checkForLeavingRoom () { int newDoor = -1; if (player.x + player.width / 2 < minX) { roomX--; newDoor = DoorPositions.MAX_X; - } - else if (player.x + player.width / 2 > maxX) { + } else if (player.x + player.width / 2 > maxX) { roomX++; newDoor = DoorPositions.MIN_X; - } - else if (player.y + player.height / 2 < minY) { + } else if (player.y + player.height / 2 < minY) { roomY--; newDoor = DoorPositions.MAX_Y; - } - else if (player.y + player.height / 2 > maxY) { + } else if (player.y + player.height / 2 > maxY) { roomY++; newDoor = DoorPositions.MIN_Y; } @@ -659,18 +638,18 @@ else if (player.y + player.height / 2 > maxY) { } } - private void doPlayerHit() { + private void doPlayerHit () { notifier.onPlayerHit(); setState(PLAYER_DEAD); playingTime = now + PLAYER_DEAD_INTERVAL; } - - private void doLeftRoom(int newDoor) { + + private void doLeftRoom (int newDoor) { notifier.onExitedRoom(now, robots.size); populateRoom(newDoor); } - - private void doCaptainActivated() { + + private void doCaptainActivated () { notifier.onCaptainActivated(now); } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldListener.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldListener.java index 12c75f2618a..42f87bddb53 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldListener.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldListener.java @@ -17,15 +17,25 @@ import com.badlydrawngames.veryangryrobots.mobiles.Robot; public interface WorldListener { - public void onCaptainActivated(float time); - public void onEnteredRoom(float time, int robots); - public void onExitedRoom(float time, int robots); - public void onPlayerFired(); - public void onPlayerHit(); - public void onPlayerSpawned(); - public void onRobotDestroyed(Robot robot); - public void onRobotFired(Robot robot); - public void onRobotHit(Robot robot); - public void onShotDestroyed(BaseShot shot); - public void onWorldReset(); + public void onCaptainActivated (float time); + + public void onEnteredRoom (float time, int robots); + + public void onExitedRoom (float time, int robots); + + public void onPlayerFired (); + + public void onPlayerHit (); + + public void onPlayerSpawned (); + + public void onRobotDestroyed (Robot robot); + + public void onRobotFired (Robot robot); + + public void onRobotHit (Robot robot); + + public void onShotDestroyed (BaseShot shot); + + public void onWorldReset (); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldNotifier.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldNotifier.java index d199182774b..b8699257d37 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldNotifier.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldNotifier.java @@ -21,86 +21,86 @@ class WorldNotifier implements WorldListener { private final Array listeners; - public WorldNotifier() { + public WorldNotifier () { listeners = new Array(); } - - public void addListener(WorldListener listener) { + + public void addListener (WorldListener listener) { listeners.add(listener); } - + @Override - public void onCaptainActivated(float time) { + public void onCaptainActivated (float time) { for (WorldListener listener : listeners) { listener.onCaptainActivated(time); } } @Override - public void onEnteredRoom(float time, int robots) { + public void onEnteredRoom (float time, int robots) { for (WorldListener listener : listeners) { listener.onEnteredRoom(time, robots); } } @Override - public void onExitedRoom(float time, int robots) { + public void onExitedRoom (float time, int robots) { for (WorldListener listener : listeners) { listener.onExitedRoom(time, robots); } } @Override - public void onPlayerFired() { + public void onPlayerFired () { for (WorldListener listener : listeners) { listener.onPlayerFired(); } } @Override - public void onPlayerHit() { + public void onPlayerHit () { for (WorldListener listener : listeners) { listener.onPlayerHit(); } } @Override - public void onPlayerSpawned() { + public void onPlayerSpawned () { for (WorldListener listener : listeners) { listener.onPlayerSpawned(); - } + } } @Override - public void onRobotDestroyed(Robot robot) { + public void onRobotDestroyed (Robot robot) { for (WorldListener listener : listeners) { listener.onRobotDestroyed(robot); - } + } } @Override - public void onRobotFired(Robot robot) { + public void onRobotFired (Robot robot) { for (WorldListener listener : listeners) { listener.onRobotFired(robot); } } @Override - public void onRobotHit(Robot robot) { + public void onRobotHit (Robot robot) { for (WorldListener listener : listeners) { listener.onRobotHit(robot); } } @Override - public void onShotDestroyed(BaseShot shot) { + public void onShotDestroyed (BaseShot shot) { for (WorldListener listener : listeners) { listener.onShotDestroyed(shot); } } @Override - public void onWorldReset() { + public void onWorldReset () { for (WorldListener listener : listeners) { listener.onWorldReset(); } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldPresenter.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldPresenter.java index 542168bf000..6bc5eb21581 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldPresenter.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldPresenter.java @@ -19,21 +19,18 @@ import com.badlydrawngames.general.GameScreen; import com.badlydrawngames.veryangryrobots.mobiles.Player; -/** - *

    - * It is the role of the WorldPresenter to glue together the {@link World} and the {@link WorldView}. It - * passes on information from the controls in the WorldView to the World, updates it, then asks the WorldView to draw - * everything on its behalf. The {@link WorldView} tells this WorldPresenter what to do via the methods - * provided by the {@link WorldView#Presenter} interface. +/**

    + * It is the role of the WorldPresenter to glue together the {@link World} and the {@link WorldView}. It passes on + * information from the controls in the WorldView to the World, updates it, then asks the WorldView to draw everything on its + * behalf. The {@link WorldView} tells this WorldPresenter what to do via the methods provided by the + * {@link WorldView#Presenter} interface. *

    * - * @author Rod - * - */ + * @author Rod */ public class WorldPresenter extends GameScreen implements WorldView.Presenter, ScoreListener { private static final float MAX_DELTA = 0.1f; - + private final World world; private final WorldView worldView; private final StatusView statusView; @@ -44,12 +41,10 @@ public class WorldPresenter extends GameScreen implements W private boolean isDead; private boolean wasBackPressed; - /** - * Constructs a new WorldPresenter. + /** Constructs a new WorldPresenter. * - * @param game the game, used primarily for switching between screens. - */ - public WorldPresenter(VeryAngryRobotsGame game) { + * @param game the game, used primarily for switching between screens. */ + public WorldPresenter (VeryAngryRobotsGame game) { super(game); difficultyManager = new ScoreBasedDifficultyManager(); world = new World(difficultyManager); @@ -69,43 +64,41 @@ public WorldPresenter(VeryAngryRobotsGame game) { } @Override - public void show() { + public void show () { Gdx.input.setCatchBackKey(true); wasBackPressed = false; world.reset(); world.resume(); } - + @Override - public void pause() { + public void pause () { world.pause(); } - + @Override - public void resume() { + public void resume () { Gdx.input.setCatchBackKey(true); world.resume(); } - + @Override - public void hide() { + public void hide () { Gdx.input.setCatchBackKey(false); } - - /** - * Called by libgdx when this screen should render itself. It responds to a request to render by updating the - * controls, updating the world and the managers, then drawing the views. + + /** Called by libgdx when this screen should render itself. It responds to a request to render by updating the controls, + * updating the world and the managers, then drawing the views. * - * @param delta the time in seconds since the last time render was called. - */ + * @param delta the time in seconds since the last time render was called. */ @Override - public void render(float delta) { + public void render (float delta) { // Update time. if (delta >= MAX_DELTA) delta = MAX_DELTA; - + // Ask the view to update the controls. worldView.updateControls(delta); - + // If we're not paused then update the world and the subsystems. world.update(delta); if (!world.isPaused()) { @@ -113,13 +106,13 @@ public void render(float delta) { worldView.update(delta); soundManager.update(delta); } - + // Clear the screen and draw the views. Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); worldView.render(delta); statusView.render(delta); - + if (isDead && world.getState() == World.PLAYING) { game.submitScore(score); game.setScreen(game.scoresScreen); @@ -129,45 +122,40 @@ public void render(float delta) { if (!wasBackPressed && isBackPressed) { if (!world.isPaused()) { world.pause(); - } - else { + } else { game.setScreen(game.mainMenuScreen); } } wasBackPressed = isBackPressed; } - - /** - * Called by the {@link WorldView} when the player wants to move. + + /** Called by the {@link WorldView} when the player wants to move. * * @param x the x value of the controller. - * @param y the y value of the controller. - */ + * @param y the y value of the controller. */ @Override - public void setController(float x, float y) { + public void setController (float x, float y) { Player player = world.getPlayer(); player.setController(x, y); } - /** - * Called by the {@link WorldView} when the player wants to fire. + /** Called by the {@link WorldView} when the player wants to fire. * * @param x the x value of the controller. - * @param y the y value of the controller. - */ + * @param y the y value of the controller. */ @Override - public void setFiringController(float x, float y) { + public void setFiringController (float x, float y) { Player player = world.getPlayer(); world.firePlayerShot.fire(player, x, y); } @Override - public void onScoreChanged(int score) { + public void onScoreChanged (int score) { this.score = score; } @Override - public void onLivesChanged(int lives) { + public void onLivesChanged (int lives) { isDead = (lives == 0); } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldView.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldView.java index 57528396599..f51678749a0 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldView.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/WorldView.java @@ -13,10 +13,6 @@ package com.badlydrawngames.veryangryrobots; -import static com.badlydrawngames.general.MathUtils.min; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_HEIGHT; -import static com.badlydrawngames.veryangryrobots.Assets.VIRTUAL_WIDTH; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; @@ -43,33 +39,34 @@ import com.badlydrawngames.veryangryrobots.mobiles.PlayerShot; import com.badlydrawngames.veryangryrobots.mobiles.Robot; -/** - * The WorldView displays the {@link World} on screen. It also provides the means by which the player can - * control the game. +import static com.badlydrawngames.general.MathUtils.*; +import static com.badlydrawngames.veryangryrobots.Assets.*; + +/** The WorldView displays the {@link World} on screen. It also provides the means by which the player can control the + * game. * - * @author Rod - * - */ + * @author Rod */ public class WorldView { - /** - * The Presenter interface is how the WorldView communicates the state of its controls. - */ + /** The Presenter interface is how the WorldView communicates the state of its controls. */ public static interface Presenter { - void setController(float x, float y); - void setFiringController(float dx, float dy); - void pause(); - void resume(); + void setController (float x, float y); + + void setFiringController (float dx, float dy); + + void pause (); + + void resume (); } private static final float PARTICLE_SIZE = Config.asFloat("particle.size", 0.1875f); - - private static final int SPRITE_CACHE_SIZE = 128; // TODO: add to Config? - private static final float FIRING_DEAD_ZONE = 0.125f; // TODO: add to Config. - private static final float JOYSTICK_DISTANCE_MULTIPLIER = 0.2f; // TODO: add to Config. - + + private static final int SPRITE_CACHE_SIZE = 128; // TODO: add to Config? + private static final float FIRING_DEAD_ZONE = 0.125f; // TODO: add to Config. + private static final float JOYSTICK_DISTANCE_MULTIPLIER = 0.2f; // TODO: add to Config. + private static final int MAX_PARTICLES = 256; - + private final World world; private final Presenter presenter; private OrthographicCamera worldCam; @@ -92,14 +89,12 @@ public static interface Presenter { private final float worldHeight; private final float worldMaxX; private final float worldMaxY; - - /** - * Constructs a new WorldView. + + /** Constructs a new WorldView. * * @param world the {@link World} that this is a view of. - * @param presenter the interface by which this WorldView communicates the state of its controls. - */ - public WorldView(World world, StatusManager statusManager, Presenter presenter) { + * @param presenter the interface by which this WorldView communicates the state of its controls. */ + public WorldView (World world, StatusManager statusManager, Presenter presenter) { this.world = world; this.presenter = presenter; Rectangle bounds = world.getRoomBounds(); @@ -131,19 +126,17 @@ public WorldView(World world, StatusManager statusManager, Presenter presenter) resetCaches(); } - public void update(float delta) { + public void update (float delta) { particleAdapter.update(delta); flyupManager.update(delta); } - - /** - * Called when the view should be rendered. + + /** Called when the view should be rendered. * - * @param delta the time in seconds since the last render. - */ - public void render(float delta) { + * @param delta the time in seconds since the last render. */ + public void render (float delta) { switch (world.getState()) { - + case World.RESETTING: resetCaches(); break; @@ -157,7 +150,7 @@ public void render(float delta) { drawWallsAndDoors(); drawMobiles(); break; - + case World.PLAYING: // TODO: this is really a bit of a hack ... does it really need to be called every tick? if (world.getStateTime() == 0.0f) { @@ -172,26 +165,26 @@ public void render(float delta) { break; } } - - private void resetCaches() { + + private void resetCaches () { cacheId = -1; cacheTransform.idt(); prevCacheTransform.idt(); } - - private void createMazeContent() { + + private void createMazeContent () { cycleCaches(); cacheId = createWallsAndDoors(spriteCache); } - - private void cycleCaches() { + + private void cycleCaches () { SpriteCache tempCache = prevSpriteCache; prevSpriteCache = spriteCache; spriteCache = tempCache; prevCacheId = cacheId; } - - private int createWallsAndDoors(SpriteCache sc) { + + private int createWallsAndDoors (SpriteCache sc) { // Walls and doors never move, so we put them into a sprite cache. sc.clear(); sc.beginCache(); @@ -209,8 +202,8 @@ private int createWallsAndDoors(SpriteCache sc) { } return sc.endCache(); } - - private void updatePanning() { + + private void updatePanning () { // If we're moving from one room to another then we want to draw the old room scrolling off as the new room // scrolls on. final float w = worldWidth; @@ -223,42 +216,42 @@ private void updatePanning() { prevCacheTransform.idt().trn(0.0f, -h * time, 0.0f); cacheTransform.idt().trn(0.0f, h - h * time, 0.0f); break; - + case DoorPositions.MAX_Y: prevCacheTransform.idt().trn(0.0f, h * time, 0.0f); cacheTransform.idt().trn(0.0f, -h + h * time, 0.0f); break; - + case DoorPositions.MIN_X: prevCacheTransform.idt().trn(-w * time, 0.0f, 0.0f); cacheTransform.idt().trn(w - w * time, 0.0f, 0.0f); break; - + case DoorPositions.MAX_X: prevCacheTransform.idt().trn(w * time, 0.0f, 0.0f); cacheTransform.idt().trn(-w + w * time, 0.0f, 0.0f); } - + prevSpriteCache.setTransformMatrix(prevCacheTransform); spriteCache.setTransformMatrix(cacheTransform); spriteBatch.setTransformMatrix(cacheTransform); } - - private void drawWallsAndDoors() { + + private void drawWallsAndDoors () { // Draw the old room if it is scrolling off. if (world.getState() == World.ENTERED_ROOM && prevCacheId != -1) { prevSpriteCache.begin(); prevSpriteCache.draw(prevCacheId); prevSpriteCache.end(); } - + // Draw the current room. spriteCache.begin(); spriteCache.draw(cacheId); spriteCache.end(); } - - private void drawMobiles() { + + private void drawMobiles () { spriteBatch.setProjectionMatrix(worldCam.combined); spriteBatch.begin(); spriteBatch.setColor(Color.WHITE); @@ -272,34 +265,34 @@ private void drawMobiles() { spriteBatch.end(); } - private void drawRobots() { + private void drawRobots () { spriteBatch.setColor(world.getRobotColor()); for (Robot robot : world.getRobots()) { drawRobot(robot); } spriteBatch.setColor(Color.WHITE); } - - private void drawCaptain() { + + private void drawCaptain () { Captain captain = world.getCaptain(); - if (captain.state == Captain.CHASING) { + if (captain.state == Captain.CHASING) { drawClipped(captain, Assets.nemesisAnimation.getKeyFrame(captain.stateTime, true)); } } - private void drawPlayersShots() { + private void drawPlayersShots () { for (PlayerShot shot : world.getPlayerShots()) { draw(shot, Assets.playerShot); } } - - private void drawRobotsShots() { + + private void drawRobotsShots () { for (BaseShot shot : world.getRobotShots()) { draw(shot, Assets.robotShot); } } - private void drawPlayer() { + private void drawPlayer () { Player player = world.getPlayer(); switch (player.state) { case Player.WALKING_LEFT: @@ -316,8 +309,8 @@ private void drawPlayer() { break; } } - - private void drawRobot(Robot robot) { + + private void drawRobot (Robot robot) { Animation robotAnimation = null; switch (robot.state) { case Robot.SCANNING: @@ -346,17 +339,17 @@ private void drawRobot(Robot robot) { } draw(robot, robotAnimation.getKeyFrame(robot.stateTime, true)); } - - private void draw(GameObject go, TextureRegion region) { + + private void draw (GameObject go, TextureRegion region) { spriteBatch.draw(region, go.x, go.y, go.width, go.height); } - private void drawClipped(GameObject go, TextureRegion region) { + private void drawClipped (GameObject go, TextureRegion region) { float boundsMinX = worldMinX + World.OUTER_WALL_ADJUST + World.WALL_HEIGHT; float boundsMaxX = worldMaxX - World.OUTER_WALL_ADJUST - World.WALL_HEIGHT; float boundsMinY = worldMinY + World.OUTER_WALL_ADJUST + World.WALL_HEIGHT; float boundsMaxY = worldMaxY - World.OUTER_WALL_ADJUST - World.WALL_HEIGHT; - + // Don't draw if it's completely out of bounds. float maxX = go.x + go.width; if (maxX < boundsMinX) return; @@ -374,45 +367,33 @@ private void drawClipped(GameObject go, TextureRegion region) { int srcY = region.getRegionY(); int srcWidth = region.getRegionWidth(); int srcHeight = region.getRegionHeight(); - if (minX < boundsMinX) { + if (minX < boundsMinX) { float n = (boundsMinX - minX); x += n; n *= (srcWidth / go.width); srcX += n; srcWidth -= n; - } - else if (maxX > boundsMaxX) { + } else if (maxX > boundsMaxX) { float n = (maxX - boundsMaxX); srcWidth -= n * (srcWidth / go.width); } - if (minY < boundsMinY) { + if (minY < boundsMinY) { float n = (boundsMinY - minY); y += n; srcHeight -= n * (srcHeight / go.height); - } - else if (maxY > boundsMaxY) { + } else if (maxY > boundsMaxY) { float n = (maxY - boundsMaxY) * (srcHeight / go.height); - srcHeight -= n ; + srcHeight -= n; srcY += n; } float width = go.width * srcWidth / region.getRegionWidth(); float height = go.height * srcHeight / region.getRegionHeight(); - - spriteBatch.draw(region.getTexture(), - x, - y, - width, - height, - srcX, - srcY, - srcWidth, - srcHeight, - false, - false); + + spriteBatch.draw(region.getTexture(), x, y, width, height, srcX, srcY, srcWidth, srcHeight, false, false); } - - private void drawParticles() { - spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); + + private void drawParticles () { + spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); for (Particle particle : particleManager.getParticles()) { if (particle.active) { spriteBatch.setColor(particle.color); @@ -421,8 +402,8 @@ private void drawParticles() { } spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); } - - private void drawFlyups() { + + private void drawFlyups () { BitmapFont font = Assets.flyupFont; float scale = font.getScaleX(); font.setScale(1.0f / Assets.pixelDensity); @@ -435,24 +416,20 @@ private void drawFlyups() { spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); font.setScale(scale); } - - /** - * Updates the state of the on-screen controls. + + /** Updates the state of the on-screen controls. * - * @param delta time in seconds since the last render. - */ - public void updateControls(float delta) { + * @param delta time in seconds since the last render. */ + public void updateControls (float delta) { presenter.setController(0.0f, 0.0f); if (Gdx.input.justTouched()) { worldCam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); if (world.isPaused()) { presenter.resume(); - } - else if (touchPoint.y >= worldMaxY) { + } else if (touchPoint.y >= worldMaxY) { presenter.pause(); } - } - else if (Gdx.input.isTouched()) { + } else if (Gdx.input.isTouched()) { worldCam.unproject(dragPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0)); float dx = dragPoint.x - touchPoint.x; float dy = dragPoint.y - touchPoint.y; diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/BaseShot.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/BaseShot.java index 7c9f2ebea8d..2dc52008b1c 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/BaseShot.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/BaseShot.java @@ -19,15 +19,15 @@ public class BaseShot extends GameObject { private float dy; private float shotSpeed; - public BaseShot() { + public BaseShot () { super(); } - public void setShotSpeed(float shotSpeed) { - this.shotSpeed = shotSpeed; + public void setShotSpeed (float shotSpeed) { + this.shotSpeed = shotSpeed; } - public void fire(float x, float y, float dx, float dy) { + public void fire (float x, float y, float dx, float dy) { this.x = x; this.y = y; this.dx = dx; @@ -35,10 +35,10 @@ public void fire(float x, float y, float dx, float dy) { } @Override - public void update(float delta) { + public void update (float delta) { stateTime += delta; float n = shotSpeed * delta; x += dx * n; y += dy * n; } -} \ No newline at end of file +} diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Captain.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Captain.java index be6ff9c279f..d7517fb2425 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Captain.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Captain.java @@ -13,61 +13,58 @@ package com.badlydrawngames.veryangryrobots.mobiles; -import static com.badlogic.gdx.math.MathUtils.atan2; -import static com.badlogic.gdx.math.MathUtils.cos; -import static com.badlogic.gdx.math.MathUtils.sin; - import com.badlydrawngames.general.Config; import com.badlydrawngames.veryangryrobots.Assets; +import static com.badlogic.gdx.math.MathUtils.*; + public class Captain extends GameObject { - + public static final int LURKING = INACTIVE + 1; public static final int CHASING = LURKING + 1; - + private static final float SPEED = Config.asFloat("Captain.speed", 3.75f); private static final float BOUNCE_SIZE = Config.asFloat("Captain.bounceSize", 5.625f); private static final float BOUNCE_FREQUENCY = Config.asFloat("Captain.bounceFrequency", 10.0f); - + private float activateTime; private Player player; private float speed; private float t; - public Captain() { + public Captain () { width = Assets.captainWidth; height = Assets.captainHeight; geometry = Assets.captainGeometry; setState(INACTIVE); speed = SPEED; } - + @Override - public void update(float delta) { + public void update (float delta) { stateTime += delta; if (state == LURKING) { updateLurking(delta); - } - else if (state == CHASING) { + } else if (state == CHASING) { updateChasing(delta); } } - public void activateAfter(float interval) { + public void activateAfter (float interval) { activateTime = stateTime + interval; } - - public void setPlayer(Player player) { + + public void setPlayer (Player player) { this.player = player; } - - private void updateLurking(float delta) { + + private void updateLurking (float delta) { if (stateTime >= activateTime) { setState(Captain.CHASING); } } - private void updateChasing(float delta) { + private void updateChasing (float delta) { float dx = player.x - x; float dy = player.y - y; float angle = atan2(dy, dx); @@ -76,8 +73,7 @@ private void updateChasing(float delta) { y += sin(angle) * sd; if (sin(t) > 0) { y += BOUNCE_SIZE * delta; - } - else { + } else { y -= BOUNCE_SIZE * delta; } t += delta * BOUNCE_FREQUENCY; diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/GameObject.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/GameObject.java index cfb7e919a2b..a196fce8f97 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/GameObject.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/GameObject.java @@ -17,64 +17,57 @@ import com.badlydrawngames.general.Colliders; import com.badlydrawngames.general.CollisionGeometry; -/** - * All game objects are ultimately based on GameObject. Different behaviours are specified by overriding +/** All game objects are ultimately based on GameObject. Different behaviours are specified by overriding * {@link GameObject#update}. * - * @author Rod - * - */ + * @author Rod */ public class GameObject { /** The default state for any new game object. */ public static final int INACTIVE = -1; - + /** This game object's x coordinate in world space. */ public float x; - + /** This game object's y coordinate in world space. */ public float y; - + /** This game object's width in world units. */ public float width; - + /** This game object's height in world units. */ public float height; - + /** This game object's collision geometry (if it has any) in local coordinates. */ public CollisionGeometry geometry; - + /** This game object's current state. */ public int state; - + /** How long this game object has been in its current state (in seconds). */ public float stateTime; - + /** Will be true if this game object is in collision. */ public boolean inCollision; // Holds this game object's bounding rectangle in world space. private final Rectangle bounds; - - public GameObject() { + + public GameObject () { stateTime = 0.0f; inCollision = false; bounds = new Rectangle(); } - /** - * Assigns collision geometry to this GameObject. - * @param geometry the new collision geometry. - */ - public void setGeometry(CollisionGeometry geometry) { + /** Assigns collision geometry to this GameObject. + * @param geometry the new collision geometry. */ + public void setGeometry (CollisionGeometry geometry) { this.geometry = geometry; } - - /** - * Returns this GameObject's bounding rectangle. - * @return the bounding rectangle. - */ - public Rectangle bounds() { + + /** Returns this GameObject's bounding rectangle. + * @return the bounding rectangle. */ + public Rectangle bounds () { bounds.x = x; bounds.y = y; bounds.width = width; @@ -82,88 +75,71 @@ public Rectangle bounds() { return bounds; } - /** - * Switches this game object into a new state and resets {@link stateTime}. - * @param state the new state. - */ - public void setState(int state) { + /** Switches this game object into a new state and resets {@link stateTime}. + * @param state the new state. */ + public void setState (int state) { this.state = state; stateTime = 0.0f; } - - /** - * Returns true if this game object's bounds intersect with the given rectangle. + + /** Returns true if this game object's bounds intersect with the given rectangle. * * @param r the rectangle to intersect. - * @return true if the bounds intersect. - */ - public boolean boundsIntersect(Rectangle r) { + * @return true if the bounds intersect. */ + public boolean boundsIntersect (Rectangle r) { return Colliders.intersects(bounds(), r); } - /** - * Returns true if this game object's bounds intersect with the given game object. + /** Returns true if this game object's bounds intersect with the given game object. * * @param go the other game object. - * @return true if the bounds intersect. - */ - public boolean boundsIntersect(GameObject go) { + * @return true if the bounds intersect. */ + public boolean boundsIntersect (GameObject go) { return Colliders.intersects(bounds(), go.bounds()); } - - /** - * Returns true if this game object's collision geometry intersects with the given rectangle. + + /** Returns true if this game object's collision geometry intersects with the given rectangle. * * @param r the rectangle to intersect. - * @return true if the geometry intersects with the rectangle. - */ - public boolean geometryIntersects(Rectangle r) { + * @return true if the geometry intersects with the rectangle. */ + public boolean geometryIntersects (Rectangle r) { return geometry.intersects(r, x, y); } - - /** - * Returns true if this game object's collision geometry intersects with another game object's collision geometry. + + /** Returns true if this game object's collision geometry intersects with another game object's collision geometry. * * @param go the other game object. - * @return true if the geometries intersect. - */ - public boolean geometryIntersects(GameObject go) { + * @return true if the geometries intersect. */ + public boolean geometryIntersects (GameObject go) { return geometry.intersects(x, y, go.geometry, go.x, go.y); } - /** - * Returns true if this game object is in collision with a rectangle. It first does a simple box test against this - * game object's bounds, then, if that's true, tests its collision geometry against the rectangle. + /** Returns true if this game object is in collision with a rectangle. It first does a simple box test against this game + * object's bounds, then, if that's true, tests its collision geometry against the rectangle. * * @param r the rectangle to intersect. - * @return true if this game object intersects the rectangle. - */ - public boolean intersects(Rectangle r) { + * @return true if this game object intersects the rectangle. */ + public boolean intersects (Rectangle r) { return boundsIntersect(r) && (geometry == null || geometryIntersects(r)); } - - /** - * Returns true if this game object is in collision with another game object. It first does a bounds test, then, - * if that's true, tests its collision geometry against the other game object's collision geometry. - */ - public boolean intersects(GameObject go) { + + /** Returns true if this game object is in collision with another game object. It first does a bounds test, then, if that's + * true, tests its collision geometry against the other game object's collision geometry. */ + public boolean intersects (GameObject go) { if (!boundsIntersect(go)) { return false; } if (geometry == null) { return go.geometry == null || go.geometryIntersects(bounds()); - } - else if (go.geometry == null) { + } else if (go.geometry == null) { return geometryIntersects(go.bounds()); } return geometryIntersects(go); } - /** - * Updates this game object. Typically you would override this to create interesting behaviour. + /** Updates this game object. Typically you would override this to create interesting behaviour. * - * @param delta time in seconds since the last update. - */ - public void update(float delta) { + * @param delta time in seconds since the last update. */ + public void update (float delta) { } } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Player.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Player.java index 2f6ed1aa5a6..8289f0efb8c 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Player.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Player.java @@ -23,34 +23,31 @@ public class Player extends GameObject { public static final int WALKING_RIGHT = WALKING_LEFT + 1; public static final int FACING_LEFT = WALKING_RIGHT + 1; public static final int FACING_RIGHT = FACING_LEFT + 1; - + private static final float SPEED = Config.asFloat("Player.speed", 12.5f); - + private float dx; private float dy; - - public Player() { + + public Player () { width = Assets.playerWidth; height = Assets.playerHeight; geometry = Assets.playerGeometry; } @Override - public void update(float delta) { + public void update (float delta) { if (dx > 0.0f) { if (state != WALKING_RIGHT) { setState(WALKING_RIGHT); } - } - else if (dx < 0.0f) { + } else if (dx < 0.0f) { if (state != WALKING_LEFT) { setState(WALKING_LEFT); } - } - else if (state == WALKING_RIGHT) { + } else if (state == WALKING_RIGHT) { setState(FACING_RIGHT); - } - else if (state == WALKING_LEFT) { + } else if (state == WALKING_LEFT) { setState(FACING_LEFT); } stateTime += delta; @@ -59,7 +56,7 @@ else if (state == WALKING_LEFT) { y += dy * d; } - public void setController(float x, float y) { + public void setController (float x, float y) { dx = x; dy = y; } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/PlayerShot.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/PlayerShot.java index 774dbe8a42c..6aaf34a4aef 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/PlayerShot.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/PlayerShot.java @@ -1,13 +1,14 @@ + package com.badlydrawngames.veryangryrobots.mobiles; import com.badlydrawngames.general.Config; import com.badlydrawngames.veryangryrobots.Assets; public class PlayerShot extends BaseShot { - + private static final float SHOT_SPEED = Config.asFloat("PlayerShot.speed", 31.25f); - - public PlayerShot() { + + public PlayerShot () { width = Assets.playerShotWidth; height = Assets.playerShotHeight; setShotSpeed(SHOT_SPEED); diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Robot.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Robot.java index 1e25b03f54e..2feea475c24 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Robot.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/Robot.java @@ -13,12 +13,6 @@ package com.badlydrawngames.veryangryrobots.mobiles; -import static com.badlogic.gdx.math.MathUtils.random; -import static com.badlydrawngames.general.MathUtils.abs; -import static com.badlydrawngames.general.MathUtils.max; -import static com.badlydrawngames.general.MathUtils.min; -import static com.badlydrawngames.general.MathUtils.sgn; - import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; @@ -27,6 +21,9 @@ import com.badlydrawngames.veryangryrobots.Assets; import com.badlydrawngames.veryangryrobots.World.FireCommand; +import static com.badlogic.gdx.math.MathUtils.*; +import static com.badlydrawngames.general.MathUtils.*; + public class Robot extends GameObject { public static final int SCANNING = INACTIVE + 1; @@ -38,7 +35,7 @@ public class Robot extends GameObject { public static final int WALKING_UP = WALKING_DOWN + 1; private static final float WALKING_SPEED = Config.asFloat("Robot.speed", 1.25f); - + private GameObject player; private Array walls; private final float distance; @@ -51,8 +48,8 @@ public class Robot extends GameObject { private Vector2 lineEnd; private float respawnX; private float respawnY; - - public Robot() { + + public Robot () { width = Assets.robotWidth; height = Assets.robotHeight; distance = max(width, height); @@ -64,21 +61,21 @@ public Robot() { lineStart = new Vector2(); lineEnd = new Vector2(); } - - public void setPlayer(GameObject player) { + + public void setPlayer (GameObject player) { this.player = player; } - - public void setWalls(Array walls) { + + public void setWalls (Array walls) { this.walls = walls; } - - public void setFireCommand(FireCommand fireCommand) { + + public void setFireCommand (FireCommand fireCommand) { this.fireCommand = fireCommand; } @Override - public void update(float delta) { + public void update (float delta) { stateTime += delta; moveRobot(delta); if (fireCommand != null && canFire(delta) && canSeePlayer()) { @@ -87,13 +84,13 @@ public void update(float delta) { fireCommand.fire(this, firingDirection.x, firingDirection.y); } } - - private boolean canFire(float delta) { + + private boolean canFire (float delta) { // TODO: remove magic numbers, or possibly switch to expovariate randomness. return random(100) < 50 * delta; } - - private void moveRobot(float delta) { + + private void moveRobot (float delta) { float dx = (player.x + player.width / 2) - (x + width / 2); float dy = (player.y + player.height / 2) - (y + height / 2); dx = abs(dx) >= 2 ? sgn(dx) : 0.0f; @@ -103,48 +100,42 @@ private void moveRobot(float delta) { if (!wouldHitWall(dx, dy)) { ax = dx; ay = dy; - } - else if (dx != 0 && !wouldHitWall(dx, 0)) { + } else if (dx != 0 && !wouldHitWall(dx, 0)) { ax = dx; - } - else if (dy != 0 && !wouldHitWall(0, dy)) { + } else if (dy != 0 && !wouldHitWall(0, dy)) { ay = dy; } dx = ax * WALKING_SPEED; dy = ay * WALKING_SPEED; x += dx * delta; y += dy * delta; - + int newState = getMovementState(dx, dy); if (newState != state) { setState(newState); } } - private int getMovementState(float dx, float dy) { + private int getMovementState (float dx, float dy) { if (dx == 0.0f && dy == 0.0f) { return SCANNING; - } - else if (dx > 0) { + } else if (dx > 0) { return (dy == 0) ? WALKING_RIGHT : WALKING_RIGHT_DIAGONAL; - } - else if (dx < 0) { + } else if (dx < 0) { return (dy == 0) ? WALKING_LEFT : WALKING_LEFT_DIAGONAL; - } - else if (dy < 0) { + } else if (dy < 0) { return WALKING_DOWN; - } - else { + } else { return WALKING_UP; } } - - private boolean wouldHitWall(float dx, float dy) { + + private boolean wouldHitWall (float dx, float dy) { float x1 = x + width / 2; float y1 = y + height / 2; float x2 = x1 + dx * distance; float y2 = y1 + dy * distance; - + for (int i = 0; i < walls.size; i++) { Rectangle wall = walls.get(i); if (doesLineHitWall(wall, x1, y1, x2, y2)) { @@ -154,47 +145,45 @@ private boolean wouldHitWall(float dx, float dy) { return false; } - private boolean doesLineHitWall(Rectangle rect, float x1, float y1, float x2, float y2) { + private boolean doesLineHitWall (Rectangle rect, float x1, float y1, float x2, float y2) { // Does not intersect if minimum y coordinate is below the rectangle. float minY = min(y1, y2); if (minY >= rect.y + rect.height + fudge) return false; - + // Does not intersect if maximum y coordinate is above the rectangle. float maxY = max(y1, y2); if (maxY < rect.y - fudge) return false; - + // Does not intersect if minimum x coordinate is to the right of the rectangle. float minX = min(x1, x2); if (minX >= rect.x + rect.width + fudge) return false; - + // Does not intersect if maximum x coordinate is to the left of the rectangle. float maxX = max(x1, x2); if (maxX < rect.x - fudge) return false; - + // And that's good enough, because the robots need to be a bit stupid // when they're near the ends of walls. return true; } - - private boolean canSeePlayer() { + + private boolean canSeePlayer () { return hasLineOfSight(this, player); } - - private boolean hasLineOfSight(GameObject a, GameObject b) { - return hasLineOfSight(a.x + a.width / 2, a.y + a.height / 2, - b.x + b.width / 2, b.y + b.height / 2); + + private boolean hasLineOfSight (GameObject a, GameObject b) { + return hasLineOfSight(a.x + a.width / 2, a.y + a.height / 2, b.x + b.width / 2, b.y + b.height / 2); } - - private boolean hasLineOfSight(float x1, float y1, float x2, float y2) { + + private boolean hasLineOfSight (float x1, float y1, float x2, float y2) { robotPos.set(x1, y1); playerPos.set(x2, y2); for (int i = 0; i < walls.size; i++) { Rectangle wall = walls.get(i); - if (wall.width > wall.height) { + if (wall.width > wall.height) { lineStart.set(wall.x, wall.y + wall.height / 2); lineEnd.set(wall.x + wall.width, lineStart.y); - } - else { + } else { lineStart.set(wall.x + wall.width / 2, wall.y); lineEnd.set(lineStart.x, wall.y + wall.height); } @@ -205,12 +194,12 @@ private boolean hasLineOfSight(float x1, float y1, float x2, float y2) { return true; } - public void setRespawnPoint(float x, float y) { + public void setRespawnPoint (float x, float y) { respawnX = x; respawnY = y; } - - public void respawn() { + + public void respawn () { x = respawnX; y = respawnY; } diff --git a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/RobotShot.java b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/RobotShot.java index d16627757da..264369adb9c 100644 --- a/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/RobotShot.java +++ b/demos/very-angry-robots/very-angry-robots/src/com/badlydrawngames/veryangryrobots/mobiles/RobotShot.java @@ -17,23 +17,23 @@ import com.badlydrawngames.veryangryrobots.Assets; public class RobotShot extends BaseShot { - + private static final float DEFAULT_SHOT_SPEED = Config.asFloat("RobotShot.slowSpeed", 4.6875f); - + private GameObject owner; - - public RobotShot() { + + public RobotShot () { width = Assets.robotShotWidth; height = Assets.robotShotHeight; setShotSpeed(DEFAULT_SHOT_SPEED); } - - public void setOwner(GameObject owner) { + + public void setOwner (GameObject owner) { this.owner = owner; } - + @Override - public boolean intersects(GameObject other) { + public boolean intersects (GameObject other) { return (owner != other) && super.intersects(other); } } diff --git a/eclipse-formatter.xml b/eclipse-formatter.xml index bdd84267088..0c25604d4cc 100644 --- a/eclipse-formatter.xml +++ b/eclipse-formatter.xml @@ -1,6 +1,6 @@ - - + + @@ -10,7 +10,7 @@ - + @@ -35,7 +35,7 @@ - + @@ -81,6 +81,7 @@ + @@ -116,6 +117,7 @@ + @@ -127,15 +129,16 @@ - + + - + @@ -162,8 +165,8 @@ - + @@ -185,6 +188,7 @@ + @@ -196,6 +200,7 @@ + @@ -240,7 +245,6 @@ - @@ -266,14 +270,14 @@ - + - + diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AppletInitializer.java b/extensions/beans/src/com/badlogic/gdx/beans/AppletInitializer.java index f52a7407324..03fc2b9ff98 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AppletInitializer.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AppletInitializer.java @@ -23,7 +23,7 @@ public interface AppletInitializer { - public void initialize(Applet newAppletBean, BeanContext bCtxt); + public void initialize (Applet newAppletBean, BeanContext bCtxt); - public void activate(Applet newApplet); + public void activate (Applet newApplet); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/ArrayPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/ArrayPersistenceDelegate.java index e30bf1233f6..8d7469afbfb 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/ArrayPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/ArrayPersistenceDelegate.java @@ -17,106 +17,97 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.ArrayPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import java.lang.reflect.Array; class ArrayPersistenceDelegate extends PersistenceDelegate { - private static PersistenceDelegate pd = null; - - public static PersistenceDelegate getInstance() { - if (pd == null) { - pd = new ArrayPersistenceDelegate(); - } - return pd; - } - - @Override - protected Expression instantiate(Object oldInstance, Encoder out) { - assert oldInstance != null && oldInstance.getClass().isArray() : oldInstance; - - int length = Array.getLength(oldInstance); - Class componentType = oldInstance.getClass().getComponentType(); - - return new Expression(oldInstance, Array.class, "newInstance", //$NON-NLS-1$ - new Object[] { componentType, Integer.valueOf(length) }); - } - - @Override - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder out) { - - assert oldInstance != null && oldInstance.getClass().isArray() : oldInstance; - assert newInstance != null && newInstance.getClass().isArray() : newInstance; - - int length = Array.getLength(oldInstance); - - for (int i = 0; i < length; ++i) { - Object oldValue = Array.get(oldInstance, i); - Object newValue = Array.get(newInstance, i); - if (!deepEquals(oldValue, newValue)) { - Statement s = new Statement(oldInstance, "set", //$NON-NLS-1$ - new Object[] { Integer.valueOf(i), oldValue }); - out.writeStatement(s); - } - } - } - - private boolean deepEquals(Object oldInstance, Object newInstance) { - if (oldInstance == newInstance) { - return true; - } - if (null == oldInstance || null == newInstance) { - return false; - } - // oldInstnace != newInstance - if (oldInstance.getClass().isAssignableFrom(newInstance.getClass()) - && oldInstance.equals(newInstance)) { - return true; - } else if (oldInstance.getClass().isArray() - && newInstance.getClass().isArray()) { - int length1 = Array.getLength(oldInstance); - int length2 = Array.getLength(newInstance); - if (length1 != length2) { - return false; - } - for (int i = 0; i < length1; i++) { - Object oldValue = Array.get(oldInstance, i); - Object newValue = Array.get(newInstance, i); - if (!deepEquals(oldValue, newValue)) { - return false; - } - } - return true; - } else { - return false; - } - } - - @Override - protected boolean mutatesTo(Object oldInstance, Object newInstance) { - if(null == oldInstance || null == newInstance){ - return false; - } - - if(!oldInstance.getClass().isArray() || !newInstance.getClass().isArray()){ - return false; - } - - // both are array - int l1 = Array.getLength(oldInstance); - int l2 = Array.getLength(newInstance); - Class cType1 = oldInstance.getClass().getComponentType(); - Class cType2 = newInstance.getClass().getComponentType(); - if(l1 == l2 && cType1.equals(cType2)){ - return true; - } - - return false; - } + private static PersistenceDelegate pd = null; + + public static PersistenceDelegate getInstance () { + if (pd == null) { + pd = new ArrayPersistenceDelegate(); + } + return pd; + } + + @Override + protected Expression instantiate (Object oldInstance, Encoder out) { + assert oldInstance != null && oldInstance.getClass().isArray() : oldInstance; + + int length = Array.getLength(oldInstance); + Class componentType = oldInstance.getClass().getComponentType(); + + return new Expression(oldInstance, Array.class, "newInstance", //$NON-NLS-1$ + new Object[] {componentType, Integer.valueOf(length)}); + } + + @Override + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder out) { + + assert oldInstance != null && oldInstance.getClass().isArray() : oldInstance; + assert newInstance != null && newInstance.getClass().isArray() : newInstance; + + int length = Array.getLength(oldInstance); + + for (int i = 0; i < length; ++i) { + Object oldValue = Array.get(oldInstance, i); + Object newValue = Array.get(newInstance, i); + if (!deepEquals(oldValue, newValue)) { + Statement s = new Statement(oldInstance, "set", //$NON-NLS-1$ + new Object[] {Integer.valueOf(i), oldValue}); + out.writeStatement(s); + } + } + } + + private boolean deepEquals (Object oldInstance, Object newInstance) { + if (oldInstance == newInstance) { + return true; + } + if (null == oldInstance || null == newInstance) { + return false; + } + // oldInstnace != newInstance + if (oldInstance.getClass().isAssignableFrom(newInstance.getClass()) && oldInstance.equals(newInstance)) { + return true; + } else if (oldInstance.getClass().isArray() && newInstance.getClass().isArray()) { + int length1 = Array.getLength(oldInstance); + int length2 = Array.getLength(newInstance); + if (length1 != length2) { + return false; + } + for (int i = 0; i < length1; i++) { + Object oldValue = Array.get(oldInstance, i); + Object newValue = Array.get(newInstance, i); + if (!deepEquals(oldValue, newValue)) { + return false; + } + } + return true; + } else { + return false; + } + } + + @Override + protected boolean mutatesTo (Object oldInstance, Object newInstance) { + if (null == oldInstance || null == newInstance) { + return false; + } + + if (!oldInstance.getClass().isArray() || !newInstance.getClass().isArray()) { + return false; + } + + // both are array + int l1 = Array.getLength(oldInstance); + int l2 = Array.getLength(newInstance); + Class cType1 = oldInstance.getClass().getComponentType(); + Class cType2 = newInstance.getClass().getComponentType(); + if (l1 == l2 && cType1.equals(cType2)) { + return true; + } + + return false; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtChoicePersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtChoicePersistenceDelegate.java index 12db8da73e7..9692d58b290 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtChoicePersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtChoicePersistenceDelegate.java @@ -19,27 +19,20 @@ import java.awt.Choice; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - class AwtChoicePersistenceDelegate extends DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { super.initialize(type, oldInstance, newInstance, enc); if (type != oldInstance.getClass()) { return; } - Choice choice = (Choice) oldInstance; + Choice choice = (Choice)oldInstance; int count = choice.getItemCount(); Expression getterExp = null; for (int i = 0; i < count; i++) { - getterExp = new Expression(choice, "getItem", new Object[] { i }); + getterExp = new Expression(choice, "getItem", new Object[] {i}); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); @@ -50,29 +43,24 @@ protected void initialize(Class type, Object oldInstance, // Get the current property value in the new environment Object newVal = null; try { - newVal = new Expression(newInstance, "getItem", - new Object[] { i }).getValue(); + newVal = new Expression(newInstance, "getItem", new Object[] {i}).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* - * Make the target value and current property value equivalent - * in the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { null }); + Statement setterStm = new Statement(oldInstance, "add", new Object[] {null}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { oldVal }); + Statement setterStm = new Statement(oldInstance, "add", new Object[] {oldVal}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtColorPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtColorPersistenceDelegate.java index eab905fdfa1..126420709c4 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtColorPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtColorPersistenceDelegate.java @@ -19,18 +19,13 @@ import java.awt.Color; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtColorPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Color color = (Color) oldInstance; - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, new Object[] { color.getRed(), - color.getGreen(), color.getBlue(), color.getAlpha() }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Color color = (Color)oldInstance; + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, new Object[] {color.getRed(), color.getGreen(), + color.getBlue(), color.getAlpha()}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtComponentPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtComponentPersistenceDelegate.java index 1dc7f463f91..d0fde5016e7 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtComponentPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtComponentPersistenceDelegate.java @@ -17,18 +17,11 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - class AwtComponentPersistenceDelegate extends DefaultPersistenceDelegate { - @Override + @Override @SuppressWarnings("nls") - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { // Call the initialization of the super type super.initialize(type, oldInstance, newInstance, enc); @@ -50,11 +43,9 @@ protected void initialize(Class type, Object oldInstance, } @SuppressWarnings("nls") - static void writeProperty(Object oldInstance, Object newInstance, - Encoder enc, String property) { + static void writeProperty (Object oldInstance, Object newInstance, Encoder enc, String property) { StringBuilder builder = new StringBuilder(); - Expression getterExp = new Expression(oldInstance, builder - .append("get").append(property).toString(), null); + Expression getterExp = new Expression(oldInstance, builder.append("get").append(property).toString(), null); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); @@ -64,29 +55,24 @@ static void writeProperty(Object oldInstance, Object newInstance, Object targetVal = enc.get(oldVal); // Get the current property value in the new environment builder.delete(0, builder.capacity()); - Object newVal = new Expression(newInstance, builder.append("get") - .append(property).toString(), null).getValue(); + Object newVal = new Expression(newInstance, builder.append("get").append(property).toString(), null).getValue(); /* - * Make the target value and current property value equivalent in - * the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null builder.delete(0, builder.capacity()); - Statement setterStm = new Statement(oldInstance, builder - .append("set").append(property).toString(), - new Object[] { null }); + Statement setterStm = new Statement(oldInstance, builder.append("set").append(property).toString(), + new Object[] {null}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal - .getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { builder.delete(0, builder.capacity()); - Statement setterStm = new Statement(oldInstance, builder - .append("set").append(property).toString(), - new Object[] { oldVal }); + Statement setterStm = new Statement(oldInstance, builder.append("set").append(property).toString(), + new Object[] {oldVal}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtContainerPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtContainerPersistenceDelegate.java index 383a19978b1..254fa6ec07f 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtContainerPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtContainerPersistenceDelegate.java @@ -19,25 +19,18 @@ import java.awt.Container; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - class AwtContainerPersistenceDelegate extends AwtComponentPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { // Call the initialization of the super type super.initialize(type, oldInstance, newInstance, enc); - Container container = (Container) oldInstance; + Container container = (Container)oldInstance; int count = container.getComponentCount(); Expression getterExp = null; for (int i = 0; i < count; i++) { - getterExp = new Expression(container.getComponent(i), container, - "getComponent", new Object[] { i }); + getterExp = new Expression(container.getComponent(i), container, "getComponent", new Object[] {i}); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); @@ -48,30 +41,25 @@ protected void initialize(Class type, Object oldInstance, // Get the current property value in the new environment Object newVal = null; try { - newVal = new Expression(((Container) newInstance) - .getComponent(i), newInstance, "getComponent", - new Object[] { i }).getValue(); + newVal = new Expression(((Container)newInstance).getComponent(i), newInstance, "getComponent", new Object[] {i}) + .getValue(); } catch (ArrayIndexOutOfBoundsException ex) { // Current Container does not have any component, newVal set // to null } /* - * Make the target value and current property value equivalent - * in the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { null }); + Statement setterStm = new Statement(oldInstance, "add", new Object[] {null}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { oldVal }); + Statement setterStm = new Statement(oldInstance, "add", new Object[] {oldVal}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtCursorPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtCursorPersistenceDelegate.java index ee9805f62c1..86173405da9 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtCursorPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtCursorPersistenceDelegate.java @@ -19,17 +19,12 @@ import java.awt.Cursor; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtCursorPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Cursor cursor = (Cursor) oldInstance; - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, new Object[] { cursor.getType() }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Cursor cursor = (Cursor)oldInstance; + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, new Object[] {cursor.getType()}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtDimensionPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtDimensionPersistenceDelegate.java index 478095cee58..0c64a6f699a 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtDimensionPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtDimensionPersistenceDelegate.java @@ -19,17 +19,12 @@ import java.awt.Dimension; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtDimensionPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Dimension dimension = (Dimension) oldInstance; - return new Expression(dimension, dimension.getClass(), BeansUtils.NEW, - new Object[] { dimension.width, dimension.height }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Dimension dimension = (Dimension)oldInstance; + return new Expression(dimension, dimension.getClass(), BeansUtils.NEW, new Object[] {dimension.width, dimension.height}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtFontPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtFontPersistenceDelegate.java index 221e18ccb6c..db294ff5963 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtFontPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtFontPersistenceDelegate.java @@ -19,18 +19,13 @@ import java.awt.Font; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtFontPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Font font = (Font) oldInstance; - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, new Object[] { font.getFontName(), - font.getStyle(), font.getSize() }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Font font = (Font)oldInstance; + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, new Object[] {font.getFontName(), + font.getStyle(), font.getSize()}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtFontTextAttributePersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtFontTextAttributePersistenceDelegate.java index c66a7cd2d68..b4d1d287a60 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtFontTextAttributePersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtFontTextAttributePersistenceDelegate.java @@ -19,11 +19,11 @@ import java.awt.font.TextAttribute; -class AwtFontTextAttributePersistenceDelegate extends - StaticFieldPersistenceDelegate { - public AwtFontTextAttributePersistenceDelegate() { +class AwtFontTextAttributePersistenceDelegate extends StaticFieldPersistenceDelegate { + public AwtFontTextAttributePersistenceDelegate () { super(); } + static { init(TextAttribute.class); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtInsetsPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtInsetsPersistenceDelegate.java index 865d66c369c..628666e8e7f 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtInsetsPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtInsetsPersistenceDelegate.java @@ -19,18 +19,13 @@ import java.awt.Insets; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtInsetsPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Insets inset = (Insets) oldInstance; - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, new Object[] { inset.top, inset.left, - inset.bottom, inset.right, }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Insets inset = (Insets)oldInstance; + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, new Object[] {inset.top, inset.left, + inset.bottom, inset.right,}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtListPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtListPersistenceDelegate.java index 8c3e0c8a2b5..5ed0b433f2d 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtListPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtListPersistenceDelegate.java @@ -19,28 +19,20 @@ import java.awt.List; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - class AwtListPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { super.initialize(type, oldInstance, newInstance, enc); - List list = (List) oldInstance; - Statement setterStm = new Statement(oldInstance, "setSize", - new Object[] { list.getSize()}); + List list = (List)oldInstance; + Statement setterStm = new Statement(oldInstance, "setSize", new Object[] {list.getSize()}); enc.writeStatement(setterStm); - + int count = list.getItemCount(); Expression getterExp = null; for (int i = 0; i < count; i++) { - getterExp = new Expression(list, "getItem", new Object[] { i }); + getterExp = new Expression(list, "getItem", new Object[] {i}); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); @@ -51,29 +43,24 @@ protected void initialize(Class type, Object oldInstance, // Get the current property value in the new environment Object newVal = null; try { - newVal = new Expression(newInstance, "getItem", - new Object[] { i }).getValue(); + newVal = new Expression(newInstance, "getItem", new Object[] {i}).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* - * Make the target value and current property value equivalent - * in the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null - setterStm = new Statement(oldInstance, "add", - new Object[] { null }); + setterStm = new Statement(oldInstance, "add", new Object[] {null}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - setterStm = new Statement(oldInstance, "add", - new Object[] { oldVal }); + setterStm = new Statement(oldInstance, "add", new Object[] {oldVal}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuBarPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuBarPersistenceDelegate.java index ba7f405d94f..8d68e724f67 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuBarPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuBarPersistenceDelegate.java @@ -20,23 +20,16 @@ import java.awt.Menu; import java.awt.MenuBar; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - class AwtMenuBarPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { super.initialize(type, oldInstance, newInstance, enc); if (type != oldInstance.getClass()) { - return; - } - - MenuBar bar = (MenuBar) oldInstance; + return; + } + + MenuBar bar = (MenuBar)oldInstance; int count = bar.getMenuCount(); Expression getterExp = null; for (int i = 0; i < count; i++) { @@ -51,31 +44,26 @@ protected void initialize(Class type, Object oldInstance, // Get the current property value in the new environment Object newVal = null; try { - newVal = new Expression(((MenuBar) newInstance).getMenu(i), - "getLabel", null).getValue(); + newVal = new Expression(((MenuBar)newInstance).getMenu(i), "getLabel", null).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* - * Make the target value and current property value equivalent - * in the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null - Statement setterStm = new Statement(oldInstance, "insert", - new Object[] { null, i }); + Statement setterStm = new Statement(oldInstance, "insert", new Object[] {null, i}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - Menu menu = new Menu((String) oldVal); + Menu menu = new Menu((String)oldVal); menu.setName(bar.getMenu(i).getName()); - Statement setterStm = new Statement(oldInstance, - "add", new Object[] { menu }); + Statement setterStm = new Statement(oldInstance, "add", new Object[] {menu}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuPersistenceDelegate.java index cc9878c72e6..b2558996ece 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuPersistenceDelegate.java @@ -20,23 +20,16 @@ import java.awt.Menu; import java.awt.MenuItem; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - class AwtMenuPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { super.initialize(type, oldInstance, newInstance, enc); if (type != oldInstance.getClass()) { - return; - } - - Menu menu = (Menu) oldInstance; + return; + } + + Menu menu = (Menu)oldInstance; int count = menu.getItemCount(); Expression getterExp = null; for (int i = 0; i < count; i++) { @@ -51,31 +44,26 @@ protected void initialize(Class type, Object oldInstance, // Get the current property value in the new environment Object newVal = null; try { - newVal = new Expression(((Menu) newInstance).getItem(i), - "getLabel", null).getValue(); + newVal = new Expression(((Menu)newInstance).getItem(i), "getLabel", null).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* - * Make the target value and current property value equivalent - * in the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null - Statement setterStm = new Statement(oldInstance, "insert", - new Object[] { null, i }); + Statement setterStm = new Statement(oldInstance, "insert", new Object[] {null, i}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - MenuItem menuItem = new MenuItem((String) oldVal); + MenuItem menuItem = new MenuItem((String)oldVal); menuItem.setName(menu.getItem(i).getName()); - Statement setterStm = new Statement(oldInstance, - "add", new Object[] { menuItem }); + Statement setterStm = new Statement(oldInstance, "add", new Object[] {menuItem}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuShortcutPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuShortcutPersistenceDelegate.java index 13bdead9e09..ed89e41a60c 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuShortcutPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtMenuShortcutPersistenceDelegate.java @@ -19,19 +19,14 @@ import java.awt.MenuShortcut; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - import org.apache.harmony.beans.BeansUtils; class AwtMenuShortcutPersistenceDelegate extends PersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - MenuShortcut shortcut = (MenuShortcut) oldInstance; - int keyCode = shortcut.getKey(); - boolean useShiftModifier = shortcut.usesShiftModifier(); - return new Expression(shortcut, shortcut.getClass(), BeansUtils.NEW, - new Object[] { keyCode, useShiftModifier }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + MenuShortcut shortcut = (MenuShortcut)oldInstance; + int keyCode = shortcut.getKey(); + boolean useShiftModifier = shortcut.usesShiftModifier(); + return new Expression(shortcut, shortcut.getClass(), BeansUtils.NEW, new Object[] {keyCode, useShiftModifier}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtPointPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtPointPersistenceDelegate.java index 1d69246305e..a89bcccf042 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtPointPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtPointPersistenceDelegate.java @@ -19,17 +19,12 @@ import java.awt.Point; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtPointPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Point point = (Point) oldInstance; - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, new Object[] { point.x, point.y }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Point point = (Point)oldInstance; + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, new Object[] {point.x, point.y}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtRectanglePersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtRectanglePersistenceDelegate.java index 94b4dbd95bd..21434fc8fa4 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtRectanglePersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtRectanglePersistenceDelegate.java @@ -19,29 +19,23 @@ import java.awt.Rectangle; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtRectanglePersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected boolean mutatesTo(Object o1, Object o2) { - return o1.equals(o2); - } - - @Override - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - return; - } - - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Rectangle rect = (Rectangle) oldInstance; - return new Expression(rect, rect.getClass(), BeansUtils.NEW, - new Object[] { rect.x, rect.y, rect.width, rect.height }); - } + @Override + protected boolean mutatesTo (Object o1, Object o2) { + return o1.equals(o2); + } + + @Override + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + return; + } + + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Rectangle rect = (Rectangle)oldInstance; + return new Expression(rect, rect.getClass(), BeansUtils.NEW, new Object[] {rect.x, rect.y, rect.width, rect.height}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtScrollPanePersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtScrollPanePersistenceDelegate.java index c2224c990aa..fe41651430d 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtScrollPanePersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtScrollPanePersistenceDelegate.java @@ -14,22 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.badlogic.gdx.beans; import java.awt.ScrollPane; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import org.apache.harmony.beans.BeansUtils; class AwtScrollPanePersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, - new Object[] { ((ScrollPane) oldInstance) - .getScrollbarDisplayPolicy() }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, + new Object[] {((ScrollPane)oldInstance).getScrollbarDisplayPolicy()}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/AwtSystemColorPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/AwtSystemColorPersistenceDelegate.java index 1349a9db9b3..fee9321f4e5 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/AwtSystemColorPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/AwtSystemColorPersistenceDelegate.java @@ -19,11 +19,11 @@ import java.awt.SystemColor; -class AwtSystemColorPersistenceDelegate extends - StaticFieldPersistenceDelegate { - public AwtSystemColorPersistenceDelegate() { +class AwtSystemColorPersistenceDelegate extends StaticFieldPersistenceDelegate { + public AwtSystemColorPersistenceDelegate () { super(); } + static { init(SystemColor.class); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/BeanDescriptor.java b/extensions/beans/src/com/badlogic/gdx/beans/BeanDescriptor.java index 07352f2a5c7..5118873960d 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/BeanDescriptor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/BeanDescriptor.java @@ -17,90 +17,70 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.FeatureDescriptor; - -/** - * Describes a bean's global information. - */ +/** Describes a bean's global information. */ public class BeanDescriptor extends FeatureDescriptor { - private Class beanClass; + private Class beanClass; - private Class customizerClass; + private Class customizerClass; - /** - *

    - * Constructs an instance with the bean's {@link Class} and a customizer - * {@link Class}. The descriptor's {@link #getName()} is set as the - * unqualified name of the beanClass. - *

    - * - * @param beanClass - * The bean's Class. - * @param customizerClass - * The bean's customizer Class. - */ - public BeanDescriptor(Class beanClass, Class customizerClass) { - if (beanClass == null) { - throw new NullPointerException(); - } - setName(getShortClassName(beanClass)); - this.beanClass = beanClass; - this.customizerClass = customizerClass; - } + /**

    + * Constructs an instance with the bean's {@link Class} and a customizer {@link Class}. The descriptor's {@link #getName()} is + * set as the unqualified name of the beanClass. + *

    + * + * @param beanClass The bean's Class. + * @param customizerClass The bean's customizer Class. */ + public BeanDescriptor (Class beanClass, Class customizerClass) { + if (beanClass == null) { + throw new NullPointerException(); + } + setName(getShortClassName(beanClass)); + this.beanClass = beanClass; + this.customizerClass = customizerClass; + } - /** - *

    - * Constructs an instance with the bean's {@link Class}. The descriptor's - * {@link #getName()} is set as the unqualified name of the - * beanClass. - *

    - * - * @param beanClass - * The bean's Class. - */ - public BeanDescriptor(Class beanClass) { - this(beanClass, null); - } + /**

    + * Constructs an instance with the bean's {@link Class}. The descriptor's {@link #getName()} is set as the unqualified name of + * the beanClass. + *

    + * + * @param beanClass The bean's Class. */ + public BeanDescriptor (Class beanClass) { + this(beanClass, null); + } - /** - *

    - * Gets the bean's customizer {@link Class}/ - *

    - * - * @return A {@link Class} instance or null. - */ - public Class getCustomizerClass() { - return customizerClass; - } + /**

    + * Gets the bean's customizer {@link Class}/ + *

    + * + * @return A {@link Class} instance or null. */ + public Class getCustomizerClass () { + return customizerClass; + } - /** - *

    - * Gets the bean's {@link Class}. - *

    - * - * @return A {@link Class} instance. - */ - public Class getBeanClass() { - return beanClass; - } + /**

    + * Gets the bean's {@link Class}. + *

    + * + * @return A {@link Class} instance. */ + public Class getBeanClass () { + return beanClass; + } - /** - *

    - * Utility method for getting the unqualified name of a {@link Class}. - *

    - * - * @param leguminaClass - * The Class to get the name from. - * @return A String instance or null. - */ - private String getShortClassName(Class leguminaClass) { - if(leguminaClass == null) { - return null; - } - String beanClassName = leguminaClass.getName(); - int lastIndex = beanClassName.lastIndexOf("."); //$NON-NLS-1$ - return (lastIndex == -1) ? beanClassName : beanClassName.substring(lastIndex + 1); - } + /**

    + * Utility method for getting the unqualified name of a {@link Class}. + *

    + * + * @param leguminaClass The Class to get the name from. + * @return A String instance or null. */ + private String getShortClassName (Class leguminaClass) { + if (leguminaClass == null) { + return null; + } + String beanClassName = leguminaClass.getName(); + int lastIndex = beanClassName.lastIndexOf("."); //$NON-NLS-1$ + return (lastIndex == -1) ? beanClassName : beanClassName.substring(lastIndex + 1); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/BeanInfo.java b/extensions/beans/src/com/badlogic/gdx/beans/BeanInfo.java index 897f965029c..3cc7fb1d71f 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/BeanInfo.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/BeanInfo.java @@ -21,27 +21,27 @@ public interface BeanInfo { - public static final int ICON_COLOR_16x16 = 1; + public static final int ICON_COLOR_16x16 = 1; - public static final int ICON_COLOR_32x32 = 2; + public static final int ICON_COLOR_32x32 = 2; - public static final int ICON_MONO_16x16 = 3; + public static final int ICON_MONO_16x16 = 3; - public static final int ICON_MONO_32x32 = 4; + public static final int ICON_MONO_32x32 = 4; - public PropertyDescriptor[] getPropertyDescriptors(); + public PropertyDescriptor[] getPropertyDescriptors (); - public MethodDescriptor[] getMethodDescriptors(); + public MethodDescriptor[] getMethodDescriptors (); - public EventSetDescriptor[] getEventSetDescriptors(); + public EventSetDescriptor[] getEventSetDescriptors (); - public BeanInfo[] getAdditionalBeanInfo(); + public BeanInfo[] getAdditionalBeanInfo (); - public BeanDescriptor getBeanDescriptor(); + public BeanDescriptor getBeanDescriptor (); - public Image getIcon(int iconKind); + public Image getIcon (int iconKind); - public int getDefaultPropertyIndex(); + public int getDefaultPropertyIndex (); - public int getDefaultEventIndex(); + public int getDefaultEventIndex (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/Beans.java b/extensions/beans/src/com/badlogic/gdx/beans/Beans.java index 0b99e06f266..53d3b175da5 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/Beans.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/Beans.java @@ -37,430 +37,351 @@ import com.badlogic.gdx.beans.beancontext.BeanContext; -/** - * This class Beans provides some methods for manipulting bean - * controls. - * - */ +/** This class Beans provides some methods for manipulting bean controls. */ public class Beans { - private static boolean designTime = false; - - private static boolean guiAvailable = true; - - /** - * Constructs a Beans instance. - */ - public Beans() { - // expected - } - - @SuppressWarnings("unchecked") - private static Object internalInstantiate(ClassLoader cls, String beanName, - BeanContext context, Object initializer) throws IOException, - ClassNotFoundException { - // First try to load it from a serialization file. - String beanResourceName = getBeanResourceName(beanName); - InputStream is = (cls == null) ? ClassLoader - .getSystemResourceAsStream(beanResourceName) : cls - .getResourceAsStream(beanResourceName); - - IOException serializationException = null; - Object result = null; - if (is != null) { - try { - ObjectInputStream ois = (cls == null) ? new ObjectInputStream( - is) : new CustomizedObjectInputStream(is, cls); - result = ois.readObject(); - } catch (IOException e) { - // Not loadable - remember this as we may throw it later. - serializationException = e; - } - } - - // If it didn't work, try to instantiate it from the given classloader - boolean deserialized = true; - ClassLoader classLoader = cls == null ? ClassLoader - .getSystemClassLoader() : cls; - if (result == null) { - deserialized = false; - try { - result = Class.forName(beanName, true, classLoader) - .newInstance(); - } catch (Exception e) { - if (serializationException != null) { - throw serializationException; - } - throw new ClassNotFoundException(e.getClass() + ": " //$NON-NLS-1$ - + e.getMessage()); - } - } - - if (result != null) { - // Applet specific initialization - boolean isApplet = false; - try { - isApplet = result instanceof Applet; - } catch (Throwable t) { - // Ignored - leave isApplet as false. - } - - if (isApplet) { - appletLoaded((Applet) result, classLoader, beanName, context, - (AppletInitializer) initializer, deserialized); - } - if (null != context) { - context.add(result); - } - } - return result; - } - - /** - * Obtains an instance of a JavaBean specified the bean name using the - * specified class loader. - *

    - * If the specified class loader is null, the system class loader is used. - *

    - * - * @param loader - * the specified class loader. It can be null. - * @param name - * the name of the JavaBean - * @return an isntance of the bean. - * @throws IOException - * @throws ClassNotFoundException - */ - public static Object instantiate(ClassLoader loader, String name) - throws IOException, ClassNotFoundException { - return internalInstantiate(loader, name, null, null); - } - - /** - * Obtains an instance of a JavaBean specified the bean name using the - * specified class loader, and adds the instance into the specified bean - * context. - * - *

    - * If the specified class loader is null, the system class loader is used. - *

    - * - * @param cls - * the specified class loader. It can be null. - * @param beanName - * the name of the JavaBean - * @param beanContext - * the beancontext in which the bean instance will be added. - * @return an instance of the specified JavaBean. - * @throws IOException - * @throws ClassNotFoundException - */ - public static Object instantiate(ClassLoader cls, String beanName, - BeanContext beanContext) throws IOException, ClassNotFoundException { + private static boolean designTime = false; + + private static boolean guiAvailable = true; + + /** Constructs a Beans instance. */ + public Beans () { + // expected + } + + @SuppressWarnings("unchecked") + private static Object internalInstantiate (ClassLoader cls, String beanName, BeanContext context, Object initializer) + throws IOException, ClassNotFoundException { + // First try to load it from a serialization file. + String beanResourceName = getBeanResourceName(beanName); + InputStream is = (cls == null) ? ClassLoader.getSystemResourceAsStream(beanResourceName) : cls + .getResourceAsStream(beanResourceName); + + IOException serializationException = null; + Object result = null; + if (is != null) { + try { + ObjectInputStream ois = (cls == null) ? new ObjectInputStream(is) : new CustomizedObjectInputStream(is, cls); + result = ois.readObject(); + } catch (IOException e) { + // Not loadable - remember this as we may throw it later. + serializationException = e; + } + } + + // If it didn't work, try to instantiate it from the given classloader + boolean deserialized = true; + ClassLoader classLoader = cls == null ? ClassLoader.getSystemClassLoader() : cls; + if (result == null) { + deserialized = false; + try { + result = Class.forName(beanName, true, classLoader).newInstance(); + } catch (Exception e) { + if (serializationException != null) { + throw serializationException; + } + throw new ClassNotFoundException(e.getClass() + ": " //$NON-NLS-1$ + + e.getMessage()); + } + } + + if (result != null) { + // Applet specific initialization + boolean isApplet = false; + try { + isApplet = result instanceof Applet; + } catch (Throwable t) { + // Ignored - leave isApplet as false. + } + + if (isApplet) { + appletLoaded((Applet)result, classLoader, beanName, context, (AppletInitializer)initializer, deserialized); + } + if (null != context) { + context.add(result); + } + } + return result; + } + + /** Obtains an instance of a JavaBean specified the bean name using the specified class loader. + *

    + * If the specified class loader is null, the system class loader is used. + *

    + * + * @param loader the specified class loader. It can be null. + * @param name the name of the JavaBean + * @return an isntance of the bean. + * @throws IOException + * @throws ClassNotFoundException */ + public static Object instantiate (ClassLoader loader, String name) throws IOException, ClassNotFoundException { + return internalInstantiate(loader, name, null, null); + } + + /** Obtains an instance of a JavaBean specified the bean name using the specified class loader, and adds the instance into the + * specified bean context. + * + *

    + * If the specified class loader is null, the system class loader is used. + *

    + * + * @param cls the specified class loader. It can be null. + * @param beanName the name of the JavaBean + * @param beanContext the beancontext in which the bean instance will be added. + * @return an instance of the specified JavaBean. + * @throws IOException + * @throws ClassNotFoundException */ + public static Object instantiate (ClassLoader cls, String beanName, BeanContext beanContext) throws IOException, + ClassNotFoundException { return internalInstantiate(cls, beanName, beanContext, null); } - /** - * Obtains an instance of a JavaBean specified by the bean name using the - * specified class loader, and adds the instance into the specified bean - * context. - *

    - * The parameter name must be a qualified name relative to the specified - * class loader. For example, "java.awt.Button" and "x.y.z". - *

    - *

    - * If the specified class loader is null, the system class loader is used. - *

    - *

    - * Firstly, The class Beans regards the bean name as a - * serialized object name. The class Beans convert bean name - * into pathname, append a suffix ".ser" to the pathname. then try to load - * the resource using the specified class loader. If Beans - * fails to load the resource, Beans will regard the - * name as a class name and construct a new instance of the - * bean class. - *

    - *

    - * For example, if the name is specified as "x.y.z", The class - * Beans will try to load the serialized object from the - * resource "x/y/z.ser"; If Beans fails to load the resource - * "x/y/z.ser", it will create a new instance of "x.y.z". - *

    - *

    - * If the bean is an instance of java.applet.Applet, Beans - * will do some special initialization for this applet bean. First, - * Beans will set the default AppletStub and AppletContext - * for the applet bean (If the specified AppletInitializer is - * not null, Beans will call the - * AppletInitializer.initialize to set the default AppletStub - * and AppletContext for the applet bean). Second, Beans will - * call the init method of the applet. (If the applet bean is - * loaded as a serialized object, the init method will not be - * called.) - *

    - * - * @param cls - * the specified class loader. It can be null. - * @param beanName - * the name of the JavaBean - * @param context - * the beancontext in which the bean instance will be added. - * @param initializer - * the AppletInitializer for applet bean instance. - * @return Obtains an instance of the JavaBean. - * @throws IOException - * @throws ClassNotFoundException - */ - public static Object instantiate(ClassLoader cls, String beanName, - BeanContext context, AppletInitializer initializer) - throws IOException, ClassNotFoundException { + /** Obtains an instance of a JavaBean specified by the bean name using the specified class loader, and adds the instance into + * the specified bean context. + *

    + * The parameter name must be a qualified name relative to the specified class loader. For example, "java.awt.Button" and + * "x.y.z". + *

    + *

    + * If the specified class loader is null, the system class loader is used. + *

    + *

    + * Firstly, The class Beans regards the bean name as a serialized object name. The class Beans + * convert bean name into pathname, append a suffix ".ser" to the pathname. then try to load the resource using the specified + * class loader. If Beans fails to load the resource, Beans will regard the name as a + * class name and construct a new instance of the bean class. + *

    + *

    + * For example, if the name is specified as "x.y.z", The class Beans will try to load the serialized object from + * the resource "x/y/z.ser"; If Beans fails to load the resource "x/y/z.ser", it will create a new instance of + * "x.y.z". + *

    + *

    + * If the bean is an instance of java.applet.Applet, Beans will do some special initialization for this applet + * bean. First, Beans will set the default AppletStub and AppletContext for the applet bean (If the specified + * AppletInitializer is not null, Beans will call the AppletInitializer.initialize to + * set the default AppletStub and AppletContext for the applet bean). Second, Beans will call the + * init method of the applet. (If the applet bean is loaded as a serialized object, the init method + * will not be called.) + *

    + * + * @param cls the specified class loader. It can be null. + * @param beanName the name of the JavaBean + * @param context the beancontext in which the bean instance will be added. + * @param initializer the AppletInitializer for applet bean instance. + * @return Obtains an instance of the JavaBean. + * @throws IOException + * @throws ClassNotFoundException */ + public static Object instantiate (ClassLoader cls, String beanName, BeanContext context, AppletInitializer initializer) + throws IOException, ClassNotFoundException { return internalInstantiate(cls, beanName, context, initializer); } - /** - * Obtain an alternative type view of the given bean. The view type is - * specified by the parameter type. - *

    - * If the type view cannot be obtained, the original bean object is - * returned. - *

    - * - * @param bean - * the original bean object. - * @param targetType - * the specified view type. - * @return a type view of the given bean. - */ - public static Object getInstanceOf(Object bean, Class targetType) { - return bean; - } - - /** - * Determine if the the specified bean object can be viewed as the specified - * type. - * - * @param bean - * the specified bean object. - * @param targetType - * the specifed view type. - * @return true if the specified bean object can be viewed as the specified - * type; otherwise, return false; - */ - public static boolean isInstanceOf(Object bean, Class targetType) { - if (bean == null) { - throw new NullPointerException(Messages.getString("beans.1D")); //$NON-NLS-1$ - } - - return targetType == null ? false : targetType.isInstance(bean); - } - - /** - * Set whether or not a GUI is available in the bean's current environment. - * - * @param isGuiAvailable - * should be true to signify that a GUI is - * available, false otherwise. - * @throws SecurityException - * if the caller does not have the required permission to access - * or modify system properties. - */ - public static synchronized void setGuiAvailable(boolean isGuiAvailable) - throws SecurityException { - checkPropertiesAccess(); - guiAvailable = isGuiAvailable; - } - - /** - * Used to indicate whether of not it's in an application construction - * environment. - * - * @param isDesignTime - * true to indicate that it's in application construction - * environment. - * @throws SecurityException - */ - public static void setDesignTime(boolean isDesignTime) - throws SecurityException { - checkPropertiesAccess(); - synchronized(Beans.class){ - designTime = isDesignTime; - } - } - - /** - * Returns a boolean indication of whether or not a GUI is available for - * beans. - * - * @return true if a GUI is available, otherwise - * false. - */ - public static synchronized boolean isGuiAvailable() { - return guiAvailable; - } - - /** - * Determine if it's in design-mode. - * - * @return true if it's in an application construction environment. - */ - public static synchronized boolean isDesignTime() { - return designTime; - } - - private static void checkPropertiesAccess() throws SecurityException { - SecurityManager sm = System.getSecurityManager(); - - if (sm != null) { - sm.checkPropertiesAccess(); - } - } - - private static String getBeanResourceName(String beanName) { - return beanName.replace('.', '/') + ".ser"; //$NON-NLS-1$ - } - - - private static void appletLoaded(Applet applet, ClassLoader loader, - String name, BeanContext context, AppletInitializer initializer, - boolean deserialized) throws ClassNotFoundException { - - // If there is an initializer - if (initializer != null) { - initializer.initialize(applet, context); - } else { - setStub(applet, loader, deserialized, name); - } - - if (!deserialized) { - applet.init(); - } - - if (initializer != null) { - initializer.activate(applet); - } - } - - private static void setStub(Applet applet, final ClassLoader loader, - boolean serialized, String beanName) throws ClassNotFoundException { - // Get path to the resource representing the applet. - String pathName = beanName.replace('.', '/'); - final String resourceName = serialized ? pathName.concat(".ser") : pathName.concat(".class"); //$NON-NLS-1$ //$NON-NLS-2$ - URL objectUrl = AccessController - .doPrivileged(new PrivilegedAction() { - public URL run() { - if (loader == null) { - return ClassLoader.getSystemResource(resourceName); - } - return loader.getResource(resourceName); - } - }); - - // If we can't get to the applet itself, the codebase and doc base are - // left as null. - if (objectUrl == null) { - applet.setStub(getAppletStub(getStubAppletContext(applet), - null, null)); - return; - } - - // Try to decompose the resource URL to get to the doc/code URL - String urlString = objectUrl.toExternalForm(); - - // This is the URL of the directory that contains the applet. - int codeURLlength = urlString.length() - resourceName.length(); - URL codeBase = safeURL(urlString.substring(0, codeURLlength)); - - // URL of the document containing the applet. - int docURLlength = urlString.lastIndexOf('/'); - URL docBase = safeURL(urlString.substring(0, docURLlength + 1)); - - applet.setStub(getAppletStub(getStubAppletContext(applet), - codeBase, docBase)); - } - - - private static AppletStub getAppletStub(final AppletContext context, final URL codeBase, final URL docBase) { - - return new AppletStub() { - public boolean isActive() { - return true; - } - - public URL getDocumentBase() { - return docBase; - } - - public URL getCodeBase() { - return codeBase; - } - - public String getParameter(String name) { - // Applet beans have no params. - return null; - } - - public AppletContext getAppletContext() { - return context; - } - - public void appletResize(int width, int height) { - // Do nothing. - } - }; - } - - private static AppletContext getStubAppletContext(final Applet target) { - return new AppletContext() { - public AudioClip getAudioClip(URL url) { - return null; - } - - public synchronized Image getImage(URL url) { - return null; - } - - public Applet getApplet(String name) { - return null; - } - - public Enumeration getApplets() { - Vector applets = new Vector(); - applets.addElement(target); - return applets.elements(); - } - - public void showDocument(URL url) { - // Do nothing. - } - - public void showDocument(URL url, String aTarget) { - // Do nothing. - } - - public void showStatus(String status) { - // Do nothing. - } - - public void setStream(String key, InputStream stream) - throws IOException { - // Do nothing. - } - - public InputStream getStream(String key) { - return null; - } - - public Iterator getStreamKeys() { - return null; - } - }; - } - - - // Maps malformed URL exception to ClassNotFoundException - private static URL safeURL(String urlString) throws ClassNotFoundException { + /** Obtain an alternative type view of the given bean. The view type is specified by the parameter type. + *

    + * If the type view cannot be obtained, the original bean object is returned. + *

    + * + * @param bean the original bean object. + * @param targetType the specified view type. + * @return a type view of the given bean. */ + public static Object getInstanceOf (Object bean, Class targetType) { + return bean; + } + + /** Determine if the the specified bean object can be viewed as the specified type. + * + * @param bean the specified bean object. + * @param targetType the specifed view type. + * @return true if the specified bean object can be viewed as the specified type; otherwise, return false; */ + public static boolean isInstanceOf (Object bean, Class targetType) { + if (bean == null) { + throw new NullPointerException(Messages.getString("beans.1D")); //$NON-NLS-1$ + } + + return targetType == null ? false : targetType.isInstance(bean); + } + + /** Set whether or not a GUI is available in the bean's current environment. + * + * @param isGuiAvailable should be true to signify that a GUI is available, false otherwise. + * @throws SecurityException if the caller does not have the required permission to access or modify system properties. */ + public static synchronized void setGuiAvailable (boolean isGuiAvailable) throws SecurityException { + checkPropertiesAccess(); + guiAvailable = isGuiAvailable; + } + + /** Used to indicate whether of not it's in an application construction environment. + * + * @param isDesignTime true to indicate that it's in application construction environment. + * @throws SecurityException */ + public static void setDesignTime (boolean isDesignTime) throws SecurityException { + checkPropertiesAccess(); + synchronized (Beans.class) { + designTime = isDesignTime; + } + } + + /** Returns a boolean indication of whether or not a GUI is available for beans. + * + * @return true if a GUI is available, otherwise false. */ + public static synchronized boolean isGuiAvailable () { + return guiAvailable; + } + + /** Determine if it's in design-mode. + * + * @return true if it's in an application construction environment. */ + public static synchronized boolean isDesignTime () { + return designTime; + } + + private static void checkPropertiesAccess () throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + + if (sm != null) { + sm.checkPropertiesAccess(); + } + } + + private static String getBeanResourceName (String beanName) { + return beanName.replace('.', '/') + ".ser"; //$NON-NLS-1$ + } + + private static void appletLoaded (Applet applet, ClassLoader loader, String name, BeanContext context, + AppletInitializer initializer, boolean deserialized) throws ClassNotFoundException { + + // If there is an initializer + if (initializer != null) { + initializer.initialize(applet, context); + } else { + setStub(applet, loader, deserialized, name); + } + + if (!deserialized) { + applet.init(); + } + + if (initializer != null) { + initializer.activate(applet); + } + } + + private static void setStub (Applet applet, final ClassLoader loader, boolean serialized, String beanName) + throws ClassNotFoundException { + // Get path to the resource representing the applet. + String pathName = beanName.replace('.', '/'); + final String resourceName = serialized ? pathName.concat(".ser") : pathName.concat(".class"); //$NON-NLS-1$ //$NON-NLS-2$ + URL objectUrl = AccessController.doPrivileged(new PrivilegedAction() { + public URL run () { + if (loader == null) { + return ClassLoader.getSystemResource(resourceName); + } + return loader.getResource(resourceName); + } + }); + + // If we can't get to the applet itself, the codebase and doc base are + // left as null. + if (objectUrl == null) { + applet.setStub(getAppletStub(getStubAppletContext(applet), null, null)); + return; + } + + // Try to decompose the resource URL to get to the doc/code URL + String urlString = objectUrl.toExternalForm(); + + // This is the URL of the directory that contains the applet. + int codeURLlength = urlString.length() - resourceName.length(); + URL codeBase = safeURL(urlString.substring(0, codeURLlength)); + + // URL of the document containing the applet. + int docURLlength = urlString.lastIndexOf('/'); + URL docBase = safeURL(urlString.substring(0, docURLlength + 1)); + + applet.setStub(getAppletStub(getStubAppletContext(applet), codeBase, docBase)); + } + + private static AppletStub getAppletStub (final AppletContext context, final URL codeBase, final URL docBase) { + + return new AppletStub() { + public boolean isActive () { + return true; + } + + public URL getDocumentBase () { + return docBase; + } + + public URL getCodeBase () { + return codeBase; + } + + public String getParameter (String name) { + // Applet beans have no params. + return null; + } + + public AppletContext getAppletContext () { + return context; + } + + public void appletResize (int width, int height) { + // Do nothing. + } + }; + } + + private static AppletContext getStubAppletContext (final Applet target) { + return new AppletContext() { + public AudioClip getAudioClip (URL url) { + return null; + } + + public synchronized Image getImage (URL url) { + return null; + } + + public Applet getApplet (String name) { + return null; + } + + public Enumeration getApplets () { + Vector applets = new Vector(); + applets.addElement(target); + return applets.elements(); + } + + public void showDocument (URL url) { + // Do nothing. + } + + public void showDocument (URL url, String aTarget) { + // Do nothing. + } + + public void showStatus (String status) { + // Do nothing. + } + + public void setStream (String key, InputStream stream) throws IOException { + // Do nothing. + } + + public InputStream getStream (String key) { + return null; + } + + public Iterator getStreamKeys () { + return null; + } + }; + } + + // Maps malformed URL exception to ClassNotFoundException + private static URL safeURL (String urlString) throws ClassNotFoundException { try { return new URL(urlString); } catch (MalformedURLException exception) { diff --git a/extensions/beans/src/com/badlogic/gdx/beans/ClassPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/ClassPersistenceDelegate.java index 467114effc6..e8c680d6efe 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/ClassPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/ClassPersistenceDelegate.java @@ -17,80 +17,72 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - import java.lang.reflect.Field; class ClassPersistenceDelegate extends PersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder out) { - Class value = (Class) oldInstance; - Field fld = null; - final String TYPE = "TYPE"; //$NON-NLS-1$ - Expression result; - /* - * Special treatment to String.class to prevent endless loop of - * instantiation. - */ - if (value == String.class) { - return new Expression(value, "", "getClass", null); //$NON-NLS-1$//$NON-NLS-2$ - } - try { - if (value.equals(Integer.TYPE)) { - fld = Integer.class.getField(TYPE); - } else if (value.equals(Short.TYPE)) { - fld = Short.class.getField(TYPE); - } else if (value.equals(Long.TYPE)) { - fld = Long.class.getField(TYPE); - } else if (value.equals(Float.TYPE)) { - fld = Float.class.getField(TYPE); - } else if (value.equals(Double.TYPE)) { - fld = Double.class.getField(TYPE); - } else if (value.equals(Byte.TYPE)) { - fld = Byte.class.getField(TYPE); - } else if (value.equals(Character.TYPE)) { - fld = Character.class.getField(TYPE); - } else if (value.equals(Boolean.TYPE)) { - fld = Boolean.class.getField(TYPE); - } - } catch (NoSuchFieldException e) { - // impossible situation for valid java.lang classes - // implementation with version >= 1.1 - throw new AssertionError(e); - } - if (fld != null) { - // we have primitive type - result = new Expression(oldInstance, fld, - "get", new Object[] { null }); //$NON-NLS-1$ - } else { - result = new Expression(oldInstance, String.class, "forName", //$NON-NLS-1$ - new Object[] { value.getName() }); - } - return result; - } + @Override + protected Expression instantiate (Object oldInstance, Encoder out) { + Class value = (Class)oldInstance; + Field fld = null; + final String TYPE = "TYPE"; //$NON-NLS-1$ + Expression result; + /* + * Special treatment to String.class to prevent endless loop of instantiation. + */ + if (value == String.class) { + return new Expression(value, "", "getClass", null); //$NON-NLS-1$//$NON-NLS-2$ + } + try { + if (value.equals(Integer.TYPE)) { + fld = Integer.class.getField(TYPE); + } else if (value.equals(Short.TYPE)) { + fld = Short.class.getField(TYPE); + } else if (value.equals(Long.TYPE)) { + fld = Long.class.getField(TYPE); + } else if (value.equals(Float.TYPE)) { + fld = Float.class.getField(TYPE); + } else if (value.equals(Double.TYPE)) { + fld = Double.class.getField(TYPE); + } else if (value.equals(Byte.TYPE)) { + fld = Byte.class.getField(TYPE); + } else if (value.equals(Character.TYPE)) { + fld = Character.class.getField(TYPE); + } else if (value.equals(Boolean.TYPE)) { + fld = Boolean.class.getField(TYPE); + } + } catch (NoSuchFieldException e) { + // impossible situation for valid java.lang classes + // implementation with version >= 1.1 + throw new AssertionError(e); + } + if (fld != null) { + // we have primitive type + result = new Expression(oldInstance, fld, "get", new Object[] {null}); //$NON-NLS-1$ + } else { + result = new Expression(oldInstance, String.class, "forName", //$NON-NLS-1$ + new Object[] {value.getName()}); + } + return result; + } - @Override - /* - * It's unnecessary to do anything for initialization, because two mutatable - * class objects are actually the same. - */ - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder out) { - // do nothing - } + @Override + /* + * It's unnecessary to do anything for initialization, because two mutatable class objects are actually the same. + */ + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder out) { + // do nothing + } - @Override - protected boolean mutatesTo(Object oldInstance, Object newInstance) { - if (oldInstance instanceof Class && newInstance instanceof Class) { - Class c1 = (Class) oldInstance; - Class c2 = (Class) newInstance; - if (c1.getName().equals(c2.getName())) { - return true; - } - return false; - } - return super.mutatesTo(oldInstance, newInstance); - } + @Override + protected boolean mutatesTo (Object oldInstance, Object newInstance) { + if (oldInstance instanceof Class && newInstance instanceof Class) { + Class c1 = (Class)oldInstance; + Class c2 = (Class)newInstance; + if (c1.getName().equals(c2.getName())) { + return true; + } + return false; + } + return super.mutatesTo(oldInstance, newInstance); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/CustomizedObjectInputStream.java b/extensions/beans/src/com/badlogic/gdx/beans/CustomizedObjectInputStream.java index 51bd3e66a04..100012591d1 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/CustomizedObjectInputStream.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/CustomizedObjectInputStream.java @@ -25,62 +25,55 @@ import org.apache.harmony.beans.internal.nls.Messages; -/** - * Customized object input stream that allows to read objects by specified class - * loader - */ +/** Customized object input stream that allows to read objects by specified class loader */ class CustomizedObjectInputStream extends ObjectInputStream { - private ClassLoader cls; + private ClassLoader cls; - public CustomizedObjectInputStream(InputStream in, ClassLoader cls) - throws IOException { - super(in); - this.cls = cls; - } + public CustomizedObjectInputStream (InputStream in, ClassLoader cls) throws IOException { + super(in); + this.cls = cls; + } - @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, - ClassNotFoundException { - String className = desc.getName(); + @Override + protected Class resolveClass (ObjectStreamClass desc) throws IOException, ClassNotFoundException { + String className = desc.getName(); - if (className.startsWith("[")) { //$NON-NLS-1$ - int idx = className.lastIndexOf("["); //$NON-NLS-1$ - String prefix = className.substring(0, idx + 1); - int[] dimensions = new int[prefix.length()]; - for (int i = 0; i < dimensions.length; ++i) { - dimensions[i] = 0; - } + if (className.startsWith("[")) { //$NON-NLS-1$ + int idx = className.lastIndexOf("["); //$NON-NLS-1$ + String prefix = className.substring(0, idx + 1); + int[] dimensions = new int[prefix.length()]; + for (int i = 0; i < dimensions.length; ++i) { + dimensions[i] = 0; + } - String postfix = className.substring(idx + 1); - Class componentType = null; - if (postfix.equals("Z")) { //$NON-NLS-1$ - componentType = boolean.class; - } else if (postfix.equals("B")) { //$NON-NLS-1$ - componentType = byte.class; - } else if (postfix.equals("C")) { //$NON-NLS-1$ - componentType = char.class; - } else if (postfix.equals("D")) { //$NON-NLS-1$ - componentType = double.class; - } else if (postfix.equals("F")) { //$NON-NLS-1$ - componentType = float.class; - } else if (postfix.equals("I")) { //$NON-NLS-1$ - componentType = int.class; - } else if (postfix.equals("L")) { //$NON-NLS-1$ - componentType = long.class; - } else if (postfix.equals("S")) { //$NON-NLS-1$ - componentType = short.class; - } else if (postfix.equals("V")) { //$NON-NLS-1$ - // expected, componentType is already null - } else if (postfix.startsWith("L")) { //$NON-NLS-1$ - componentType = cls.loadClass(postfix.substring(1, postfix - .length() - 1)); - } else { - throw new IllegalArgumentException(Messages.getString( - "beans.1E", className)); //$NON-NLS-1$ - } - return Array.newInstance(componentType, dimensions).getClass(); - } - return Class.forName(className, true, cls); - } + String postfix = className.substring(idx + 1); + Class componentType = null; + if (postfix.equals("Z")) { //$NON-NLS-1$ + componentType = boolean.class; + } else if (postfix.equals("B")) { //$NON-NLS-1$ + componentType = byte.class; + } else if (postfix.equals("C")) { //$NON-NLS-1$ + componentType = char.class; + } else if (postfix.equals("D")) { //$NON-NLS-1$ + componentType = double.class; + } else if (postfix.equals("F")) { //$NON-NLS-1$ + componentType = float.class; + } else if (postfix.equals("I")) { //$NON-NLS-1$ + componentType = int.class; + } else if (postfix.equals("L")) { //$NON-NLS-1$ + componentType = long.class; + } else if (postfix.equals("S")) { //$NON-NLS-1$ + componentType = short.class; + } else if (postfix.equals("V")) { //$NON-NLS-1$ + // expected, componentType is already null + } else if (postfix.startsWith("L")) { //$NON-NLS-1$ + componentType = cls.loadClass(postfix.substring(1, postfix.length() - 1)); + } else { + throw new IllegalArgumentException(Messages.getString("beans.1E", className)); //$NON-NLS-1$ + } + return Array.newInstance(componentType, dimensions).getClass(); + } + return Class.forName(className, true, cls); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/Customizer.java b/extensions/beans/src/com/badlogic/gdx/beans/Customizer.java index 21f908964e3..3b77a694eaf 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/Customizer.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/Customizer.java @@ -17,13 +17,11 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeListener; - public interface Customizer { - public void setObject(Object bean); + public void setObject (Object bean); - public void removePropertyChangeListener(PropertyChangeListener listener); + public void removePropertyChangeListener (PropertyChangeListener listener); - public void addPropertyChangeListener(PropertyChangeListener listener); + public void addPropertyChangeListener (PropertyChangeListener listener); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/DefaultPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/DefaultPersistenceDelegate.java index 7dd0cf2c597..dae8b49a8f3 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/DefaultPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/DefaultPersistenceDelegate.java @@ -17,15 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.BeanInfo; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.IntrospectionException; -import com.badlogic.gdx.beans.Introspector; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.PropertyDescriptor; -import com.badlogic.gdx.beans.Statement; - import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.AccessController; @@ -34,267 +25,217 @@ import org.apache.harmony.beans.BeansUtils; -/** - * Default PersistenceDelegate for normal classes. The instances of this class - * are used when other customized PersistenceDelegate is not set in the encoders - * for a particular type. +/** Default PersistenceDelegate for normal classes. The instances of this class are used when other customized PersistenceDelegate + * is not set in the encoders for a particular type. *

    - * This PersistenceDelegate assumes that the bean to be made persistent has a - * default constructor that takes no parameters or a constructor that takes some - * properties as its parameters. Only the properties that can be got or set - * based on the knowledge gained through an introspection will be made - * persistent. In the case that a bean is constructed with some properties, the - * value of these properties should be available via the conventional getter - * method. + * This PersistenceDelegate assumes that the bean to be made persistent has a default constructor that takes no parameters or a + * constructor that takes some properties as its parameters. Only the properties that can be got or set based on the knowledge + * gained through an introspection will be made persistent. In the case that a bean is constructed with some properties, the value + * of these properties should be available via the conventional getter method. *

    * - * @see Encoder - */ + * @see Encoder */ public class DefaultPersistenceDelegate extends PersistenceDelegate { - // shared empty property name array - private static String[] EMPTY_PROPERTIES = new String[0]; - - // names of the properties accepted by the bean's constructor - private String[] propertyNames = EMPTY_PROPERTIES; - - /** - * Constructs a DefaultPersistenceDelegate instance that - * supports the persistence of a bean which has a default constructor. - * - */ - public DefaultPersistenceDelegate() { - // empty - } - - /** - * Constructs a DefaultPersistenceDelegate instance that - * supports the persistence of a bean which is constructed with some - * properties. - * - * @param propertyNames - * the name of the properties that are taken as parameters by the - * bean's constructor - */ - public DefaultPersistenceDelegate(String[] propertyNames) { - if (null != propertyNames) { - this.propertyNames = propertyNames; - } - } - - /** - * Initializes the new instance in the new environment so that it becomes - * equivalent with the old one, meanwhile recording this process in the - * encoder. - *

    - * This is done by inspecting each property of the bean. The property value - * from the old bean instance and the value from the new bean instance are - * both retrieved and examined to see whether the latter mutates to the - * former, and if not, issue a call to the write method to set the - * equivalent value for the new instance. Exceptions occured during this - * process are reported to the exception listener of the encoder. - *

    - * - * @param type - * the type of the bean - * @param oldInstance - * the original bean object to be recorded - * @param newInstance - * the simmulating new bean object to be initialized - * @param enc - * the encoder to write the outputs to - */ - @Override - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - // Call the initialization of the super type - super.initialize(type, oldInstance, newInstance, enc); - // Continue only if initializing the "current" type - if (type != oldInstance.getClass()) { - return; - } - - // Get all bean properties - BeanInfo info = null; - try { - info = Introspector.getBeanInfo(type); - } catch (IntrospectionException ex) { - enc.getExceptionListener().exceptionThrown(ex); - return; - } - PropertyDescriptor[] pds = info.getPropertyDescriptors(); - Method getter, setter; - // Initialize each found non-transient property - for (int i = 0; i < pds.length; i++) { - // Skip a property whose transient attribute is true - if (Boolean.TRUE.equals(pds[i].getValue("transient"))) { //$NON-NLS-1$ - continue; - } - getter = pds[i].getReadMethod(); - setter = pds[i].getWriteMethod(); - // Skip a property having no setter or getter - if (getter == null || setter == null) { - continue; - } - - // Get the value of the property in the old instance - Expression getterExp = new Expression(oldInstance, - getter.getName(), null); - try { - // Calculate the old value of the property - Object oldVal = getterExp.getValue(); - // Write the getter expression to the encoder - enc.writeExpression(getterExp); - // Get the target value that exists in the new environment - Object targetVal = enc.get(oldVal); - Object newVal = new Expression(newInstance, getter.getName(), - null).getValue(); - boolean invokeSetter = targetVal == null ? (newVal != null && oldVal == null) - : !enc.getPersistenceDelegate(targetVal.getClass()) - .mutatesTo(targetVal, newVal); - if (invokeSetter) { - enc.writeStatement(new Statement(oldInstance, setter - .getName(), new Object[] { oldVal })); - } - } catch (Exception ex) { - enc.getExceptionListener().exceptionThrown(ex); - } - } - } - - /* - * Get the field value of an object using privileged code. - */ - private Object getFieldValue(Object oldInstance, String fieldName) - throws NoSuchFieldException, IllegalAccessException { - Class c = oldInstance.getClass(); - final Field f = c.getDeclaredField(fieldName); - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - f.setAccessible(true); - return null; - } - }); - return f.get(oldInstance); - } - - /* - * Get the value for the specified property of the given bean instance. - */ - private Object getPropertyValue( - HashMap proDscMap, Object oldInstance, - String propName) throws Exception { - // Try to get the read method for the property - Method getter = null; - if (null != proDscMap) { - PropertyDescriptor pd = proDscMap.get(Introspector - .decapitalize(propName)); - if (null != pd) { - getter = pd.getReadMethod(); - } - } - - // Invoke read method to get the value if found - if (null != getter) { - return getter.invoke(oldInstance, (Object[]) null); - } - - // Otherwise, try to access the field directly - try { - return getFieldValue(oldInstance, propName); - } catch (Exception ex) { - // Fail, throw an exception - throw new NoSuchMethodException( - "The getter method for the property " //$NON-NLS-1$ - + propName + " can't be found."); //$NON-NLS-1$ - } - } - - /** - * Returns an expression that represents a call to the bean's constructor. - * The constructor may take zero or more parameters, as specified when this - * DefaultPersistenceDelegate is constructed. - * - * @param oldInstance - * the old instance - * @param enc - * the encoder that wants to record the old instance - * @return an expression for instantiating an object of the same type as the - * old instance - */ - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Object[] args = null; - - // Set the constructor arguments if any property names exist - if (this.propertyNames.length > 0) { - // Prepare the property descriptors for finding getter method later - BeanInfo info = null; - HashMap proDscMap = null; - try { - info = Introspector.getBeanInfo(oldInstance.getClass(), - Introspector.IGNORE_ALL_BEANINFO); - proDscMap = internalAsMap(info.getPropertyDescriptors()); - } catch (IntrospectionException ex) { - enc.getExceptionListener().exceptionThrown(ex); - throw new Error(ex); - } - - // Get the arguments values - args = new Object[this.propertyNames.length]; - for (int i = 0; i < this.propertyNames.length; i++) { - String propertyName = propertyNames[i]; - if (null == propertyName || 0 == propertyName.length()) { - continue; - } - - // Get the value for each property of the given instance - try { - args[i] = getPropertyValue(proDscMap, oldInstance, - this.propertyNames[i]); - } catch (Exception ex) { - enc.getExceptionListener().exceptionThrown(ex); - } - } - } - - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, args); - } - - private static HashMap internalAsMap( - PropertyDescriptor[] propertyDescs) { - HashMap map = new HashMap(); - for (int i = 0; i < propertyDescs.length; i++) { - map.put(propertyDescs[i].getName(), propertyDescs[i]); - } - return map; - } - - /** - * Determines whether one object mutates to the other object. If this - * DefaultPersistenceDelegate is constructed with one or more - * property names, and the class of o1 overrides the - * "equals(Object)" method, then o2 is considered to mutate to - * o1 if o1 equals to o2. Otherwise, - * the result is the same as the definition in - * PersistenceDelegate. - * - * @param o1 - * one object - * @param o2 - * the other object - * @return true if second object mutates to the first object, otherwise - * false - */ - @Override - protected boolean mutatesTo(Object o1, Object o2) { - if (this.propertyNames.length > 0) { - if (BeansUtils.declaredEquals(o1.getClass())) { - return o1.equals(o2); - } - } - return super.mutatesTo(o1, o2); - } -} \ No newline at end of file + // shared empty property name array + private static String[] EMPTY_PROPERTIES = new String[0]; + + // names of the properties accepted by the bean's constructor + private String[] propertyNames = EMPTY_PROPERTIES; + + /** Constructs a DefaultPersistenceDelegate instance that supports the persistence of a bean which has a default + * constructor. */ + public DefaultPersistenceDelegate () { + // empty + } + + /** Constructs a DefaultPersistenceDelegate instance that supports the persistence of a bean which is constructed + * with some properties. + * + * @param propertyNames the name of the properties that are taken as parameters by the bean's constructor */ + public DefaultPersistenceDelegate (String[] propertyNames) { + if (null != propertyNames) { + this.propertyNames = propertyNames; + } + } + + /** Initializes the new instance in the new environment so that it becomes equivalent with the old one, meanwhile recording this + * process in the encoder. + *

    + * This is done by inspecting each property of the bean. The property value from the old bean instance and the value from the + * new bean instance are both retrieved and examined to see whether the latter mutates to the former, and if not, issue a call + * to the write method to set the equivalent value for the new instance. Exceptions occured during this process are reported to + * the exception listener of the encoder. + *

    + * + * @param type the type of the bean + * @param oldInstance the original bean object to be recorded + * @param newInstance the simmulating new bean object to be initialized + * @param enc the encoder to write the outputs to */ + @Override + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + // Call the initialization of the super type + super.initialize(type, oldInstance, newInstance, enc); + // Continue only if initializing the "current" type + if (type != oldInstance.getClass()) { + return; + } + + // Get all bean properties + BeanInfo info = null; + try { + info = Introspector.getBeanInfo(type); + } catch (IntrospectionException ex) { + enc.getExceptionListener().exceptionThrown(ex); + return; + } + PropertyDescriptor[] pds = info.getPropertyDescriptors(); + Method getter, setter; + // Initialize each found non-transient property + for (int i = 0; i < pds.length; i++) { + // Skip a property whose transient attribute is true + if (Boolean.TRUE.equals(pds[i].getValue("transient"))) { //$NON-NLS-1$ + continue; + } + getter = pds[i].getReadMethod(); + setter = pds[i].getWriteMethod(); + // Skip a property having no setter or getter + if (getter == null || setter == null) { + continue; + } + + // Get the value of the property in the old instance + Expression getterExp = new Expression(oldInstance, getter.getName(), null); + try { + // Calculate the old value of the property + Object oldVal = getterExp.getValue(); + // Write the getter expression to the encoder + enc.writeExpression(getterExp); + // Get the target value that exists in the new environment + Object targetVal = enc.get(oldVal); + Object newVal = new Expression(newInstance, getter.getName(), null).getValue(); + boolean invokeSetter = targetVal == null ? (newVal != null && oldVal == null) : !enc.getPersistenceDelegate( + targetVal.getClass()).mutatesTo(targetVal, newVal); + if (invokeSetter) { + enc.writeStatement(new Statement(oldInstance, setter.getName(), new Object[] {oldVal})); + } + } catch (Exception ex) { + enc.getExceptionListener().exceptionThrown(ex); + } + } + } + + /* + * Get the field value of an object using privileged code. + */ + private Object getFieldValue (Object oldInstance, String fieldName) throws NoSuchFieldException, IllegalAccessException { + Class c = oldInstance.getClass(); + final Field f = c.getDeclaredField(fieldName); + AccessController.doPrivileged(new PrivilegedAction() { + public Object run () { + f.setAccessible(true); + return null; + } + }); + return f.get(oldInstance); + } + + /* + * Get the value for the specified property of the given bean instance. + */ + private Object getPropertyValue (HashMap proDscMap, Object oldInstance, String propName) + throws Exception { + // Try to get the read method for the property + Method getter = null; + if (null != proDscMap) { + PropertyDescriptor pd = proDscMap.get(Introspector.decapitalize(propName)); + if (null != pd) { + getter = pd.getReadMethod(); + } + } + + // Invoke read method to get the value if found + if (null != getter) { + return getter.invoke(oldInstance, (Object[])null); + } + + // Otherwise, try to access the field directly + try { + return getFieldValue(oldInstance, propName); + } catch (Exception ex) { + // Fail, throw an exception + throw new NoSuchMethodException("The getter method for the property " //$NON-NLS-1$ + + propName + " can't be found."); //$NON-NLS-1$ + } + } + + /** Returns an expression that represents a call to the bean's constructor. The constructor may take zero or more parameters, as + * specified when this DefaultPersistenceDelegate is constructed. + * + * @param oldInstance the old instance + * @param enc the encoder that wants to record the old instance + * @return an expression for instantiating an object of the same type as the old instance */ + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Object[] args = null; + + // Set the constructor arguments if any property names exist + if (this.propertyNames.length > 0) { + // Prepare the property descriptors for finding getter method later + BeanInfo info = null; + HashMap proDscMap = null; + try { + info = Introspector.getBeanInfo(oldInstance.getClass(), Introspector.IGNORE_ALL_BEANINFO); + proDscMap = internalAsMap(info.getPropertyDescriptors()); + } catch (IntrospectionException ex) { + enc.getExceptionListener().exceptionThrown(ex); + throw new Error(ex); + } + + // Get the arguments values + args = new Object[this.propertyNames.length]; + for (int i = 0; i < this.propertyNames.length; i++) { + String propertyName = propertyNames[i]; + if (null == propertyName || 0 == propertyName.length()) { + continue; + } + + // Get the value for each property of the given instance + try { + args[i] = getPropertyValue(proDscMap, oldInstance, this.propertyNames[i]); + } catch (Exception ex) { + enc.getExceptionListener().exceptionThrown(ex); + } + } + } + + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, args); + } + + private static HashMap internalAsMap (PropertyDescriptor[] propertyDescs) { + HashMap map = new HashMap(); + for (int i = 0; i < propertyDescs.length; i++) { + map.put(propertyDescs[i].getName(), propertyDescs[i]); + } + return map; + } + + /** Determines whether one object mutates to the other object. If this DefaultPersistenceDelegate is constructed + * with one or more property names, and the class of o1 overrides the "equals(Object)" method, then + * o2 is considered to mutate to o1 if o1 equals to o2. Otherwise, the + * result is the same as the definition in PersistenceDelegate. + * + * @param o1 one object + * @param o2 the other object + * @return true if second object mutates to the first object, otherwise false */ + @Override + protected boolean mutatesTo (Object o1, Object o2) { + if (this.propertyNames.length > 0) { + if (BeansUtils.declaredEquals(o1.getClass())) { + return o1.equals(o2); + } + } + return super.mutatesTo(o1, o2); + } +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/DesignMode.java b/extensions/beans/src/com/badlogic/gdx/beans/DesignMode.java index c2d2a408172..59adef8162c 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/DesignMode.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/DesignMode.java @@ -19,9 +19,9 @@ public interface DesignMode { - public static final String PROPERTYNAME = "designTime"; //$NON-NLS-1$ + public static final String PROPERTYNAME = "designTime"; //$NON-NLS-1$ - public void setDesignTime(boolean designTime); + public void setDesignTime (boolean designTime); - public boolean isDesignTime(); + public boolean isDesignTime (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/Encoder.java b/extensions/beans/src/com/badlogic/gdx/beans/Encoder.java index 95239238f91..fdb5833ee12 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/Encoder.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/Encoder.java @@ -34,18 +34,6 @@ import java.awt.ScrollPane; import java.awt.SystemColor; import java.awt.font.TextAttribute; - -import com.badlogic.gdx.beans.ArrayPersistenceDelegate; -import com.badlogic.gdx.beans.BeanInfo; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.ExceptionListener; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.Introspector; -import com.badlogic.gdx.beans.NullPersistenceDelegate; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.ProxyPersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -61,383 +49,325 @@ import javax.swing.JTabbedPane; import javax.swing.ToolTipManager; -/** - * The Encoder, together with PersistenceDelegate s, - * can encode an object into a series of java statements. By executing these - * statements, a new object can be created and it will has the same state as the - * original object which has been passed to the encoder. Here "has the same - * state" means the two objects are indistinguishable from their public API. +/** The Encoder, together with PersistenceDelegate s, can encode an object into a series of java + * statements. By executing these statements, a new object can be created and it will has the same state as the original object + * which has been passed to the encoder. Here "has the same state" means the two objects are indistinguishable from their public + * API. *

    - * The Encoder and PersistenceDelegate s do this by - * creating copies of the input object and all objects it references. The copy - * process continues recursively util every object in the object graph has its - * new copy and the new version has the same state as the old version. All - * statements used to create those new objects and executed on them during the + * The Encoder and PersistenceDelegate s do this by creating copies of the input object and all objects + * it references. The copy process continues recursively util every object in the object graph has its new copy and the new + * version has the same state as the old version. All statements used to create those new objects and executed on them during the * process form the result of encoding. - *

    - * - */ + *

    */ public class Encoder { - private static final Hashtable, PersistenceDelegate> delegates = new Hashtable, PersistenceDelegate>(); - - private static final DefaultPersistenceDelegate defaultPD = new DefaultPersistenceDelegate(); - - private static final ArrayPersistenceDelegate arrayPD = new ArrayPersistenceDelegate(); - - private static final ProxyPersistenceDelegate proxyPD = new ProxyPersistenceDelegate(); - - private static final NullPersistenceDelegate nullPD = new NullPersistenceDelegate(); - - private static final ExceptionListener defaultExListener = new DefaultExceptionListener(); - - private static class DefaultExceptionListener implements ExceptionListener { - - public void exceptionThrown(Exception exception) { - System.err.println("Exception during encoding:" + exception); //$NON-NLS-1$ - System.err.println("Continue..."); //$NON-NLS-1$ - } - - } - - static { - PersistenceDelegate ppd = new PrimitiveWrapperPersistenceDelegate(); - delegates.put(Boolean.class, ppd); - delegates.put(Byte.class, ppd); - delegates.put(Character.class, ppd); - delegates.put(Double.class, ppd); - delegates.put(Float.class, ppd); - delegates.put(Integer.class, ppd); - delegates.put(Long.class, ppd); - delegates.put(Short.class, ppd); - - delegates.put(Class.class, new ClassPersistenceDelegate()); - delegates.put(Field.class, new FieldPersistenceDelegate()); - delegates.put(Method.class, new MethodPersistenceDelegate()); - delegates.put(String.class, new StringPersistenceDelegate()); - delegates.put(Proxy.class, new ProxyPersistenceDelegate()); - - delegates.put(Choice.class, new AwtChoicePersistenceDelegate()); - delegates.put(Color.class, new AwtColorPersistenceDelegate()); - delegates.put(Container.class, new AwtContainerPersistenceDelegate()); - delegates.put(Component.class, new AwtComponentPersistenceDelegate()); - delegates.put(Cursor.class, new AwtCursorPersistenceDelegate()); - delegates.put(Dimension.class, new AwtDimensionPersistenceDelegate()); - delegates.put(Font.class, new AwtFontPersistenceDelegate()); - delegates.put(Insets.class, new AwtInsetsPersistenceDelegate()); - delegates.put(List.class, new AwtListPersistenceDelegate()); - delegates.put(Menu.class, new AwtMenuPersistenceDelegate()); - delegates.put(MenuBar.class, new AwtMenuBarPersistenceDelegate()); - delegates.put(MenuShortcut.class, - new AwtMenuShortcutPersistenceDelegate()); - delegates.put(Point.class, new AwtPointPersistenceDelegate()); - delegates.put(Rectangle.class, new AwtRectanglePersistenceDelegate()); - delegates.put(SystemColor.class, - new AwtSystemColorPersistenceDelegate()); - delegates.put(TextAttribute.class, - new AwtFontTextAttributePersistenceDelegate()); - - delegates.put(Box.class, new SwingBoxPersistenceDelegate()); - delegates.put(JFrame.class, new SwingJFramePersistenceDelegate()); - delegates.put(JTabbedPane.class, - new SwingJTabbedPanePersistenceDelegate()); - delegates.put(DefaultComboBoxModel.class, - new SwingDefaultComboBoxModelPersistenceDelegate()); - delegates.put(ToolTipManager.class, - new SwingToolTipManagerPersistenceDelegate()); - delegates.put(ScrollPane.class, new AwtScrollPanePersistenceDelegate()); - - delegates.put(Date.class, new UtilDatePersistenceDelegate()); - } - - private ExceptionListener listener = defaultExListener; - - private IdentityHashMap oldNewMap = new IdentityHashMap(); - - /** - * Construct a new encoder. - */ - public Encoder() { - super(); - } - - /** - * Clear all the new objects have been created. - */ - void clear() { - oldNewMap.clear(); - } - - /** - * Gets the new copy of the given old object. - *

    - * Strings are special objects which have their new copy by default, so if - * the old object is a string, it is returned directly. - *

    - * - * @param old - * an old object - * @return the new copy of the given old object, or null if there is not - * one. - */ - public Object get(Object old) { - if (old == null || old.getClass() == String.class) { - return old; - } - return oldNewMap.get(old); - } - - /** - * Returns the exception listener of this encoder. - *

    - * An encoder always have a non-null exception listener. A default exception - * listener is used when the encoder is created. - *

    - * - * @return the exception listener of this encoder - */ - public ExceptionListener getExceptionListener() { - return listener; - } - - /** - * Returns a PersistenceDelegate for the given class type. - *

    - * The PersistenceDelegate is determined as following: - *

      - *
    1. If a PersistenceDelegate has been registered by calling - * setPersistenceDelegate for the given type, it is returned.
    2. - *
    3. If the given type is an array class, a special - * PersistenceDelegate for array types is returned.
    4. - *
    5. If the given type is a proxy class, a special - * PersistenceDelegate for proxy classes is returned.
    6. - *
    7. Introspector is used to check the bean descriptor value - * "persistenceDelegate". If one is set, it is returned.
    8. - *
    9. If none of the above applies, the - * DefaultPersistenceDelegate is returned.
    10. - *
    - *

    - * - * @param type - * a class type - * @return a PersistenceDelegate for the given class type - */ - public PersistenceDelegate getPersistenceDelegate(Class type) { - if (type == null) { - return nullPD; // may be return a special PD? - } - - // registered delegate - PersistenceDelegate registeredPD = delegates.get(type); - if (registeredPD != null) { - return registeredPD; - } - - if (java.util.List.class.isAssignableFrom(type)) { - return new UtilListPersistenceDelegate(); - } - - if (Collection.class.isAssignableFrom(type)) { - return new UtilCollectionPersistenceDelegate(); - } - - if (Map.class.isAssignableFrom(type)) { - return new UtilMapPersistenceDelegate(); - } - - if (type.isArray()) { - return arrayPD; - } - - if (Proxy.isProxyClass(type)) { - return proxyPD; - } - - // check "persistenceDelegate" property - try { - BeanInfo beanInfo = Introspector.getBeanInfo(type); - if (beanInfo != null) { - PersistenceDelegate pd = (PersistenceDelegate) beanInfo - .getBeanDescriptor().getValue("persistenceDelegate"); //$NON-NLS-1$ - if (pd != null) { - return pd; - } - } - } catch (Exception e) { - // Ignored - } - - // default persistence delegate - return defaultPD; - } - - /** - * Remove the existing new copy of the given old object. - * - * @param old - * an old object - * @return the removed new version of the old object, or null if there is - * not one - */ - public Object remove(Object old) { - return oldNewMap.remove(old); - } - - /** - * Sets the exception listener of this encoder. - * - * @param listener - * the exception listener to set - */ - public void setExceptionListener(ExceptionListener listener) { - this.listener = listener == null ? defaultExListener : listener; - } - - /** - * Register the PersistenceDelegate of the specified type. - * - * @param type - * @param delegate - */ - public void setPersistenceDelegate(Class type, - PersistenceDelegate delegate) { - if (type == null || delegate == null) { - throw new NullPointerException(); - } - delegates.put(type, delegate); - } - - Object expressionValue(Expression exp) { - try { - return exp == null ? null : exp.getValue(); - } catch (IndexOutOfBoundsException e) { - return null; - } catch (Exception e) { - listener.exceptionThrown(new Exception( - "failed to excute expression: " + exp, e)); //$NON-NLS-1$ - } - return null; - } - - private Statement createNewStatement(Statement oldStat) { - Object newTarget = createNewObject(oldStat.getTarget()); - Object[] oldArgs = oldStat.getArguments(); - Object[] newArgs = new Object[oldArgs.length]; - for (int index = 0; index < oldArgs.length; index++) { - newArgs[index] = createNewObject(oldArgs[index]); - } - - if (oldStat.getClass() == Expression.class) { - return new Expression(newTarget, oldStat.getMethodName(), newArgs); - } else { - return new Statement(newTarget, oldStat.getMethodName(), newArgs); - } - } - - private Object createNewObject(Object old) { - Object nu = get(old); - if (nu == null) { - writeObject(old); - nu = get(old); - } - return nu; - } - - /** - * Write an expression of old objects. - *

    - * The implementation first check the return value of the expression. If - * there exists a new version of the object, simply return. - *

    - *

    - * A new expression is created using the new versions of the target and the - * arguments. If any of the old objects do not have its new version yet, - * writeObject() is called to create the new version. - *

    - *

    - * The new expression is then executed to obtained a new copy of the old - * return value. - *

    - *

    - * Call writeObject() with the old return value, so that more - * statements will be executed on its new version to change it into the same - * state as the old value. - *

    - * - * @param oldExp - * the expression to write. The target, arguments, and return - * value of the expression are all old objects. - */ - public void writeExpression(Expression oldExp) { - if (oldExp == null) { - throw new NullPointerException(); - } - try { - // if oldValue exists, no operation - Object oldValue = expressionValue(oldExp); - if (oldValue == null || get(oldValue) != null) { - return; - } - - // copy to newExp - Expression newExp = (Expression) createNewStatement(oldExp); - // relate oldValue to newValue - try { - oldNewMap.put(oldValue, newExp.getValue()); - } catch (IndexOutOfBoundsException e) { - // container does not have any component, set newVal null - } - - // force same state - writeObject(oldValue); - } catch (Exception e) { - listener.exceptionThrown(new Exception( - "failed to write expression: " + oldExp, e)); //$NON-NLS-1$ - } - } - - /** - * Encode the given object into a series of statements and expressions. - *

    - * The implementation simply finds the PersistenceDelegate - * responsible for the object's class, and delegate the call to it. - *

    - * - * @param o - * the object to encode - */ - protected void writeObject(Object o) { - if (o == null) { - return; - } - getPersistenceDelegate(o.getClass()).writeObject(o, this); - } - - /** - * Write a statement of old objects. - *

    - * A new statement is created by using the new versions of the target and - * arguments. If any of the objects do not have its new copy yet, - * writeObject() is called to create one. - *

    - *

    - * The new statement is then executed to change the state of the new object. - *

    - * - * @param oldStat - * a statement of old objects - */ - public void writeStatement(Statement oldStat) { - if (oldStat == null) { - throw new NullPointerException(); - } - Statement newStat = createNewStatement(oldStat); - try { - // execute newStat - newStat.execute(); - } catch (Exception e) { - listener.exceptionThrown(new Exception( - "failed to write statement: " + oldStat, e)); //$NON-NLS-1$ - } - } + private static final Hashtable, PersistenceDelegate> delegates = new Hashtable, PersistenceDelegate>(); + + private static final DefaultPersistenceDelegate defaultPD = new DefaultPersistenceDelegate(); + + private static final ArrayPersistenceDelegate arrayPD = new ArrayPersistenceDelegate(); + + private static final ProxyPersistenceDelegate proxyPD = new ProxyPersistenceDelegate(); + + private static final NullPersistenceDelegate nullPD = new NullPersistenceDelegate(); + + private static final ExceptionListener defaultExListener = new DefaultExceptionListener(); + + private static class DefaultExceptionListener implements ExceptionListener { + + public void exceptionThrown (Exception exception) { + System.err.println("Exception during encoding:" + exception); //$NON-NLS-1$ + System.err.println("Continue..."); //$NON-NLS-1$ + } + + } + + static { + PersistenceDelegate ppd = new PrimitiveWrapperPersistenceDelegate(); + delegates.put(Boolean.class, ppd); + delegates.put(Byte.class, ppd); + delegates.put(Character.class, ppd); + delegates.put(Double.class, ppd); + delegates.put(Float.class, ppd); + delegates.put(Integer.class, ppd); + delegates.put(Long.class, ppd); + delegates.put(Short.class, ppd); + + delegates.put(Class.class, new ClassPersistenceDelegate()); + delegates.put(Field.class, new FieldPersistenceDelegate()); + delegates.put(Method.class, new MethodPersistenceDelegate()); + delegates.put(String.class, new StringPersistenceDelegate()); + delegates.put(Proxy.class, new ProxyPersistenceDelegate()); + + delegates.put(Choice.class, new AwtChoicePersistenceDelegate()); + delegates.put(Color.class, new AwtColorPersistenceDelegate()); + delegates.put(Container.class, new AwtContainerPersistenceDelegate()); + delegates.put(Component.class, new AwtComponentPersistenceDelegate()); + delegates.put(Cursor.class, new AwtCursorPersistenceDelegate()); + delegates.put(Dimension.class, new AwtDimensionPersistenceDelegate()); + delegates.put(Font.class, new AwtFontPersistenceDelegate()); + delegates.put(Insets.class, new AwtInsetsPersistenceDelegate()); + delegates.put(List.class, new AwtListPersistenceDelegate()); + delegates.put(Menu.class, new AwtMenuPersistenceDelegate()); + delegates.put(MenuBar.class, new AwtMenuBarPersistenceDelegate()); + delegates.put(MenuShortcut.class, new AwtMenuShortcutPersistenceDelegate()); + delegates.put(Point.class, new AwtPointPersistenceDelegate()); + delegates.put(Rectangle.class, new AwtRectanglePersistenceDelegate()); + delegates.put(SystemColor.class, new AwtSystemColorPersistenceDelegate()); + delegates.put(TextAttribute.class, new AwtFontTextAttributePersistenceDelegate()); + + delegates.put(Box.class, new SwingBoxPersistenceDelegate()); + delegates.put(JFrame.class, new SwingJFramePersistenceDelegate()); + delegates.put(JTabbedPane.class, new SwingJTabbedPanePersistenceDelegate()); + delegates.put(DefaultComboBoxModel.class, new SwingDefaultComboBoxModelPersistenceDelegate()); + delegates.put(ToolTipManager.class, new SwingToolTipManagerPersistenceDelegate()); + delegates.put(ScrollPane.class, new AwtScrollPanePersistenceDelegate()); + + delegates.put(Date.class, new UtilDatePersistenceDelegate()); + } + + private ExceptionListener listener = defaultExListener; + + private IdentityHashMap oldNewMap = new IdentityHashMap(); + + /** Construct a new encoder. */ + public Encoder () { + super(); + } + + /** Clear all the new objects have been created. */ + void clear () { + oldNewMap.clear(); + } + + /** Gets the new copy of the given old object. + *

    + * Strings are special objects which have their new copy by default, so if the old object is a string, it is returned directly. + *

    + * + * @param old an old object + * @return the new copy of the given old object, or null if there is not one. */ + public Object get (Object old) { + if (old == null || old.getClass() == String.class) { + return old; + } + return oldNewMap.get(old); + } + + /** Returns the exception listener of this encoder. + *

    + * An encoder always have a non-null exception listener. A default exception listener is used when the encoder is created. + *

    + * + * @return the exception listener of this encoder */ + public ExceptionListener getExceptionListener () { + return listener; + } + + /** Returns a PersistenceDelegate for the given class type. + *

    + * The PersistenceDelegate is determined as following: + *

      + *
    1. If a PersistenceDelegate has been registered by calling setPersistenceDelegate for the given + * type, it is returned.
    2. + *
    3. If the given type is an array class, a special PersistenceDelegate for array types is returned.
    4. + *
    5. If the given type is a proxy class, a special PersistenceDelegate for proxy classes is returned.
    6. + *
    7. Introspector is used to check the bean descriptor value "persistenceDelegate". If one is set, it is + * returned.
    8. + *
    9. If none of the above applies, the DefaultPersistenceDelegate is returned.
    10. + *
    + *

    + * + * @param type a class type + * @return a PersistenceDelegate for the given class type */ + public PersistenceDelegate getPersistenceDelegate (Class type) { + if (type == null) { + return nullPD; // may be return a special PD? + } + + // registered delegate + PersistenceDelegate registeredPD = delegates.get(type); + if (registeredPD != null) { + return registeredPD; + } + + if (java.util.List.class.isAssignableFrom(type)) { + return new UtilListPersistenceDelegate(); + } + + if (Collection.class.isAssignableFrom(type)) { + return new UtilCollectionPersistenceDelegate(); + } + + if (Map.class.isAssignableFrom(type)) { + return new UtilMapPersistenceDelegate(); + } + + if (type.isArray()) { + return arrayPD; + } + + if (Proxy.isProxyClass(type)) { + return proxyPD; + } + + // check "persistenceDelegate" property + try { + BeanInfo beanInfo = Introspector.getBeanInfo(type); + if (beanInfo != null) { + PersistenceDelegate pd = (PersistenceDelegate)beanInfo.getBeanDescriptor().getValue("persistenceDelegate"); //$NON-NLS-1$ + if (pd != null) { + return pd; + } + } + } catch (Exception e) { + // Ignored + } + + // default persistence delegate + return defaultPD; + } + + /** Remove the existing new copy of the given old object. + * + * @param old an old object + * @return the removed new version of the old object, or null if there is not one */ + public Object remove (Object old) { + return oldNewMap.remove(old); + } + + /** Sets the exception listener of this encoder. + * + * @param listener the exception listener to set */ + public void setExceptionListener (ExceptionListener listener) { + this.listener = listener == null ? defaultExListener : listener; + } + + /** Register the PersistenceDelegate of the specified type. + * + * @param type + * @param delegate */ + public void setPersistenceDelegate (Class type, PersistenceDelegate delegate) { + if (type == null || delegate == null) { + throw new NullPointerException(); + } + delegates.put(type, delegate); + } + + Object expressionValue (Expression exp) { + try { + return exp == null ? null : exp.getValue(); + } catch (IndexOutOfBoundsException e) { + return null; + } catch (Exception e) { + listener.exceptionThrown(new Exception("failed to excute expression: " + exp, e)); //$NON-NLS-1$ + } + return null; + } + + private Statement createNewStatement (Statement oldStat) { + Object newTarget = createNewObject(oldStat.getTarget()); + Object[] oldArgs = oldStat.getArguments(); + Object[] newArgs = new Object[oldArgs.length]; + for (int index = 0; index < oldArgs.length; index++) { + newArgs[index] = createNewObject(oldArgs[index]); + } + + if (oldStat.getClass() == Expression.class) { + return new Expression(newTarget, oldStat.getMethodName(), newArgs); + } else { + return new Statement(newTarget, oldStat.getMethodName(), newArgs); + } + } + + private Object createNewObject (Object old) { + Object nu = get(old); + if (nu == null) { + writeObject(old); + nu = get(old); + } + return nu; + } + + /** Write an expression of old objects. + *

    + * The implementation first check the return value of the expression. If there exists a new version of the object, simply + * return. + *

    + *

    + * A new expression is created using the new versions of the target and the arguments. If any of the old objects do not have + * its new version yet, writeObject() is called to create the new version. + *

    + *

    + * The new expression is then executed to obtained a new copy of the old return value. + *

    + *

    + * Call writeObject() with the old return value, so that more statements will be executed on its new version to + * change it into the same state as the old value. + *

    + * + * @param oldExp the expression to write. The target, arguments, and return value of the expression are all old objects. */ + public void writeExpression (Expression oldExp) { + if (oldExp == null) { + throw new NullPointerException(); + } + try { + // if oldValue exists, no operation + Object oldValue = expressionValue(oldExp); + if (oldValue == null || get(oldValue) != null) { + return; + } + + // copy to newExp + Expression newExp = (Expression)createNewStatement(oldExp); + // relate oldValue to newValue + try { + oldNewMap.put(oldValue, newExp.getValue()); + } catch (IndexOutOfBoundsException e) { + // container does not have any component, set newVal null + } + + // force same state + writeObject(oldValue); + } catch (Exception e) { + listener.exceptionThrown(new Exception("failed to write expression: " + oldExp, e)); //$NON-NLS-1$ + } + } + + /** Encode the given object into a series of statements and expressions. + *

    + * The implementation simply finds the PersistenceDelegate responsible for the object's class, and delegate the + * call to it. + *

    + * + * @param o the object to encode */ + protected void writeObject (Object o) { + if (o == null) { + return; + } + getPersistenceDelegate(o.getClass()).writeObject(o, this); + } + + /** Write a statement of old objects. + *

    + * A new statement is created by using the new versions of the target and arguments. If any of the objects do not have its new + * copy yet, writeObject() is called to create one. + *

    + *

    + * The new statement is then executed to change the state of the new object. + *

    + * + * @param oldStat a statement of old objects */ + public void writeStatement (Statement oldStat) { + if (oldStat == null) { + throw new NullPointerException(); + } + Statement newStat = createNewStatement(oldStat); + try { + // execute newStat + newStat.execute(); + } catch (Exception e) { + listener.exceptionThrown(new Exception("failed to write statement: " + oldStat, e)); //$NON-NLS-1$ + } + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/EventHandler.java b/extensions/beans/src/com/badlogic/gdx/beans/EventHandler.java index 8050020a1bd..eaff35a69bc 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/EventHandler.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/EventHandler.java @@ -17,12 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.BeanInfo; -import com.badlogic.gdx.beans.EventHandler; -import com.badlogic.gdx.beans.IntrospectionException; -import com.badlogic.gdx.beans.Introspector; -import com.badlogic.gdx.beans.PropertyDescriptor; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -37,329 +31,303 @@ public class EventHandler implements InvocationHandler { - private Object target; - - private String action; - - private String eventPropertyName; - - private String listenerMethodName; - - final private AccessControlContext context; - - public EventHandler(Object target, String action, String eventPropertyName, - String listenerMethodName) { - if (target == null || action == null) { - throw new NullPointerException(); - } - this.target = target; - this.action = action; - this.eventPropertyName = eventPropertyName; - this.listenerMethodName = listenerMethodName; - this.context = AccessController.getContext(); - } - - public Object invoke(final Object proxy, final Method method, final Object[] arguments) { - return AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - return invokeImpl(proxy, method, arguments); - } - }, context); - } - - private Object invokeImpl(Object proxy, Method method, Object[] arguments) { - Class proxyClass = proxy.getClass(); - Object[] theArguments = arguments == null ? new Object[0] : arguments; - Object result = null; - - // if a proxy - if (Proxy.isProxyClass(proxyClass)) { - InvocationHandler handler = Proxy.getInvocationHandler(proxy); - - // if a valid object - if (handler instanceof EventHandler) { - // if the method from the Object class is called - String methodName = method.getName(); - if (method.getDeclaringClass() == Object.class) { - if (theArguments.length == 0) { - if ("hashCode".equals(methodName)) { //$NON-NLS-1$ - result = Integer.valueOf(hashCode()); - } else if ("toString".equals(methodName)) { //$NON-NLS-1$ - result = proxy.getClass().getSimpleName() - + toString().substring( - getClass().getName().length()); - } - } else if (theArguments.length == 1 - && theArguments[0] != null - && "equals".equals(methodName)) { //$NON-NLS-1$ - result = Boolean.valueOf(proxy == theArguments[0]); - } - } else if (isValidInvocation(method, theArguments)) { - // if listener method - try { - // extract value from event property name - Object[] args = getArgs(theArguments); - // extract method to be invoked on target - Method m = getMethod(proxy, method, theArguments, args); - - // we have a valid listener method at this point - result = m.invoke(target, args); - } catch (RuntimeException e) { - throw e; - } catch (Throwable t) { - throw new RuntimeException(t); - } - } else { - // in order to be compatible with RI - if (listenerMethodName.equals(methodName)) { - throw new IllegalArgumentException(Messages - .getString("beans.4D")); //$NON-NLS-1$ - } - } - } - } else { - // HARMONY-2495 - if (null == method) { - throw new NullPointerException(Messages.getString("beans.55")); //$NON-NLS-1$ - } - } - return result; - } - - public String getListenerMethodName() { - return listenerMethodName; - } - - public String getEventPropertyName() { - return eventPropertyName; - } - - public String getAction() { - return action; - } - - public Object getTarget() { - return target; - } - - @SuppressWarnings("unchecked") - public static T create(Class listenerInterface, Object target, - String action, String eventPropertyName, String listenerMethodName) { - if (action == null || target == null || listenerInterface == null) { - throw new NullPointerException(); - } - return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), - new Class[] { listenerInterface }, new EventHandler(target, - action, eventPropertyName, listenerMethodName)); - } - - public static T create(Class listenerInterface, Object target, - String action, String eventPropertyName) { - return create(listenerInterface, target, action, eventPropertyName, - null); - } - - public static T create(Class listenerInterface, Object target, - String action) { - return create(listenerInterface, target, action, null, null); - } - - private boolean isValidInvocation(Method method, Object[] arguments) { - // all listener methods are valid - if (listenerMethodName == null) { - return true; - } - - // method's name matches - if (listenerMethodName.equals(method.getName())) { - // no arguments in call are valid - if (eventPropertyName == null - && (arguments == null || arguments.length == 0)) { - return true; - } - // one-argument call is also valid - if (arguments != null && arguments.length == 1) { - return true; - } - } - return false; - } - - private Object[] getArgs(Object[] arguments) throws Exception { - if (eventPropertyName == null) { - return new Object[0]; - } else if ((arguments == null) || (arguments.length == 0)) { - return arguments; - } else { - Object arg = arguments[0]; - StringTokenizer st = new StringTokenizer(eventPropertyName, "."); //$NON-NLS-1$ - - while (st.hasMoreTokens()) { - String propertyName = st.nextToken(); - PropertyDescriptor pd = findPropertyDescriptor(arg.getClass(), - propertyName); - - Method getMethod = null; - if (pd != null) { - getMethod = pd.getReadMethod(); - - if (getMethod != null) { - arg = getMethod.invoke(arg, new Object[] {}); - } else { - throw new IntrospectionException(Messages.getString( - "beans.11", propertyName)); //$NON-NLS-1$ - } - } else { - getMethod = findStaticGetter(arg.getClass(), propertyName); - - if (getMethod != null) { - arg = getMethod.invoke(null, new Object[] {}); - } else { - // cannot access property getter - // RI throws NPE here so we should do the same - throw new NullPointerException(Messages.getString( - "beans.12", propertyName)); //$NON-NLS-1$ - } - } - } - return new Object[] { arg }; - } - } - - private Method getMethod(Object proxy, Method method, Object[] arguments, - Object[] args) throws Exception { - // filtering - examine if the 'method' could be applied to proxy - boolean found = false; - - if (listenerMethodName == null) { - // can be invoke with any listener method - Class[] proxyInterfaces = proxy.getClass().getInterfaces(); - for (Class proxyInstance : proxyInterfaces) { - Method[] interfaceMethods = proxyInstance.getMethods(); - for (Method listenerMethod : interfaceMethods) { - if (equalNames(listenerMethod, method) - && canInvokeWithArguments(listenerMethod, arguments)) { - found = true; - break; - } - } - - if (found) { - break; - } - } - } else if (listenerMethodName.equals(method.getName())) { - // can be invoked with a specified listener method - found = true; - } - - if (found == false) { - return null; - } - - // 'Method' can be applied to proxy - filtering succeeded - try { - Method result = findMethod(target.getClass(), args); - if (result == null) { - PropertyDescriptor pd = findPropertyDescriptor(target - .getClass(), action); - - if (pd != null) { - result = pd.getWriteMethod(); - - if (result == null) { - throw new NoSuchMethodException(Messages.getString( - "beans.13", action)); //$NON-NLS-1$ - } - } else { - throw new IndexOutOfBoundsException(Messages - .getString("beans.14")); //$NON-NLS-1$ - } - } - return result; - } catch (IntrospectionException ie) { - throw new IndexOutOfBoundsException(Messages.getString("beans.14")); //$NON-NLS-1$ - } - } - - private PropertyDescriptor findPropertyDescriptor(Class theClass, - String propertyName) throws IntrospectionException { - BeanInfo beanInfo = Introspector.getBeanInfo(theClass); - PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); - - for (PropertyDescriptor pd : pds) { - if (pd.getName().equals(propertyName)) { - return pd; - } - } - return null; - } - - private Method findStaticGetter(Class theClass, String propertyName) { - Method[] methods = theClass.getMethods(); - for (Method method : methods) { - int modifiers = method.getModifiers(); - - if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) { - String methodName = method.getName(); - String postfix = null; - - if (methodName.startsWith("get")) { //$NON-NLS-1$ - postfix = methodName.substring(3); - } else if (methodName.startsWith("is")) { //$NON-NLS-1$ - postfix = methodName.substring(2); - } else { - continue; - } - - if ((method.getParameterTypes().length != 0) - || (method.getReturnType() == void.class)) { - continue; - } - - postfix = Introspector.decapitalize(postfix); - if (postfix.equals(propertyName)) { - return method; - } - } - } - return null; - } - - private Method findMethod(Class type, Object[] args) { - Method[] methods = type.getMethods(); - for (Method method : methods) { - if (action.equals(method.getName()) - && canInvokeWithArguments(method, args)) { - return method; - } - } - return null; - } - - private static boolean canInvokeWithArguments(Method method, - Object[] arguments) { - Class[] parameterTypes = method.getParameterTypes(); - if (parameterTypes.length != arguments.length) { - return false; - } - - for (int index = 0; index < arguments.length; index++) { - Class argumentType = (arguments[index] == null) ? null - : arguments[index].getClass(); - if (argumentType == null - || BeansUtils.isPrimitiveWrapper(argumentType, - parameterTypes[index])) { - continue; - } - if (!argumentType.isAssignableFrom(parameterTypes[index])) { - return false; - } - } - return true; - } - - private static boolean equalNames(Method m1, Method m2) { - return m1.getName().equals(m2.getName()); - } + private Object target; + + private String action; + + private String eventPropertyName; + + private String listenerMethodName; + + final private AccessControlContext context; + + public EventHandler (Object target, String action, String eventPropertyName, String listenerMethodName) { + if (target == null || action == null) { + throw new NullPointerException(); + } + this.target = target; + this.action = action; + this.eventPropertyName = eventPropertyName; + this.listenerMethodName = listenerMethodName; + this.context = AccessController.getContext(); + } + + public Object invoke (final Object proxy, final Method method, final Object[] arguments) { + return AccessController.doPrivileged(new PrivilegedAction() { + public Object run () { + return invokeImpl(proxy, method, arguments); + } + }, context); + } + + private Object invokeImpl (Object proxy, Method method, Object[] arguments) { + Class proxyClass = proxy.getClass(); + Object[] theArguments = arguments == null ? new Object[0] : arguments; + Object result = null; + + // if a proxy + if (Proxy.isProxyClass(proxyClass)) { + InvocationHandler handler = Proxy.getInvocationHandler(proxy); + + // if a valid object + if (handler instanceof EventHandler) { + // if the method from the Object class is called + String methodName = method.getName(); + if (method.getDeclaringClass() == Object.class) { + if (theArguments.length == 0) { + if ("hashCode".equals(methodName)) { //$NON-NLS-1$ + result = Integer.valueOf(hashCode()); + } else if ("toString".equals(methodName)) { //$NON-NLS-1$ + result = proxy.getClass().getSimpleName() + toString().substring(getClass().getName().length()); + } + } else if (theArguments.length == 1 && theArguments[0] != null && "equals".equals(methodName)) { //$NON-NLS-1$ + result = Boolean.valueOf(proxy == theArguments[0]); + } + } else if (isValidInvocation(method, theArguments)) { + // if listener method + try { + // extract value from event property name + Object[] args = getArgs(theArguments); + // extract method to be invoked on target + Method m = getMethod(proxy, method, theArguments, args); + + // we have a valid listener method at this point + result = m.invoke(target, args); + } catch (RuntimeException e) { + throw e; + } catch (Throwable t) { + throw new RuntimeException(t); + } + } else { + // in order to be compatible with RI + if (listenerMethodName.equals(methodName)) { + throw new IllegalArgumentException(Messages.getString("beans.4D")); //$NON-NLS-1$ + } + } + } + } else { + // HARMONY-2495 + if (null == method) { + throw new NullPointerException(Messages.getString("beans.55")); //$NON-NLS-1$ + } + } + return result; + } + + public String getListenerMethodName () { + return listenerMethodName; + } + + public String getEventPropertyName () { + return eventPropertyName; + } + + public String getAction () { + return action; + } + + public Object getTarget () { + return target; + } + + @SuppressWarnings("unchecked") + public static T create (Class listenerInterface, Object target, String action, String eventPropertyName, + String listenerMethodName) { + if (action == null || target == null || listenerInterface == null) { + throw new NullPointerException(); + } + return (T)Proxy.newProxyInstance(target.getClass().getClassLoader(), new Class[] {listenerInterface}, new EventHandler( + target, action, eventPropertyName, listenerMethodName)); + } + + public static T create (Class listenerInterface, Object target, String action, String eventPropertyName) { + return create(listenerInterface, target, action, eventPropertyName, null); + } + + public static T create (Class listenerInterface, Object target, String action) { + return create(listenerInterface, target, action, null, null); + } + + private boolean isValidInvocation (Method method, Object[] arguments) { + // all listener methods are valid + if (listenerMethodName == null) { + return true; + } + + // method's name matches + if (listenerMethodName.equals(method.getName())) { + // no arguments in call are valid + if (eventPropertyName == null && (arguments == null || arguments.length == 0)) { + return true; + } + // one-argument call is also valid + if (arguments != null && arguments.length == 1) { + return true; + } + } + return false; + } + + private Object[] getArgs (Object[] arguments) throws Exception { + if (eventPropertyName == null) { + return new Object[0]; + } else if ((arguments == null) || (arguments.length == 0)) { + return arguments; + } else { + Object arg = arguments[0]; + StringTokenizer st = new StringTokenizer(eventPropertyName, "."); //$NON-NLS-1$ + + while (st.hasMoreTokens()) { + String propertyName = st.nextToken(); + PropertyDescriptor pd = findPropertyDescriptor(arg.getClass(), propertyName); + + Method getMethod = null; + if (pd != null) { + getMethod = pd.getReadMethod(); + + if (getMethod != null) { + arg = getMethod.invoke(arg, new Object[] {}); + } else { + throw new IntrospectionException(Messages.getString("beans.11", propertyName)); //$NON-NLS-1$ + } + } else { + getMethod = findStaticGetter(arg.getClass(), propertyName); + + if (getMethod != null) { + arg = getMethod.invoke(null, new Object[] {}); + } else { + // cannot access property getter + // RI throws NPE here so we should do the same + throw new NullPointerException(Messages.getString("beans.12", propertyName)); //$NON-NLS-1$ + } + } + } + return new Object[] {arg}; + } + } + + private Method getMethod (Object proxy, Method method, Object[] arguments, Object[] args) throws Exception { + // filtering - examine if the 'method' could be applied to proxy + boolean found = false; + + if (listenerMethodName == null) { + // can be invoke with any listener method + Class[] proxyInterfaces = proxy.getClass().getInterfaces(); + for (Class proxyInstance : proxyInterfaces) { + Method[] interfaceMethods = proxyInstance.getMethods(); + for (Method listenerMethod : interfaceMethods) { + if (equalNames(listenerMethod, method) && canInvokeWithArguments(listenerMethod, arguments)) { + found = true; + break; + } + } + + if (found) { + break; + } + } + } else if (listenerMethodName.equals(method.getName())) { + // can be invoked with a specified listener method + found = true; + } + + if (found == false) { + return null; + } + + // 'Method' can be applied to proxy - filtering succeeded + try { + Method result = findMethod(target.getClass(), args); + if (result == null) { + PropertyDescriptor pd = findPropertyDescriptor(target.getClass(), action); + + if (pd != null) { + result = pd.getWriteMethod(); + + if (result == null) { + throw new NoSuchMethodException(Messages.getString("beans.13", action)); //$NON-NLS-1$ + } + } else { + throw new IndexOutOfBoundsException(Messages.getString("beans.14")); //$NON-NLS-1$ + } + } + return result; + } catch (IntrospectionException ie) { + throw new IndexOutOfBoundsException(Messages.getString("beans.14")); //$NON-NLS-1$ + } + } + + private PropertyDescriptor findPropertyDescriptor (Class theClass, String propertyName) throws IntrospectionException { + BeanInfo beanInfo = Introspector.getBeanInfo(theClass); + PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); + + for (PropertyDescriptor pd : pds) { + if (pd.getName().equals(propertyName)) { + return pd; + } + } + return null; + } + + private Method findStaticGetter (Class theClass, String propertyName) { + Method[] methods = theClass.getMethods(); + for (Method method : methods) { + int modifiers = method.getModifiers(); + + if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) { + String methodName = method.getName(); + String postfix = null; + + if (methodName.startsWith("get")) { //$NON-NLS-1$ + postfix = methodName.substring(3); + } else if (methodName.startsWith("is")) { //$NON-NLS-1$ + postfix = methodName.substring(2); + } else { + continue; + } + + if ((method.getParameterTypes().length != 0) || (method.getReturnType() == void.class)) { + continue; + } + + postfix = Introspector.decapitalize(postfix); + if (postfix.equals(propertyName)) { + return method; + } + } + } + return null; + } + + private Method findMethod (Class type, Object[] args) { + Method[] methods = type.getMethods(); + for (Method method : methods) { + if (action.equals(method.getName()) && canInvokeWithArguments(method, args)) { + return method; + } + } + return null; + } + + private static boolean canInvokeWithArguments (Method method, Object[] arguments) { + Class[] parameterTypes = method.getParameterTypes(); + if (parameterTypes.length != arguments.length) { + return false; + } + + for (int index = 0; index < arguments.length; index++) { + Class argumentType = (arguments[index] == null) ? null : arguments[index].getClass(); + if (argumentType == null || BeansUtils.isPrimitiveWrapper(argumentType, parameterTypes[index])) { + continue; + } + if (!argumentType.isAssignableFrom(parameterTypes[index])) { + return false; + } + } + return true; + } + + private static boolean equalNames (Method m1, Method m2) { + return m1.getName().equals(m2.getName()); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/EventSetDescriptor.java b/extensions/beans/src/com/badlogic/gdx/beans/EventSetDescriptor.java index 856b262e1e2..973004cf571 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/EventSetDescriptor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/EventSetDescriptor.java @@ -17,421 +17,367 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.EventSetDescriptor; -import com.badlogic.gdx.beans.FeatureDescriptor; -import com.badlogic.gdx.beans.IntrospectionException; -import com.badlogic.gdx.beans.MethodDescriptor; - import java.lang.reflect.Method; import java.util.ArrayList; import java.util.TooManyListenersException; + import org.apache.harmony.beans.internal.nls.Messages; public class EventSetDescriptor extends FeatureDescriptor { - private Class listenerType; - - private ArrayList listenerMethodDescriptors; - - private Method[] listenerMethods; - - private Method getListenerMethod; - - private Method addListenerMethod; - - private Method removeListenerMethod; - - private boolean unicast; - - private boolean inDefaultEventSet = true; - - public EventSetDescriptor(Class sourceClass, String eventSetName, - Class listenerType, String listenerMethodName) - throws IntrospectionException { - checkNotNull(sourceClass, eventSetName, listenerType, - listenerMethodName); - setName(eventSetName); - this.listenerType = listenerType; - - Method method = findListenerMethodByName(listenerMethodName); - checkEventType(eventSetName, method); - listenerMethodDescriptors = new ArrayList(); - listenerMethodDescriptors.add(new MethodDescriptor(method)); - addListenerMethod = findMethodByPrefix(sourceClass, "add", ""); //$NON-NLS-1$ //$NON-NLS-2$ - removeListenerMethod = findMethodByPrefix(sourceClass, "remove", ""); //$NON-NLS-1$ //$NON-NLS-2$ - - if (addListenerMethod == null || removeListenerMethod == null) { - throw new IntrospectionException(Messages.getString("beans.38")); //$NON-NLS-1$ - } - - getListenerMethod = findMethodByPrefix(sourceClass, "get", "s"); //$NON-NLS-1$ //$NON-NLS-2$ - unicast = isUnicastByDefault(addListenerMethod); - } - - public EventSetDescriptor(Class sourceClass, String eventSetName, - Class listenerType, String[] listenerMethodNames, - String addListenerMethodName, String removeListenerMethodName) - throws IntrospectionException { - this(sourceClass, eventSetName, listenerType, listenerMethodNames, - addListenerMethodName, removeListenerMethodName, null); - - } - - public EventSetDescriptor(Class sourceClass, String eventSetName, - Class listenerType, String[] listenerMethodNames, - String addListenerMethodName, String removeListenerMethodName, - String getListenerMethodName) throws IntrospectionException { - - checkNotNull(sourceClass, eventSetName, listenerType, - listenerMethodNames); - - setName(eventSetName); - this.listenerType = listenerType; - - listenerMethodDescriptors = new ArrayList(); - for (String element : listenerMethodNames) { - Method m = findListenerMethodByName(element); - - // checkEventType(eventSetName, m); - listenerMethodDescriptors.add(new MethodDescriptor(m)); - } - - if (addListenerMethodName != null) { - this.addListenerMethod = findAddRemoveListenerMethod(sourceClass, - addListenerMethodName); - } - if (removeListenerMethodName != null) { - this.removeListenerMethod = findAddRemoveListenerMethod( - sourceClass, removeListenerMethodName); - } - if (getListenerMethodName != null) { - this.getListenerMethod = findGetListenerMethod(sourceClass, - getListenerMethodName); - } - this.unicast = isUnicastByDefault(addListenerMethod); - } - - private Method findListenerMethodByName(String listenerMethodName) - throws IntrospectionException { - Method result = null; - Method[] methods = listenerType.getMethods(); - for (Method method : methods) { - if (listenerMethodName.equals(method.getName())) { - Class[] paramTypes = method.getParameterTypes(); - if (paramTypes.length == 1 - && paramTypes[0].getName().endsWith("Event")) { //$NON-NLS-1$ - result = method; - break; - } - - } - } - if (null == result) { - throw new IntrospectionException(Messages.getString("beans.31", //$NON-NLS-1$ - listenerMethodName, listenerType.getName())); - } - return result; - } - - public EventSetDescriptor(String eventSetName, Class listenerType, - Method[] listenerMethods, Method addListenerMethod, - Method removeListenerMethod) throws IntrospectionException { - - this(eventSetName, listenerType, listenerMethods, addListenerMethod, - removeListenerMethod, null); - } - - public EventSetDescriptor(String eventSetName, Class listenerType, - Method[] listenerMethods, Method addListenerMethod, - Method removeListenerMethod, Method getListenerMethod) - throws IntrospectionException { - - setName(eventSetName); - this.listenerType = listenerType; - - this.listenerMethods = listenerMethods; - if (listenerMethods != null) { - listenerMethodDescriptors = new ArrayList(); - - for (Method element : listenerMethods) { - // XXX do we need this check? - // checkEventType(eventSetName, element); - // if (checkMethod(listenerType, element)) { - this.listenerMethodDescriptors - .add(new MethodDescriptor(element)); - // } - } - } - - this.addListenerMethod = addListenerMethod; - this.removeListenerMethod = removeListenerMethod; - this.getListenerMethod = getListenerMethod; - this.unicast = isUnicastByDefault(addListenerMethod); - } - - public EventSetDescriptor(String eventSetName, Class listenerType, - MethodDescriptor[] listenerMethodDescriptors, - Method addListenerMethod, Method removeListenerMethod) - throws IntrospectionException { - - this(eventSetName, listenerType, null, addListenerMethod, - removeListenerMethod, null); - - if (listenerMethodDescriptors != null) { - this.listenerMethodDescriptors = new ArrayList(); - - for (MethodDescriptor element : listenerMethodDescriptors) { - this.listenerMethodDescriptors.add(element); - } - } - } - - // ensures that there is no nulls - @SuppressWarnings("nls") - private void checkNotNull(Object sourceClass, Object eventSetName, - Object alistenerType, Object listenerMethodName) { - if (sourceClass == null) { - throw new NullPointerException(Messages.getString("beans.0C")); - } - if (eventSetName == null) { - throw new NullPointerException(Messages.getString("beans.53")); - } - if (alistenerType == null) { - throw new NullPointerException(Messages.getString("beans.54")); - } - if (listenerMethodName == null) { - throw new NullPointerException(Messages.getString("beans.52")); - } - } - - /** - * Checks that given listener method has an argument of the valid type. - * - * @param eventSetName - * event set name - * @param listenerMethod - * listener method - * @throws IntrospectionException - * if check fails - */ - private static void checkEventType(String eventSetName, - Method listenerMethod) throws IntrospectionException { - Class[] params = listenerMethod.getParameterTypes(); - String firstParamTypeName = null; - String eventTypeName = prepareEventTypeName(eventSetName); - - if (params.length > 0) { - firstParamTypeName = extractShortClassName(params[0] - .getName()); - } - - if (firstParamTypeName == null - || !firstParamTypeName.equals(eventTypeName)) { - throw new IntrospectionException(Messages.getString("beans.51", //$NON-NLS-1$ - listenerMethod.getName(), eventTypeName)); - } - } - - /** - * @param fullClassName full name of the class - * @return name with package and encapsulating class info omitted - */ - private static String extractShortClassName(String fullClassName) { - int k = fullClassName.lastIndexOf('$'); - k = (k == -1 ? fullClassName.lastIndexOf('.') : k); - return fullClassName.substring(k + 1); - } - - private static String prepareEventTypeName(String eventSetName) { - StringBuilder sb = new StringBuilder(); - - if (eventSetName != null && eventSetName.length() > 0) { - sb.append(Character.toUpperCase(eventSetName.charAt(0))); - - if (eventSetName.length() > 1) { - sb.append(eventSetName.substring(1)); - } - } - - sb.append("Event"); //$NON-NLS-1$ - return sb.toString(); - } - - public Method[] getListenerMethods() { - if (listenerMethods != null) { - return listenerMethods; - } - - if (listenerMethodDescriptors != null) { - listenerMethods = new Method[listenerMethodDescriptors.size()]; - int index = 0; - for (MethodDescriptor md : listenerMethodDescriptors) { - listenerMethods[index++] = md.getMethod(); - } - return listenerMethods; - } - return null; - } - - public MethodDescriptor[] getListenerMethodDescriptors() { - return listenerMethodDescriptors == null ? null - : listenerMethodDescriptors.toArray(new MethodDescriptor[0]); - } - - public Method getRemoveListenerMethod() { - return removeListenerMethod; - } - - public Method getGetListenerMethod() { - return getListenerMethod; - } - - public Method getAddListenerMethod() { - return addListenerMethod; - } - - public Class getListenerType() { - return listenerType; - } - - public void setUnicast(boolean unicast) { - this.unicast = unicast; - } - - public void setInDefaultEventSet(boolean inDefaultEventSet) { - this.inDefaultEventSet = inDefaultEventSet; - } - - public boolean isUnicast() { - return unicast; - } - - public boolean isInDefaultEventSet() { - return inDefaultEventSet; - } - - /** - * Searches for {add|remove}Listener methods in the event source. Parameter - * check is also performed. - * - * @param sourceClass - * event source class - * @param methodName - * method name to search - * @return found method - * @throws IntrospectionException - * if no valid method found - */ - private Method findAddRemoveListenerMethod(Class sourceClass, - String methodName) throws IntrospectionException { - try { - return sourceClass.getMethod(methodName, listenerType); - } catch (NoSuchMethodException e) { - return findAddRemoveListnerMethodWithLessCheck(sourceClass, - methodName); - } catch (Exception e) { - throw new IntrospectionException(Messages.getString("beans.31", //$NON-NLS-1$ - methodName, listenerType.getName())); - } - } - - private Method findAddRemoveListnerMethodWithLessCheck( - Class sourceClass, String methodName) - throws IntrospectionException { - Method[] methods = sourceClass.getMethods(); - Method result = null; - for (Method method : methods) { - if (method.getName().equals(methodName)) { - Class[] paramTypes = method.getParameterTypes(); - if (paramTypes.length == 1) { - result = method; - break; - } - } - } - if (null == result) { - throw new IntrospectionException(Messages.getString("beans.31", //$NON-NLS-1$ - methodName, listenerType.getName())); - } - return result; - } - - /** - * @param sourceClass - * class of event source - * @param methodName - * name of the custom getListeners() method - * @return found Method object for custom getListener or null if nothing is - * found - */ - private Method findGetListenerMethod(Class sourceClass, String methodName) { - try { - return sourceClass.getMethod(methodName); - } catch (Exception e) { - // RI keeps silence here and just returns null - return null; - } - } - - private Method findMethodByPrefix(Class sourceClass, String prefix, - String postfix) { - String shortName = listenerType.getName(); - if (listenerType.getPackage() != null) { - shortName = shortName.substring(listenerType.getPackage().getName() - .length() + 1); - } - String methodName = prefix + shortName + postfix; - try { - if ("get".equals(prefix)) { //$NON-NLS-1$ - return sourceClass.getMethod(methodName); - } - } catch (NoSuchMethodException nsme) { - return null; - } - Method[] methods = sourceClass.getMethods(); - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(methodName)) { - Class[] paramTypes = methods[i].getParameterTypes(); - if (paramTypes.length == 1) { - return methods[i]; - } - } - } - return null; - } - - private static boolean isUnicastByDefault(Method addMethod) { - if (addMethod != null) { - Class[] exceptionTypes = addMethod.getExceptionTypes(); - for (Class element : exceptionTypes) { - if (element.equals(TooManyListenersException.class)) { - return true; - } - } - } - return false; - } - - void merge(EventSetDescriptor event) { - super.merge(event); - if (addListenerMethod == null) { - addListenerMethod = event.addListenerMethod; - } - if (getListenerMethod == null) { - getListenerMethod = event.getListenerMethod; - } - if (listenerMethodDescriptors == null) { - listenerMethodDescriptors = event.listenerMethodDescriptors; - } - if (listenerMethods == null) { - listenerMethods = event.listenerMethods; - } - if (listenerType == null) { - listenerType = event.listenerType; - } - - if (removeListenerMethod == null) { - removeListenerMethod = event.removeListenerMethod; - } - inDefaultEventSet &= event.inDefaultEventSet; - } + private Class listenerType; + + private ArrayList listenerMethodDescriptors; + + private Method[] listenerMethods; + + private Method getListenerMethod; + + private Method addListenerMethod; + + private Method removeListenerMethod; + + private boolean unicast; + + private boolean inDefaultEventSet = true; + + public EventSetDescriptor (Class sourceClass, String eventSetName, Class listenerType, String listenerMethodName) + throws IntrospectionException { + checkNotNull(sourceClass, eventSetName, listenerType, listenerMethodName); + setName(eventSetName); + this.listenerType = listenerType; + + Method method = findListenerMethodByName(listenerMethodName); + checkEventType(eventSetName, method); + listenerMethodDescriptors = new ArrayList(); + listenerMethodDescriptors.add(new MethodDescriptor(method)); + addListenerMethod = findMethodByPrefix(sourceClass, "add", ""); //$NON-NLS-1$ //$NON-NLS-2$ + removeListenerMethod = findMethodByPrefix(sourceClass, "remove", ""); //$NON-NLS-1$ //$NON-NLS-2$ + + if (addListenerMethod == null || removeListenerMethod == null) { + throw new IntrospectionException(Messages.getString("beans.38")); //$NON-NLS-1$ + } + + getListenerMethod = findMethodByPrefix(sourceClass, "get", "s"); //$NON-NLS-1$ //$NON-NLS-2$ + unicast = isUnicastByDefault(addListenerMethod); + } + + public EventSetDescriptor (Class sourceClass, String eventSetName, Class listenerType, String[] listenerMethodNames, + String addListenerMethodName, String removeListenerMethodName) throws IntrospectionException { + this(sourceClass, eventSetName, listenerType, listenerMethodNames, addListenerMethodName, removeListenerMethodName, null); + + } + + public EventSetDescriptor (Class sourceClass, String eventSetName, Class listenerType, String[] listenerMethodNames, + String addListenerMethodName, String removeListenerMethodName, String getListenerMethodName) throws IntrospectionException { + + checkNotNull(sourceClass, eventSetName, listenerType, listenerMethodNames); + + setName(eventSetName); + this.listenerType = listenerType; + + listenerMethodDescriptors = new ArrayList(); + for (String element : listenerMethodNames) { + Method m = findListenerMethodByName(element); + + // checkEventType(eventSetName, m); + listenerMethodDescriptors.add(new MethodDescriptor(m)); + } + + if (addListenerMethodName != null) { + this.addListenerMethod = findAddRemoveListenerMethod(sourceClass, addListenerMethodName); + } + if (removeListenerMethodName != null) { + this.removeListenerMethod = findAddRemoveListenerMethod(sourceClass, removeListenerMethodName); + } + if (getListenerMethodName != null) { + this.getListenerMethod = findGetListenerMethod(sourceClass, getListenerMethodName); + } + this.unicast = isUnicastByDefault(addListenerMethod); + } + + private Method findListenerMethodByName (String listenerMethodName) throws IntrospectionException { + Method result = null; + Method[] methods = listenerType.getMethods(); + for (Method method : methods) { + if (listenerMethodName.equals(method.getName())) { + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 1 && paramTypes[0].getName().endsWith("Event")) { //$NON-NLS-1$ + result = method; + break; + } + + } + } + if (null == result) { + throw new IntrospectionException(Messages.getString("beans.31", //$NON-NLS-1$ + listenerMethodName, listenerType.getName())); + } + return result; + } + + public EventSetDescriptor (String eventSetName, Class listenerType, Method[] listenerMethods, Method addListenerMethod, + Method removeListenerMethod) throws IntrospectionException { + + this(eventSetName, listenerType, listenerMethods, addListenerMethod, removeListenerMethod, null); + } + + public EventSetDescriptor (String eventSetName, Class listenerType, Method[] listenerMethods, Method addListenerMethod, + Method removeListenerMethod, Method getListenerMethod) throws IntrospectionException { + + setName(eventSetName); + this.listenerType = listenerType; + + this.listenerMethods = listenerMethods; + if (listenerMethods != null) { + listenerMethodDescriptors = new ArrayList(); + + for (Method element : listenerMethods) { + // XXX do we need this check? + // checkEventType(eventSetName, element); + // if (checkMethod(listenerType, element)) { + this.listenerMethodDescriptors.add(new MethodDescriptor(element)); + // } + } + } + + this.addListenerMethod = addListenerMethod; + this.removeListenerMethod = removeListenerMethod; + this.getListenerMethod = getListenerMethod; + this.unicast = isUnicastByDefault(addListenerMethod); + } + + public EventSetDescriptor (String eventSetName, Class listenerType, MethodDescriptor[] listenerMethodDescriptors, + Method addListenerMethod, Method removeListenerMethod) throws IntrospectionException { + + this(eventSetName, listenerType, null, addListenerMethod, removeListenerMethod, null); + + if (listenerMethodDescriptors != null) { + this.listenerMethodDescriptors = new ArrayList(); + + for (MethodDescriptor element : listenerMethodDescriptors) { + this.listenerMethodDescriptors.add(element); + } + } + } + + // ensures that there is no nulls + @SuppressWarnings("nls") + private void checkNotNull (Object sourceClass, Object eventSetName, Object alistenerType, Object listenerMethodName) { + if (sourceClass == null) { + throw new NullPointerException(Messages.getString("beans.0C")); + } + if (eventSetName == null) { + throw new NullPointerException(Messages.getString("beans.53")); + } + if (alistenerType == null) { + throw new NullPointerException(Messages.getString("beans.54")); + } + if (listenerMethodName == null) { + throw new NullPointerException(Messages.getString("beans.52")); + } + } + + /** Checks that given listener method has an argument of the valid type. + * + * @param eventSetName event set name + * @param listenerMethod listener method + * @throws IntrospectionException if check fails */ + private static void checkEventType (String eventSetName, Method listenerMethod) throws IntrospectionException { + Class[] params = listenerMethod.getParameterTypes(); + String firstParamTypeName = null; + String eventTypeName = prepareEventTypeName(eventSetName); + + if (params.length > 0) { + firstParamTypeName = extractShortClassName(params[0].getName()); + } + + if (firstParamTypeName == null || !firstParamTypeName.equals(eventTypeName)) { + throw new IntrospectionException(Messages.getString("beans.51", //$NON-NLS-1$ + listenerMethod.getName(), eventTypeName)); + } + } + + /** @param fullClassName full name of the class + * @return name with package and encapsulating class info omitted */ + private static String extractShortClassName (String fullClassName) { + int k = fullClassName.lastIndexOf('$'); + k = (k == -1 ? fullClassName.lastIndexOf('.') : k); + return fullClassName.substring(k + 1); + } + + private static String prepareEventTypeName (String eventSetName) { + StringBuilder sb = new StringBuilder(); + + if (eventSetName != null && eventSetName.length() > 0) { + sb.append(Character.toUpperCase(eventSetName.charAt(0))); + + if (eventSetName.length() > 1) { + sb.append(eventSetName.substring(1)); + } + } + + sb.append("Event"); //$NON-NLS-1$ + return sb.toString(); + } + + public Method[] getListenerMethods () { + if (listenerMethods != null) { + return listenerMethods; + } + + if (listenerMethodDescriptors != null) { + listenerMethods = new Method[listenerMethodDescriptors.size()]; + int index = 0; + for (MethodDescriptor md : listenerMethodDescriptors) { + listenerMethods[index++] = md.getMethod(); + } + return listenerMethods; + } + return null; + } + + public MethodDescriptor[] getListenerMethodDescriptors () { + return listenerMethodDescriptors == null ? null : listenerMethodDescriptors.toArray(new MethodDescriptor[0]); + } + + public Method getRemoveListenerMethod () { + return removeListenerMethod; + } + + public Method getGetListenerMethod () { + return getListenerMethod; + } + + public Method getAddListenerMethod () { + return addListenerMethod; + } + + public Class getListenerType () { + return listenerType; + } + + public void setUnicast (boolean unicast) { + this.unicast = unicast; + } + + public void setInDefaultEventSet (boolean inDefaultEventSet) { + this.inDefaultEventSet = inDefaultEventSet; + } + + public boolean isUnicast () { + return unicast; + } + + public boolean isInDefaultEventSet () { + return inDefaultEventSet; + } + + /** Searches for {add|remove}Listener methods in the event source. Parameter check is also performed. + * + * @param sourceClass event source class + * @param methodName method name to search + * @return found method + * @throws IntrospectionException if no valid method found */ + private Method findAddRemoveListenerMethod (Class sourceClass, String methodName) throws IntrospectionException { + try { + return sourceClass.getMethod(methodName, listenerType); + } catch (NoSuchMethodException e) { + return findAddRemoveListnerMethodWithLessCheck(sourceClass, methodName); + } catch (Exception e) { + throw new IntrospectionException(Messages.getString("beans.31", //$NON-NLS-1$ + methodName, listenerType.getName())); + } + } + + private Method findAddRemoveListnerMethodWithLessCheck (Class sourceClass, String methodName) throws IntrospectionException { + Method[] methods = sourceClass.getMethods(); + Method result = null; + for (Method method : methods) { + if (method.getName().equals(methodName)) { + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 1) { + result = method; + break; + } + } + } + if (null == result) { + throw new IntrospectionException(Messages.getString("beans.31", //$NON-NLS-1$ + methodName, listenerType.getName())); + } + return result; + } + + /** @param sourceClass class of event source + * @param methodName name of the custom getListeners() method + * @return found Method object for custom getListener or null if nothing is found */ + private Method findGetListenerMethod (Class sourceClass, String methodName) { + try { + return sourceClass.getMethod(methodName); + } catch (Exception e) { + // RI keeps silence here and just returns null + return null; + } + } + + private Method findMethodByPrefix (Class sourceClass, String prefix, String postfix) { + String shortName = listenerType.getName(); + if (listenerType.getPackage() != null) { + shortName = shortName.substring(listenerType.getPackage().getName().length() + 1); + } + String methodName = prefix + shortName + postfix; + try { + if ("get".equals(prefix)) { //$NON-NLS-1$ + return sourceClass.getMethod(methodName); + } + } catch (NoSuchMethodException nsme) { + return null; + } + Method[] methods = sourceClass.getMethods(); + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(methodName)) { + Class[] paramTypes = methods[i].getParameterTypes(); + if (paramTypes.length == 1) { + return methods[i]; + } + } + } + return null; + } + + private static boolean isUnicastByDefault (Method addMethod) { + if (addMethod != null) { + Class[] exceptionTypes = addMethod.getExceptionTypes(); + for (Class element : exceptionTypes) { + if (element.equals(TooManyListenersException.class)) { + return true; + } + } + } + return false; + } + + void merge (EventSetDescriptor event) { + super.merge(event); + if (addListenerMethod == null) { + addListenerMethod = event.addListenerMethod; + } + if (getListenerMethod == null) { + getListenerMethod = event.getListenerMethod; + } + if (listenerMethodDescriptors == null) { + listenerMethodDescriptors = event.listenerMethodDescriptors; + } + if (listenerMethods == null) { + listenerMethods = event.listenerMethods; + } + if (listenerType == null) { + listenerType = event.listenerType; + } + + if (removeListenerMethod == null) { + removeListenerMethod = event.removeListenerMethod; + } + inDefaultEventSet &= event.inDefaultEventSet; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/ExceptionListener.java b/extensions/beans/src/com/badlogic/gdx/beans/ExceptionListener.java index 66eb194bb0b..40c9476914a 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/ExceptionListener.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/ExceptionListener.java @@ -19,5 +19,5 @@ public interface ExceptionListener { - public void exceptionThrown(Exception e); + public void exceptionThrown (Exception e); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/Expression.java b/extensions/beans/src/com/badlogic/gdx/beans/Expression.java index 7295ff63199..7402c236725 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/Expression.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/Expression.java @@ -17,58 +17,54 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Statement; - import org.apache.harmony.beans.BeansUtils; public class Expression extends Statement { - boolean valueIsDefined = false; + boolean valueIsDefined = false; - Object value; + Object value; - public Expression(Object value, Object target, String methodName, - Object[] arguments) { - super(target, methodName, arguments); - this.value = value; - this.valueIsDefined = true; - } + public Expression (Object value, Object target, String methodName, Object[] arguments) { + super(target, methodName, arguments); + this.value = value; + this.valueIsDefined = true; + } - public Expression(Object target, String methodName, Object[] arguments) { - super(target, methodName, arguments); - this.value = null; - this.valueIsDefined = false; - } + public Expression (Object target, String methodName, Object[] arguments) { + super(target, methodName, arguments); + this.value = null; + this.valueIsDefined = false; + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (!valueIsDefined) { - sb.append(""); //$NON-NLS-1$ - } else { - if (value == null) { - sb.append(BeansUtils.NULL); - } else { - Class clazz = value.getClass(); - sb.append(clazz == String.class ? BeansUtils.QUOTE : BeansUtils - .idOfClass(clazz)); - } - } - sb.append('='); - sb.append(super.toString()); - return sb.toString(); - } + @Override + public String toString () { + StringBuilder sb = new StringBuilder(); + if (!valueIsDefined) { + sb.append(""); //$NON-NLS-1$ + } else { + if (value == null) { + sb.append(BeansUtils.NULL); + } else { + Class clazz = value.getClass(); + sb.append(clazz == String.class ? BeansUtils.QUOTE : BeansUtils.idOfClass(clazz)); + } + } + sb.append('='); + sb.append(super.toString()); + return sb.toString(); + } - public void setValue(Object value) { - this.value = value; - this.valueIsDefined = true; - } + public void setValue (Object value) { + this.value = value; + this.valueIsDefined = true; + } - public Object getValue() throws Exception { - if (!valueIsDefined) { - value = invokeMethod(); - valueIsDefined = true; - } - return value; - } -} \ No newline at end of file + public Object getValue () throws Exception { + if (!valueIsDefined) { + value = invokeMethod(); + valueIsDefined = true; + } + return value; + } +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/FeatureDescriptor.java b/extensions/beans/src/com/badlogic/gdx/beans/FeatureDescriptor.java index 516fb719fcd..a6a1fcfed68 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/FeatureDescriptor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/FeatureDescriptor.java @@ -17,235 +17,189 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.FeatureDescriptor; - import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; -/** - * Common base class for Descriptors. - */ +/** Common base class for Descriptors. */ public class FeatureDescriptor { - private Map values; - - boolean preferred, hidden, expert; - - String shortDescription; - - String name; - - String displayName; - - /** - *

    - * Constructs an instance. - *

    - */ - public FeatureDescriptor() { - this.values = new HashMap(); - } - - /** - *

    - * Sets the value for the named attribute. - *

    - * - * @param attributeName - * The name of the attribute to set a value with. - * @param value - * The value to set. - */ - public void setValue(String attributeName, Object value) { - if (attributeName == null || value == null) { - throw new NullPointerException(); - } - values.put(attributeName, value); - } - - /** - *

    - * Gets the value associated with the named attribute. - *

    - * - * @param attributeName - * The name of the attribute to get a value for. - * @return The attribute's value. - */ - public Object getValue(String attributeName) { - if (attributeName != null) { - return values.get(attributeName); - } - return null; - } - - /** - *

    - * Enumerates the attribute names. - *

    - * - * @return An instance of {@link Enumeration}. - */ - public Enumeration attributeNames() { - // Create a new list, so that the references are copied - return Collections.enumeration(new LinkedList(values.keySet())); - } - - /** - *

    - * Sets the short description. - *

    - * - * @param text - * The description to set. - */ - public void setShortDescription(String text) { - this.shortDescription = text; - } - - /** - *

    - * Sets the name. - *

    - * - * @param name - * The name to set. - */ - public void setName(String name) { - this.name = name; - } - - /** - *

    - * Sets the display name. - *

    - * - * @param displayName - * The display name to set. - */ - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - /** - *

    - * Gets the short description or {@link #getDisplayName()} if not set. - *

    - * - * @return The description. - */ - public String getShortDescription() { - return shortDescription == null ? getDisplayName() : shortDescription; - } - - /** - *

    - * Gets the name. - *

    - * - * @return The name. - */ - public String getName() { - return name; - } - - /** - *

    - * Gets the display name or {@link #getName()} if not set. - *

    - * - * @return The display name. - */ - public String getDisplayName() { - return displayName == null ? getName() : displayName; - } - - /** - *

    - * Sets the preferred indicator. - *

    - * - * @param preferred - * true if preferred, false - * otherwise. - */ - public void setPreferred(boolean preferred) { - this.preferred = preferred; - } - - /** - *

    - * Sets the hidden indicator. - *

    - * - * @param hidden - * true if hidden, false otherwise. - */ - public void setHidden(boolean hidden) { - this.hidden = hidden; - } - - /** - *

    - * Sets the expert indicator. - *

    - * - * @param expert - * true if expert, false otherwise. - */ - public void setExpert(boolean expert) { - this.expert = expert; - } - - /** - *

    - * Indicates if this feature is preferred. - *

    - * - * @return true if preferred, false otherwise. - */ - public boolean isPreferred() { - return preferred; - } - - /** - *

    - * Indicates if this feature is hidden. - *

    - * - * @return true if hidden, false otherwise. - */ - public boolean isHidden() { - return hidden; - } - - /** - *

    - * Indicates if this feature is an expert feature. - *

    - * - * @return true if hidden, false otherwise. - */ - public boolean isExpert() { - return expert; - } - - void merge(FeatureDescriptor feature){ - assert(name.equals(feature.name)); - expert |= feature.expert; - hidden |= feature.hidden; - preferred |= feature.preferred; - if(shortDescription == null){ - shortDescription = feature.shortDescription; - } - if(name == null){ - name = feature.name; - } - if(displayName == null){ - displayName = feature.displayName; - } - } + private Map values; + + boolean preferred, hidden, expert; + + String shortDescription; + + String name; + + String displayName; + + /**

    + * Constructs an instance. + *

    */ + public FeatureDescriptor () { + this.values = new HashMap(); + } + + /**

    + * Sets the value for the named attribute. + *

    + * + * @param attributeName The name of the attribute to set a value with. + * @param value The value to set. */ + public void setValue (String attributeName, Object value) { + if (attributeName == null || value == null) { + throw new NullPointerException(); + } + values.put(attributeName, value); + } + + /**

    + * Gets the value associated with the named attribute. + *

    + * + * @param attributeName The name of the attribute to get a value for. + * @return The attribute's value. */ + public Object getValue (String attributeName) { + if (attributeName != null) { + return values.get(attributeName); + } + return null; + } + + /**

    + * Enumerates the attribute names. + *

    + * + * @return An instance of {@link Enumeration}. */ + public Enumeration attributeNames () { + // Create a new list, so that the references are copied + return Collections.enumeration(new LinkedList(values.keySet())); + } + + /**

    + * Sets the short description. + *

    + * + * @param text The description to set. */ + public void setShortDescription (String text) { + this.shortDescription = text; + } + + /**

    + * Sets the name. + *

    + * + * @param name The name to set. */ + public void setName (String name) { + this.name = name; + } + + /**

    + * Sets the display name. + *

    + * + * @param displayName The display name to set. */ + public void setDisplayName (String displayName) { + this.displayName = displayName; + } + + /**

    + * Gets the short description or {@link #getDisplayName()} if not set. + *

    + * + * @return The description. */ + public String getShortDescription () { + return shortDescription == null ? getDisplayName() : shortDescription; + } + + /**

    + * Gets the name. + *

    + * + * @return The name. */ + public String getName () { + return name; + } + + /**

    + * Gets the display name or {@link #getName()} if not set. + *

    + * + * @return The display name. */ + public String getDisplayName () { + return displayName == null ? getName() : displayName; + } + + /**

    + * Sets the preferred indicator. + *

    + * + * @param preferred true if preferred, false otherwise. */ + public void setPreferred (boolean preferred) { + this.preferred = preferred; + } + + /**

    + * Sets the hidden indicator. + *

    + * + * @param hidden true if hidden, false otherwise. */ + public void setHidden (boolean hidden) { + this.hidden = hidden; + } + + /**

    + * Sets the expert indicator. + *

    + * + * @param expert true if expert, false otherwise. */ + public void setExpert (boolean expert) { + this.expert = expert; + } + + /**

    + * Indicates if this feature is preferred. + *

    + * + * @return true if preferred, false otherwise. */ + public boolean isPreferred () { + return preferred; + } + + /**

    + * Indicates if this feature is hidden. + *

    + * + * @return true if hidden, false otherwise. */ + public boolean isHidden () { + return hidden; + } + + /**

    + * Indicates if this feature is an expert feature. + *

    + * + * @return true if hidden, false otherwise. */ + public boolean isExpert () { + return expert; + } + + void merge (FeatureDescriptor feature) { + assert (name.equals(feature.name)); + expert |= feature.expert; + hidden |= feature.hidden; + preferred |= feature.preferred; + if (shortDescription == null) { + shortDescription = feature.shortDescription; + } + if (name == null) { + name = feature.name; + } + if (displayName == null) { + displayName = feature.displayName; + } + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/FieldPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/FieldPersistenceDelegate.java index 5571ea4ff3f..750d71c5373 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/FieldPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/FieldPersistenceDelegate.java @@ -17,41 +17,35 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - import java.lang.reflect.Field; -/** - * This is a persistence delegate for the {@link java.lang.reflect.Field} class. - */ +/** This is a persistence delegate for the {@link java.lang.reflect.Field} class. */ class FieldPersistenceDelegate extends PersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder out) { - // should not be null or have a type other than Field - assert oldInstance instanceof Field : oldInstance; - Field oldField = (Field) oldInstance; - Class declClass = oldField.getDeclaringClass(); - return new Expression(oldField, declClass, "getField", //$NON-NLS-1$ - new Object[] { oldField.getName() }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder out) { + // should not be null or have a type other than Field + assert oldInstance instanceof Field : oldInstance; + Field oldField = (Field)oldInstance; + Class declClass = oldField.getDeclaringClass(); + return new Expression(oldField, declClass, "getField", //$NON-NLS-1$ + new Object[] {oldField.getName()}); + } - @Override - protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { - // check for consistency - assert oldInstance instanceof Field : oldInstance; - assert newInstance instanceof Field : newInstance; - assert newInstance.equals(oldInstance); - } + @Override + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder out) { + // check for consistency + assert oldInstance instanceof Field : oldInstance; + assert newInstance instanceof Field : newInstance; + assert newInstance.equals(oldInstance); + } - @Override - protected boolean mutatesTo(Object oldInstance, Object newInstance) { - assert oldInstance instanceof Field : oldInstance; - if (!(newInstance instanceof Field)) { - // if null or not a Field - return false; - } - return oldInstance.equals(newInstance); - } + @Override + protected boolean mutatesTo (Object oldInstance, Object newInstance) { + assert oldInstance instanceof Field : oldInstance; + if (!(newInstance instanceof Field)) { + // if null or not a Field + return false; + } + return oldInstance.equals(newInstance); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyChangeEvent.java b/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyChangeEvent.java index 7ca915d1be4..70b6bc1d139 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyChangeEvent.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyChangeEvent.java @@ -17,52 +17,34 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; - -/** - * A type of {@link PropertyChangeEvent} that indicates that an indexed property - * has changed. +/** A type of {@link PropertyChangeEvent} that indicates that an indexed property has changed. * - * @since 1.5 - */ + * @since 1.5 */ public class IndexedPropertyChangeEvent extends PropertyChangeEvent { - private static final long serialVersionUID = -320227448495806870L; + private static final long serialVersionUID = -320227448495806870L; - private final int index; + private final int index; - /** - * Creates a new property changed event with an indication of the property - * index. - * - * @param source - * the changed bean. - * @param propertyName - * the changed property, or null to indicate an - * unspecified set of the properties have changed. - * @param oldValue - * the previous value of the property, or null if - * the propertyName is null or the - * previous value is unknown. - * @param newValue - * the new value of the property, or null if the - * propertyName is null or the new - * value is unknown.. - * @param index - * the index of the property. - */ - public IndexedPropertyChangeEvent(Object source, String propertyName, - Object oldValue, Object newValue, int index) { - super(source, propertyName, oldValue, newValue); - this.index = index; - } + /** Creates a new property changed event with an indication of the property index. + * + * @param source the changed bean. + * @param propertyName the changed property, or null to indicate an unspecified set of the properties have + * changed. + * @param oldValue the previous value of the property, or null if the propertyName is + * null or the previous value is unknown. + * @param newValue the new value of the property, or null if the propertyName is null or + * the new value is unknown.. + * @param index the index of the property. */ + public IndexedPropertyChangeEvent (Object source, String propertyName, Object oldValue, Object newValue, int index) { + super(source, propertyName, oldValue, newValue); + this.index = index; + } - /** - * Answer the index of the property that was changed in this event. - * - * @return The property element index. - */ - public int getIndex() { - return index; - } + /** Answer the index of the property that was changed in this event. + * + * @return The property element index. */ + public int getIndex () { + return index; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyDescriptor.java b/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyDescriptor.java index 04f8960760d..ece5b30959a 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyDescriptor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/IndexedPropertyDescriptor.java @@ -17,10 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.IndexedPropertyDescriptor; -import com.badlogic.gdx.beans.IntrospectionException; -import com.badlogic.gdx.beans.PropertyDescriptor; - import java.lang.reflect.Method; import org.apache.harmony.beans.BeansUtils; @@ -28,360 +24,301 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { - private Class indexedPropertyType; - - private Method indexedGetter; - - private Method indexedSetter; - - /** - * Constructs a new instance of IndexedPropertyDescriptor. - * - * @param propertyName - * the specified indexed property's name. - * @param beanClass - * the bean class - * @param getterName - * the name of the array getter - * @param setterName - * the name of the array setter - * @param indexedGetterName - * the name of the indexed getter. - * @param indexedSetterName - * the name of the indexed setter. - * @throws IntrospectionException - */ - public IndexedPropertyDescriptor(String propertyName, Class beanClass, - String getterName, String setterName, String indexedGetterName, - String indexedSetterName) throws IntrospectionException { - super(propertyName, beanClass, getterName, setterName); - setIndexedByName(beanClass, indexedGetterName, indexedSetterName); - } - - private void setIndexedByName(Class beanClass, String indexedGetterName, - String indexedSetterName) throws IntrospectionException { - - String theIndexedGetterName = indexedGetterName; - if (theIndexedGetterName == null) { - if (indexedSetterName != null) { - setIndexedWriteMethod(beanClass, indexedSetterName); - } - } else { - if (theIndexedGetterName.length() == 0) { - theIndexedGetterName = "get" + name; //$NON-NLS-1$ - } - setIndexedReadMethod(beanClass, theIndexedGetterName); - if (indexedSetterName != null) { - setIndexedWriteMethod(beanClass, indexedSetterName, - indexedPropertyType); - } - } - - if (!isCompatible()) { - // beans.57=Property type is incompatible with the indexed property type - throw new IntrospectionException(Messages.getString("beans.57")); //$NON-NLS-1$ - } - } - - private boolean isCompatible() { - Class propertyType = getPropertyType(); - - if (propertyType == null) { - return true; - } - Class componentTypeOfProperty = propertyType.getComponentType(); - if (componentTypeOfProperty == null) { - return false; - } - if (indexedPropertyType == null) { - return false; - } - - return componentTypeOfProperty.getName().equals( - indexedPropertyType.getName()); - } - - /** - * Constructs a new instance of IndexedPropertyDescriptor. - * - * @param propertyName - * the specified indexed property's name. - * @param getter - * the array getter - * @param setter - * the array setter - * @param indexedGetter - * the indexed getter - * @param indexedSetter - * the indexed setter - * @throws IntrospectionException - */ - public IndexedPropertyDescriptor(String propertyName, Method getter, - Method setter, Method indexedGetter, Method indexedSetter) - throws IntrospectionException { - super(propertyName, getter, setter); - if (indexedGetter != null) { - internalSetIndexedReadMethod(indexedGetter); - internalSetIndexedWriteMethod(indexedSetter, true); - } else { - internalSetIndexedWriteMethod(indexedSetter, true); - internalSetIndexedReadMethod(indexedGetter); - } - - if (!isCompatible()) { - // beans.57=Property type is incompatible with the indexed property type - throw new IntrospectionException(Messages.getString("beans.57")); //$NON-NLS-1$ - } - } - - /** - * Constructs a new instance of IndexedPropertyDescriptor. - * - * @param propertyName - * the specified indexed property's name. - * @param beanClass - * the bean class. - * @throws IntrospectionException - */ - public IndexedPropertyDescriptor(String propertyName, Class beanClass) - throws IntrospectionException { - super(propertyName, beanClass); - setIndexedByName(beanClass, "get" //$NON-NLS-1$ - .concat(initialUpperCase(propertyName)), "set" //$NON-NLS-1$ - .concat(initialUpperCase(propertyName))); - } - - /** - * Sets the indexed getter as the specified method. - * - * @param indexedGetter - * the specified indexed getter. - * @throws IntrospectionException - */ - public void setIndexedReadMethod(Method indexedGetter) - throws IntrospectionException { - this.internalSetIndexedReadMethod(indexedGetter); - } - - /** - * Sets the indexed setter as the specified method. - * - * @param indexedSetter - * the specified indexed setter. - * @throws IntrospectionException - */ - public void setIndexedWriteMethod(Method indexedSetter) - throws IntrospectionException { - this.internalSetIndexedWriteMethod(indexedSetter, false); - } - - /** - * Obtains the indexed setter. - * - * @return the indexed setter. - */ - public Method getIndexedWriteMethod() { - return indexedSetter; - } - - /** - * Obtains the indexed getter. - * - * @return the indexed getter. - */ - public Method getIndexedReadMethod() { - return indexedGetter; - } - - /** - * Determines if this IndexedPropertyDescriptor is equal to - * the specified object. Two IndexedPropertyDescriptor s are - * equal if the reader, indexed reader, writer, indexed writer, property - * types, indexed property type, property editor and flags are equal. - * - * @param obj - * @return true if this indexed property descriptor is equal to the - * specified object. - */ - @Override - public boolean equals(Object obj) { - if (!(obj instanceof IndexedPropertyDescriptor)) { - return false; - } - - IndexedPropertyDescriptor other = (IndexedPropertyDescriptor) obj; - - return (super.equals(other) - && (indexedPropertyType == null ? other.indexedPropertyType == null - : indexedPropertyType.equals(other.indexedPropertyType)) - && (indexedGetter == null ? other.indexedGetter == null - : indexedGetter.equals(other.indexedGetter)) && (indexedSetter == null ? other.indexedSetter == null - : indexedSetter.equals(other.indexedSetter))); - } - - /** - * HashCode of the IndexedPropertyDescriptor - */ - @Override - public int hashCode() { - return super.hashCode() + BeansUtils.getHashCode(indexedPropertyType) - + BeansUtils.getHashCode(indexedGetter) - + BeansUtils.getHashCode(indexedSetter); - } - - /** - * Obtains the Class object of the indexed property type. - * - * @return the Class object of the indexed property type. - */ - public Class getIndexedPropertyType() { - return indexedPropertyType; - } - - private void setIndexedReadMethod(Class beanClass, String indexedGetterName) - throws IntrospectionException { - Method getter; - try { - getter = beanClass.getMethod(indexedGetterName, - new Class[] { Integer.TYPE }); - } catch (NoSuchMethodException exception) { - // beans.58=No such indexed read method - throw new IntrospectionException(Messages.getString("beans.58")); //$NON-NLS-1$ - } catch (SecurityException exception) { - // beans.59=Security violation accessing indexed read method - throw new IntrospectionException(Messages.getString("beans.59")); //$NON-NLS-1$ - } - internalSetIndexedReadMethod(getter); - } - - private void internalSetIndexedReadMethod(Method indexGetter) - throws IntrospectionException { - // Clearing the indexed read method. - if (indexGetter == null) { - if (indexedSetter == null) { - if (getPropertyType() != null) { - // beans.5A=Indexed method is not compatible with non indexed method - throw new IntrospectionException(Messages - .getString("beans.5A")); //$NON-NLS-1$ - } - indexedPropertyType = null; - } - this.indexedGetter = null; - return; - } - // Validate the indexed getter. - if ((indexGetter.getParameterTypes().length != 1) - || (indexGetter.getParameterTypes()[0] != Integer.TYPE)) { - // beans.5B=Indexed read method must take a single int argument - throw new IntrospectionException(Messages.getString("beans.5B")); //$NON-NLS-1$ - } - Class indexedReadType = indexGetter.getReturnType(); - if (indexedReadType == Void.TYPE) { - // beans.5B=Indexed read method must take a single int argument - throw new IntrospectionException(Messages.getString("beans.5B")); //$NON-NLS-1$ - } else if (indexedSetter != null - && indexGetter.getReturnType() != indexedSetter - .getParameterTypes()[1]) { - // beans.5A=Indexed read method is not compatible with indexed write method - throw new IntrospectionException(Messages.getString("beans.5A")); //$NON-NLS-1$ - } - - // Set the indexed property type if not already set, confirm validity if - // it is. - if (this.indexedGetter == null) { - indexedPropertyType = indexedReadType; - } else { - if (indexedPropertyType != indexedReadType) { - // beans.5A=Indexed read method is not compatible with indexed write method - throw new IntrospectionException(Messages.getString("beans.5A")); //$NON-NLS-1$ - } - } - - // Set the indexed getter - this.indexedGetter = indexGetter; - } - - private void setIndexedWriteMethod(Class beanClass, String indexedSetterName) - throws IntrospectionException { - Method setter = null; - try { - setter = beanClass.getMethod(indexedSetterName, new Class[] { - Integer.TYPE, getPropertyType().getComponentType() }); - } catch (SecurityException e) { - // beans.5C=Security violation accessing indexed write method - throw new IntrospectionException(Messages.getString("beans.5C")); //$NON-NLS-1$ - } catch (NoSuchMethodException e) { - // beans.5D=No such indexed write method - throw new IntrospectionException(Messages.getString("beans.5D")); //$NON-NLS-1$ - } - internalSetIndexedWriteMethod(setter, true); - } - - private void setIndexedWriteMethod(Class beanClass, - String indexedSetterName, Class argType) - throws IntrospectionException { - try { - Method setter = beanClass.getMethod(indexedSetterName, new Class[] { - Integer.TYPE, argType }); - internalSetIndexedWriteMethod(setter, true); - } catch (NoSuchMethodException exception) { - // beans.5D=No such indexed write method - throw new IntrospectionException(Messages.getString("beans.5D")); //$NON-NLS-1$ - } catch (SecurityException exception) { - // beans.5C=Security violation accessing indexed write method - throw new IntrospectionException(Messages.getString("beans.5C")); //$NON-NLS-1$ - } - } - - private void internalSetIndexedWriteMethod(Method indexSetter, - boolean initialize) throws IntrospectionException { - // Clearing the indexed write method. - if (indexSetter == null) { - if (indexedGetter == null) { - if (getPropertyType() != null) { - // beans.5E=Indexed method is not compatible with non indexed method - throw new IntrospectionException(Messages - .getString("beans.5E")); //$NON-NLS-1$ - } - indexedPropertyType = null; - } - this.indexedSetter = null; - return; - } - - // Validate the indexed write method. - Class[] indexedSetterArgs = indexSetter.getParameterTypes(); - if (indexedSetterArgs.length != 2) { - // beans.5F=Indexed write method must take two arguments - throw new IntrospectionException(Messages.getString("beans.5F")); //$NON-NLS-1$ - } - if (indexedSetterArgs[0] != Integer.TYPE) { - // beans.60=Indexed write method must take an int as its first argument - throw new IntrospectionException(Messages.getString("beans.60")); //$NON-NLS-1$ - } - - // Set the indexed property type if not already set, confirm validity if - // it is. - Class indexedWriteType = indexedSetterArgs[1]; - if (initialize && indexedGetter == null) { - indexedPropertyType = indexedWriteType; - } else { - if (indexedPropertyType != indexedWriteType) { - // beans.61=Indexed write method is not compatible with indexed read method - throw new IntrospectionException(Messages.getString("beans.61")); //$NON-NLS-1$ - } - } - - // Set the indexed write method. - this.indexedSetter = indexSetter; - } - - private static String initialUpperCase(String string) { - if (Character.isUpperCase(string.charAt(0))) { - return string; - } - - String initial = string.substring(0, 1).toUpperCase(); - return initial.concat(string.substring(1)); - } + private Class indexedPropertyType; + + private Method indexedGetter; + + private Method indexedSetter; + + /** Constructs a new instance of IndexedPropertyDescriptor. + * + * @param propertyName the specified indexed property's name. + * @param beanClass the bean class + * @param getterName the name of the array getter + * @param setterName the name of the array setter + * @param indexedGetterName the name of the indexed getter. + * @param indexedSetterName the name of the indexed setter. + * @throws IntrospectionException */ + public IndexedPropertyDescriptor (String propertyName, Class beanClass, String getterName, String setterName, + String indexedGetterName, String indexedSetterName) throws IntrospectionException { + super(propertyName, beanClass, getterName, setterName); + setIndexedByName(beanClass, indexedGetterName, indexedSetterName); + } + + private void setIndexedByName (Class beanClass, String indexedGetterName, String indexedSetterName) + throws IntrospectionException { + + String theIndexedGetterName = indexedGetterName; + if (theIndexedGetterName == null) { + if (indexedSetterName != null) { + setIndexedWriteMethod(beanClass, indexedSetterName); + } + } else { + if (theIndexedGetterName.length() == 0) { + theIndexedGetterName = "get" + name; //$NON-NLS-1$ + } + setIndexedReadMethod(beanClass, theIndexedGetterName); + if (indexedSetterName != null) { + setIndexedWriteMethod(beanClass, indexedSetterName, indexedPropertyType); + } + } + + if (!isCompatible()) { + // beans.57=Property type is incompatible with the indexed property type + throw new IntrospectionException(Messages.getString("beans.57")); //$NON-NLS-1$ + } + } + + private boolean isCompatible () { + Class propertyType = getPropertyType(); + + if (propertyType == null) { + return true; + } + Class componentTypeOfProperty = propertyType.getComponentType(); + if (componentTypeOfProperty == null) { + return false; + } + if (indexedPropertyType == null) { + return false; + } + + return componentTypeOfProperty.getName().equals(indexedPropertyType.getName()); + } + + /** Constructs a new instance of IndexedPropertyDescriptor. + * + * @param propertyName the specified indexed property's name. + * @param getter the array getter + * @param setter the array setter + * @param indexedGetter the indexed getter + * @param indexedSetter the indexed setter + * @throws IntrospectionException */ + public IndexedPropertyDescriptor (String propertyName, Method getter, Method setter, Method indexedGetter, Method indexedSetter) + throws IntrospectionException { + super(propertyName, getter, setter); + if (indexedGetter != null) { + internalSetIndexedReadMethod(indexedGetter); + internalSetIndexedWriteMethod(indexedSetter, true); + } else { + internalSetIndexedWriteMethod(indexedSetter, true); + internalSetIndexedReadMethod(indexedGetter); + } + + if (!isCompatible()) { + // beans.57=Property type is incompatible with the indexed property type + throw new IntrospectionException(Messages.getString("beans.57")); //$NON-NLS-1$ + } + } + + /** Constructs a new instance of IndexedPropertyDescriptor. + * + * @param propertyName the specified indexed property's name. + * @param beanClass the bean class. + * @throws IntrospectionException */ + public IndexedPropertyDescriptor (String propertyName, Class beanClass) throws IntrospectionException { + super(propertyName, beanClass); + setIndexedByName(beanClass, "get" //$NON-NLS-1$ + .concat(initialUpperCase(propertyName)), "set" //$NON-NLS-1$ + .concat(initialUpperCase(propertyName))); + } + + /** Sets the indexed getter as the specified method. + * + * @param indexedGetter the specified indexed getter. + * @throws IntrospectionException */ + public void setIndexedReadMethod (Method indexedGetter) throws IntrospectionException { + this.internalSetIndexedReadMethod(indexedGetter); + } + + /** Sets the indexed setter as the specified method. + * + * @param indexedSetter the specified indexed setter. + * @throws IntrospectionException */ + public void setIndexedWriteMethod (Method indexedSetter) throws IntrospectionException { + this.internalSetIndexedWriteMethod(indexedSetter, false); + } + + /** Obtains the indexed setter. + * + * @return the indexed setter. */ + public Method getIndexedWriteMethod () { + return indexedSetter; + } + + /** Obtains the indexed getter. + * + * @return the indexed getter. */ + public Method getIndexedReadMethod () { + return indexedGetter; + } + + /** Determines if this IndexedPropertyDescriptor is equal to the specified object. Two + * IndexedPropertyDescriptor s are equal if the reader, indexed reader, writer, indexed writer, property types, + * indexed property type, property editor and flags are equal. + * + * @param obj + * @return true if this indexed property descriptor is equal to the specified object. */ + @Override + public boolean equals (Object obj) { + if (!(obj instanceof IndexedPropertyDescriptor)) { + return false; + } + + IndexedPropertyDescriptor other = (IndexedPropertyDescriptor)obj; + + return (super.equals(other) + && (indexedPropertyType == null ? other.indexedPropertyType == null : indexedPropertyType + .equals(other.indexedPropertyType)) + && (indexedGetter == null ? other.indexedGetter == null : indexedGetter.equals(other.indexedGetter)) && (indexedSetter == null ? other.indexedSetter == null + : indexedSetter.equals(other.indexedSetter))); + } + + /** HashCode of the IndexedPropertyDescriptor */ + @Override + public int hashCode () { + return super.hashCode() + BeansUtils.getHashCode(indexedPropertyType) + BeansUtils.getHashCode(indexedGetter) + + BeansUtils.getHashCode(indexedSetter); + } + + /** Obtains the Class object of the indexed property type. + * + * @return the Class object of the indexed property type. */ + public Class getIndexedPropertyType () { + return indexedPropertyType; + } + + private void setIndexedReadMethod (Class beanClass, String indexedGetterName) throws IntrospectionException { + Method getter; + try { + getter = beanClass.getMethod(indexedGetterName, new Class[] {Integer.TYPE}); + } catch (NoSuchMethodException exception) { + // beans.58=No such indexed read method + throw new IntrospectionException(Messages.getString("beans.58")); //$NON-NLS-1$ + } catch (SecurityException exception) { + // beans.59=Security violation accessing indexed read method + throw new IntrospectionException(Messages.getString("beans.59")); //$NON-NLS-1$ + } + internalSetIndexedReadMethod(getter); + } + + private void internalSetIndexedReadMethod (Method indexGetter) throws IntrospectionException { + // Clearing the indexed read method. + if (indexGetter == null) { + if (indexedSetter == null) { + if (getPropertyType() != null) { + // beans.5A=Indexed method is not compatible with non indexed method + throw new IntrospectionException(Messages.getString("beans.5A")); //$NON-NLS-1$ + } + indexedPropertyType = null; + } + this.indexedGetter = null; + return; + } + // Validate the indexed getter. + if ((indexGetter.getParameterTypes().length != 1) || (indexGetter.getParameterTypes()[0] != Integer.TYPE)) { + // beans.5B=Indexed read method must take a single int argument + throw new IntrospectionException(Messages.getString("beans.5B")); //$NON-NLS-1$ + } + Class indexedReadType = indexGetter.getReturnType(); + if (indexedReadType == Void.TYPE) { + // beans.5B=Indexed read method must take a single int argument + throw new IntrospectionException(Messages.getString("beans.5B")); //$NON-NLS-1$ + } else if (indexedSetter != null && indexGetter.getReturnType() != indexedSetter.getParameterTypes()[1]) { + // beans.5A=Indexed read method is not compatible with indexed write method + throw new IntrospectionException(Messages.getString("beans.5A")); //$NON-NLS-1$ + } + + // Set the indexed property type if not already set, confirm validity if + // it is. + if (this.indexedGetter == null) { + indexedPropertyType = indexedReadType; + } else { + if (indexedPropertyType != indexedReadType) { + // beans.5A=Indexed read method is not compatible with indexed write method + throw new IntrospectionException(Messages.getString("beans.5A")); //$NON-NLS-1$ + } + } + + // Set the indexed getter + this.indexedGetter = indexGetter; + } + + private void setIndexedWriteMethod (Class beanClass, String indexedSetterName) throws IntrospectionException { + Method setter = null; + try { + setter = beanClass.getMethod(indexedSetterName, new Class[] {Integer.TYPE, getPropertyType().getComponentType()}); + } catch (SecurityException e) { + // beans.5C=Security violation accessing indexed write method + throw new IntrospectionException(Messages.getString("beans.5C")); //$NON-NLS-1$ + } catch (NoSuchMethodException e) { + // beans.5D=No such indexed write method + throw new IntrospectionException(Messages.getString("beans.5D")); //$NON-NLS-1$ + } + internalSetIndexedWriteMethod(setter, true); + } + + private void setIndexedWriteMethod (Class beanClass, String indexedSetterName, Class argType) + throws IntrospectionException { + try { + Method setter = beanClass.getMethod(indexedSetterName, new Class[] {Integer.TYPE, argType}); + internalSetIndexedWriteMethod(setter, true); + } catch (NoSuchMethodException exception) { + // beans.5D=No such indexed write method + throw new IntrospectionException(Messages.getString("beans.5D")); //$NON-NLS-1$ + } catch (SecurityException exception) { + // beans.5C=Security violation accessing indexed write method + throw new IntrospectionException(Messages.getString("beans.5C")); //$NON-NLS-1$ + } + } + + private void internalSetIndexedWriteMethod (Method indexSetter, boolean initialize) throws IntrospectionException { + // Clearing the indexed write method. + if (indexSetter == null) { + if (indexedGetter == null) { + if (getPropertyType() != null) { + // beans.5E=Indexed method is not compatible with non indexed method + throw new IntrospectionException(Messages.getString("beans.5E")); //$NON-NLS-1$ + } + indexedPropertyType = null; + } + this.indexedSetter = null; + return; + } + + // Validate the indexed write method. + Class[] indexedSetterArgs = indexSetter.getParameterTypes(); + if (indexedSetterArgs.length != 2) { + // beans.5F=Indexed write method must take two arguments + throw new IntrospectionException(Messages.getString("beans.5F")); //$NON-NLS-1$ + } + if (indexedSetterArgs[0] != Integer.TYPE) { + // beans.60=Indexed write method must take an int as its first argument + throw new IntrospectionException(Messages.getString("beans.60")); //$NON-NLS-1$ + } + + // Set the indexed property type if not already set, confirm validity if + // it is. + Class indexedWriteType = indexedSetterArgs[1]; + if (initialize && indexedGetter == null) { + indexedPropertyType = indexedWriteType; + } else { + if (indexedPropertyType != indexedWriteType) { + // beans.61=Indexed write method is not compatible with indexed read method + throw new IntrospectionException(Messages.getString("beans.61")); //$NON-NLS-1$ + } + } + + // Set the indexed write method. + this.indexedSetter = indexSetter; + } + + private static String initialUpperCase (String string) { + if (Character.isUpperCase(string.charAt(0))) { + return string; + } + + String initial = string.substring(0, 1).toUpperCase(); + return initial.concat(string.substring(1)); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/IntrospectionException.java b/extensions/beans/src/com/badlogic/gdx/beans/IntrospectionException.java index 10e1c52de6a..b4523a886e4 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/IntrospectionException.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/IntrospectionException.java @@ -19,9 +19,9 @@ public class IntrospectionException extends Exception { - private static final long serialVersionUID = -3728150539969542619L; + private static final long serialVersionUID = -3728150539969542619L; - public IntrospectionException(String message) { - super(message); - } + public IntrospectionException (String message) { + super(message); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/Introspector.java b/extensions/beans/src/com/badlogic/gdx/beans/Introspector.java index 3a88a9f1dd6..ab67d6699f9 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/Introspector.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/Introspector.java @@ -17,356 +17,282 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.BeanDescriptor; -import com.badlogic.gdx.beans.BeanInfo; -import com.badlogic.gdx.beans.IntrospectionException; - import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; -/** - * The Introspector is a utility for developers to figure out - * which properties, events, and methods a JavaBean supports. +/** The Introspector is a utility for developers to figure out which properties, events, and methods a JavaBean + * supports. *

    - * The Introspector class walks over the class/superclass chain - * of the target bean class. At each level it checks if there is a matching - * BeanInfo class which provides explicit information about the - * bean, and if so uses that explicit information. Otherwise it uses the low - * level reflection APIs to study the target class and uses design patterns to - * analyze its behaviour and then proceeds to continue the introspection with - * its baseclass. + * The Introspector class walks over the class/superclass chain of the target bean class. At each level it checks if + * there is a matching BeanInfo class which provides explicit information about the bean, and if so uses that + * explicit information. Otherwise it uses the low level reflection APIs to study the target class and uses design patterns to + * analyze its behaviour and then proceeds to continue the introspection with its baseclass. *

    *

    * To look for the explicit information of a bean: *

    *
      - *
    1. The Introspector appends "BeanInfo" to the qualified name - * of the bean class, try to use the new class as the "BeanInfo" class. If the - * "BeanInfo" class exsits and returns non-null value when queried for explicit - * information, use the explicit information
    2. - *
    3. If the first step fails, the Introspector will extract a - * simple class name of the bean class by removing the package name from the - * qualified name of the bean class, append "BeanInfo" to it. And look for the - * simple class name in the packages defined in the "BeanInfo" search path (The - * default "BeanInfo" search path is sun.beans.infos). If it - * finds a "BeanInfo" class and the "BeanInfo" class returns non-null value when - * queried for explicit information, use the explicit information
    4. - *
    - * - */ -//ScrollPane cannot be introspected correctly + *
  • The Introspector appends "BeanInfo" to the qualified name of the bean class, try to use the new class as the + * "BeanInfo" class. If the "BeanInfo" class exsits and returns non-null value when queried for explicit information, use the + * explicit information
  • + *
  • If the first step fails, the Introspector will extract a simple class name of the bean class by removing the + * package name from the qualified name of the bean class, append "BeanInfo" to it. And look for the simple class name in the + * packages defined in the "BeanInfo" search path (The default "BeanInfo" search path is sun.beans.infos). If it + * finds a "BeanInfo" class and the "BeanInfo" class returns non-null value when queried for explicit information, use the + * explicit information
  • + * */ +// ScrollPane cannot be introspected correctly public class Introspector extends java.lang.Object { - // Public fields - /** - * Constant values to indicate that the Introspector will - * ignore all BeanInfo class. - */ - public static final int IGNORE_ALL_BEANINFO = 3; + // Public fields + /** Constant values to indicate that the Introspector will ignore all BeanInfo class. */ + public static final int IGNORE_ALL_BEANINFO = 3; - /** - * Constant values to indicate that the Introspector will - * ignore the BeanInfo class of the current bean class. - */ - public static final int IGNORE_IMMEDIATE_BEANINFO = 2; + /** Constant values to indicate that the Introspector will ignore the BeanInfo class of the current + * bean class. */ + public static final int IGNORE_IMMEDIATE_BEANINFO = 2; - /** - * Constant values to indicate that the Introspector will use - * all BeanInfo class which have been found. This is the default one. - */ - public static final int USE_ALL_BEANINFO = 1; + /** Constant values to indicate that the Introspector will use all BeanInfo class which have been + * found. This is the default one. */ + public static final int USE_ALL_BEANINFO = 1; - // Default search path for BeanInfo classes - private static final String DEFAULT_BEANINFO_SEARCHPATH = "sun.beans.infos"; //$NON-NLS-1$ + // Default search path for BeanInfo classes + private static final String DEFAULT_BEANINFO_SEARCHPATH = "sun.beans.infos"; //$NON-NLS-1$ - // The search path to use to find BeanInfo classes - // - an array of package names that are used in turn - private static String[] searchPath = { DEFAULT_BEANINFO_SEARCHPATH }; + // The search path to use to find BeanInfo classes + // - an array of package names that are used in turn + private static String[] searchPath = {DEFAULT_BEANINFO_SEARCHPATH}; - // The cache to store Bean Info objects that have been found or created - private static final int DEFAULT_CAPACITY = 128; + // The cache to store Bean Info objects that have been found or created + private static final int DEFAULT_CAPACITY = 128; - private static Map, StandardBeanInfo> theCache = Collections.synchronizedMap(new WeakHashMap, StandardBeanInfo>(DEFAULT_CAPACITY)); + private static Map, StandardBeanInfo> theCache = Collections + .synchronizedMap(new WeakHashMap, StandardBeanInfo>(DEFAULT_CAPACITY)); - private Introspector() { - super(); - } + private Introspector () { + super(); + } - /** - * Decapitalizes a given string according to the rule: - *
      - *
    • If the first or only character is Upper Case, it is made Lower Case - *
    • UNLESS the second character is also Upper Case, when the String is - * returned unchanged - * - * @param name - - * the String to decapitalize - * @return the decapitalized version of the String - */ - public static String decapitalize(String name) { + /** Decapitalizes a given string according to the rule: + *
        + *
      • If the first or only character is Upper Case, it is made Lower Case + *
      • UNLESS the second character is also Upper Case, when the String is returned unchanged + * + * @param name - the String to decapitalize + * @return the decapitalized version of the String */ + public static String decapitalize (String name) { - if (name == null) - return null; - // The rule for decapitalize is that: - // If the first letter of the string is Upper Case, make it lower case - // UNLESS the second letter of the string is also Upper Case, in which case no - // changes are made. - if (name.length() == 0 || (name.length() > 1 && Character.isUpperCase(name.charAt(1)))) { - return name; - } - - char[] chars = name.toCharArray(); - chars[0] = Character.toLowerCase(chars[0]); - return new String(chars); - } + if (name == null) return null; + // The rule for decapitalize is that: + // If the first letter of the string is Upper Case, make it lower case + // UNLESS the second letter of the string is also Upper Case, in which case no + // changes are made. + if (name.length() == 0 || (name.length() > 1 && Character.isUpperCase(name.charAt(1)))) { + return name; + } - /** - * Flushes all BeanInfo caches. - * - */ - public static void flushCaches() { - // Flush the cache by throwing away the cache HashMap and creating a - // new empty one - theCache.clear(); - } + char[] chars = name.toCharArray(); + chars[0] = Character.toLowerCase(chars[0]); + return new String(chars); + } - /** - * Flushes the BeanInfo caches of the specified bean class - * - * @param clazz - * the specified bean class - */ - public static void flushFromCaches(Class clazz) { - if(clazz == null){ - throw new NullPointerException(); - } - theCache.remove(clazz); - } + /** Flushes all BeanInfo caches. */ + public static void flushCaches () { + // Flush the cache by throwing away the cache HashMap and creating a + // new empty one + theCache.clear(); + } - /** - * Gets the BeanInfo object which contains the information of - * the properties, events and methods of the specified bean class. + /** Flushes the BeanInfo caches of the specified bean class + * + * @param clazz the specified bean class */ + public static void flushFromCaches (Class clazz) { + if (clazz == null) { + throw new NullPointerException(); + } + theCache.remove(clazz); + } + + /** Gets the BeanInfo object which contains the information of the properties, events and methods of the specified + * bean class. * *

        - * The Introspector will cache the BeanInfo - * object. Subsequent calls to this method will be answered with the cached - * data. + * The Introspector will cache the BeanInfo object. Subsequent calls to this method will be answered + * with the cached data. *

        * - * @param beanClass - * the specified bean class. + * @param beanClass the specified bean class. * @return the BeanInfo of the bean class. - * @throws IntrospectionException - */ - public static BeanInfo getBeanInfo(Class beanClass) - throws IntrospectionException { - StandardBeanInfo beanInfo = theCache.get(beanClass); - if (beanInfo == null) { - beanInfo = getBeanInfoImplAndInit(beanClass, null, USE_ALL_BEANINFO); - theCache.put(beanClass, beanInfo); - } - return beanInfo; - } - - /** - * Gets the BeanInfo object which contains the information of - * the properties, events and methods of the specified bean class. It will - * not introspect the "stopclass" and its super class. - * - *

        - * The Introspector will cache the BeanInfo - * object. Subsequent calls to this method will be answered with the cached - * data. - *

        - * - * @param beanClass - * the specified beanClass. - * @param stopClass - * the sopt class which should be super class of the bean class. - * May be null. - * @return the BeanInfo of the bean class. - * @throws IntrospectionException - */ - public static BeanInfo getBeanInfo(Class beanClass, Class stopClass) - throws IntrospectionException { - if(stopClass == null){ - //try to use cache - return getBeanInfo(beanClass); - } - return getBeanInfoImplAndInit(beanClass, stopClass, USE_ALL_BEANINFO); - } + * @throws IntrospectionException */ + public static BeanInfo getBeanInfo (Class beanClass) throws IntrospectionException { + StandardBeanInfo beanInfo = theCache.get(beanClass); + if (beanInfo == null) { + beanInfo = getBeanInfoImplAndInit(beanClass, null, USE_ALL_BEANINFO); + theCache.put(beanClass, beanInfo); + } + return beanInfo; + } - /** - * Gets the BeanInfo object which contains the information of - * the properties, events and methods of the specified bean class. - *
          - *
        1. If flag==IGNORE_ALL_BEANINFO, the - * Introspector will ignore all BeanInfo - * class.
        2. - *
        3. If flag==IGNORE_IMMEDIATE_BEANINFO, the - * Introspector will ignore the BeanInfo class - * of the current bean class.
        4. - *
        5. If flag==USE_ALL_BEANINFO, the - * Introspector will use all BeanInfo class - * which have been found.
        6. - *
        - *

        - * The Introspector will cache the BeanInfo - * object. Subsequent calls to this method will be answered with the cached - * data. - *

        - * - * @param beanClass - * the specified bean class. - * @param flags - * the flag to control the usage of the explicit - * BeanInfo class. - * @return the BeanInfo of the bean class. - * @throws IntrospectionException - */ - public static BeanInfo getBeanInfo(Class beanClass, int flags) - throws IntrospectionException { - if(flags == USE_ALL_BEANINFO){ - //try to use cache - return getBeanInfo(beanClass); - } - return getBeanInfoImplAndInit(beanClass, null, flags); - } - - /** - * Gets an array of search packages. - * - * @return an array of search packages. - */ - public static String[] getBeanInfoSearchPath() { - String[] path = new String[searchPath.length]; - System.arraycopy(searchPath, 0, path, 0, searchPath.length); - return path; - } + /** Gets the BeanInfo object which contains the information of the properties, events and methods of the specified + * bean class. It will not introspect the "stopclass" and its super class. + * + *

        + * The Introspector will cache the BeanInfo object. Subsequent calls to this method will be answered + * with the cached data. + *

        + * + * @param beanClass the specified beanClass. + * @param stopClass the sopt class which should be super class of the bean class. May be null. + * @return the BeanInfo of the bean class. + * @throws IntrospectionException */ + public static BeanInfo getBeanInfo (Class beanClass, Class stopClass) throws IntrospectionException { + if (stopClass == null) { + // try to use cache + return getBeanInfo(beanClass); + } + return getBeanInfoImplAndInit(beanClass, stopClass, USE_ALL_BEANINFO); + } - /** - * Sets the search packages. - * - * @param path the new search packages to be set. - */ - public static void setBeanInfoSearchPath(String[] path) { - if (System.getSecurityManager() != null) { - System.getSecurityManager().checkPropertiesAccess(); - } - searchPath = path; - } + /** Gets the BeanInfo object which contains the information of the properties, events and methods of the specified + * bean class. + *
          + *
        1. If flag==IGNORE_ALL_BEANINFO, the Introspector will ignore all BeanInfo class.
        2. + *
        3. If flag==IGNORE_IMMEDIATE_BEANINFO, the Introspector will ignore the BeanInfo + * class of the current bean class.
        4. + *
        5. If flag==USE_ALL_BEANINFO, the Introspector will use all BeanInfo class which + * have been found.
        6. + *
        + *

        + * The Introspector will cache the BeanInfo object. Subsequent calls to this method will be answered + * with the cached data. + *

        + * + * @param beanClass the specified bean class. + * @param flags the flag to control the usage of the explicit BeanInfo class. + * @return the BeanInfo of the bean class. + * @throws IntrospectionException */ + public static BeanInfo getBeanInfo (Class beanClass, int flags) throws IntrospectionException { + if (flags == USE_ALL_BEANINFO) { + // try to use cache + return getBeanInfo(beanClass); + } + return getBeanInfoImplAndInit(beanClass, null, flags); + } - private static StandardBeanInfo getBeanInfoImpl(Class beanClass, Class stopClass, - int flags) throws IntrospectionException { - BeanInfo explicitInfo = null; - if (flags == USE_ALL_BEANINFO) { - explicitInfo = getExplicitBeanInfo(beanClass); - } - StandardBeanInfo beanInfo = new StandardBeanInfo(beanClass, explicitInfo, stopClass); + /** Gets an array of search packages. + * + * @return an array of search packages. */ + public static String[] getBeanInfoSearchPath () { + String[] path = new String[searchPath.length]; + System.arraycopy(searchPath, 0, path, 0, searchPath.length); + return path; + } - if (beanInfo.additionalBeanInfo != null) { - for (int i = beanInfo.additionalBeanInfo.length-1; i >=0; i--) { - BeanInfo info = beanInfo.additionalBeanInfo[i]; - beanInfo.mergeBeanInfo(info, true); - } - } - - // recursive get beaninfo for super classes - Class beanSuperClass = beanClass.getSuperclass(); - if (beanSuperClass != stopClass) { - if (beanSuperClass == null) - throw new IntrospectionException( - "Stop class is not super class of bean class"); //$NON-NLS-1$ - int superflags = flags == IGNORE_IMMEDIATE_BEANINFO ? USE_ALL_BEANINFO - : flags; - BeanInfo superBeanInfo = getBeanInfoImpl(beanSuperClass, stopClass, - superflags); - if (superBeanInfo != null) { - beanInfo.mergeBeanInfo(superBeanInfo, false); - } - } - return beanInfo; - } + /** Sets the search packages. + * + * @param path the new search packages to be set. */ + public static void setBeanInfoSearchPath (String[] path) { + if (System.getSecurityManager() != null) { + System.getSecurityManager().checkPropertiesAccess(); + } + searchPath = path; + } - private static BeanInfo getExplicitBeanInfo(Class beanClass) { - String beanInfoClassName = beanClass.getName() + "BeanInfo"; //$NON-NLS-1$ - try { - return loadBeanInfo(beanInfoClassName, beanClass); - } catch (Exception e) { - // fall through - } + private static StandardBeanInfo getBeanInfoImpl (Class beanClass, Class stopClass, int flags) + throws IntrospectionException { + BeanInfo explicitInfo = null; + if (flags == USE_ALL_BEANINFO) { + explicitInfo = getExplicitBeanInfo(beanClass); + } + StandardBeanInfo beanInfo = new StandardBeanInfo(beanClass, explicitInfo, stopClass); - int index = beanInfoClassName.lastIndexOf('.'); - String beanInfoName = index >= 0 ? beanInfoClassName - .substring(index + 1) : beanInfoClassName; - BeanInfo theBeanInfo = null; - BeanDescriptor beanDescriptor = null; - for (int i = 0; i < searchPath.length; i++) { - beanInfoClassName = searchPath[i] + "." + beanInfoName; //$NON-NLS-1$ - try { - theBeanInfo = loadBeanInfo(beanInfoClassName, beanClass); - } catch (Exception e) { - // ignore, try next one - continue; - } - beanDescriptor = theBeanInfo.getBeanDescriptor(); - if (beanDescriptor != null - && beanClass == beanDescriptor.getBeanClass()) { - return theBeanInfo; - } - } - if (BeanInfo.class.isAssignableFrom(beanClass)) { - try { - return loadBeanInfo(beanClass.getName(), beanClass); - } catch (Exception e) { - // fall through - } - } - return null; - } + if (beanInfo.additionalBeanInfo != null) { + for (int i = beanInfo.additionalBeanInfo.length - 1; i >= 0; i--) { + BeanInfo info = beanInfo.additionalBeanInfo[i]; + beanInfo.mergeBeanInfo(info, true); + } + } - /* - * Method which attempts to instantiate a BeanInfo object of the supplied - * classname - * - * @param theBeanInfoClassName - - * the Class Name of the class of which the BeanInfo is an - * instance - * @param classLoader - * @return A BeanInfo object which is an instance of the Class named - * theBeanInfoClassName null if the Class does not exist or if there - * are problems instantiating the instance - */ - private static BeanInfo loadBeanInfo(String beanInfoClassName, - Class beanClass) throws Exception{ - try { - ClassLoader cl = beanClass.getClassLoader(); - if(cl != null){ - return (BeanInfo) Class.forName(beanInfoClassName, true, - beanClass.getClassLoader()).newInstance(); - } - } catch (Exception e) { - // fall through - } - try { - return (BeanInfo) Class.forName(beanInfoClassName, true, - ClassLoader.getSystemClassLoader()).newInstance(); - } catch (Exception e) { - // fall through - } - return (BeanInfo) Class.forName(beanInfoClassName, true, - Thread.currentThread().getContextClassLoader()).newInstance(); - } + // recursive get beaninfo for super classes + Class beanSuperClass = beanClass.getSuperclass(); + if (beanSuperClass != stopClass) { + if (beanSuperClass == null) throw new IntrospectionException("Stop class is not super class of bean class"); //$NON-NLS-1$ + int superflags = flags == IGNORE_IMMEDIATE_BEANINFO ? USE_ALL_BEANINFO : flags; + BeanInfo superBeanInfo = getBeanInfoImpl(beanSuperClass, stopClass, superflags); + if (superBeanInfo != null) { + beanInfo.mergeBeanInfo(superBeanInfo, false); + } + } + return beanInfo; + } - private static StandardBeanInfo getBeanInfoImplAndInit(Class beanClass, - Class stopClass, int flag) throws IntrospectionException { - StandardBeanInfo standardBeanInfo = getBeanInfoImpl(beanClass, - stopClass, flag); - standardBeanInfo.init(); - return standardBeanInfo; - } -} + private static BeanInfo getExplicitBeanInfo (Class beanClass) { + String beanInfoClassName = beanClass.getName() + "BeanInfo"; //$NON-NLS-1$ + try { + return loadBeanInfo(beanInfoClassName, beanClass); + } catch (Exception e) { + // fall through + } + int index = beanInfoClassName.lastIndexOf('.'); + String beanInfoName = index >= 0 ? beanInfoClassName.substring(index + 1) : beanInfoClassName; + BeanInfo theBeanInfo = null; + BeanDescriptor beanDescriptor = null; + for (int i = 0; i < searchPath.length; i++) { + beanInfoClassName = searchPath[i] + "." + beanInfoName; //$NON-NLS-1$ + try { + theBeanInfo = loadBeanInfo(beanInfoClassName, beanClass); + } catch (Exception e) { + // ignore, try next one + continue; + } + beanDescriptor = theBeanInfo.getBeanDescriptor(); + if (beanDescriptor != null && beanClass == beanDescriptor.getBeanClass()) { + return theBeanInfo; + } + } + if (BeanInfo.class.isAssignableFrom(beanClass)) { + try { + return loadBeanInfo(beanClass.getName(), beanClass); + } catch (Exception e) { + // fall through + } + } + return null; + } + /* + * Method which attempts to instantiate a BeanInfo object of the supplied classname + * + * @param theBeanInfoClassName - the Class Name of the class of which the BeanInfo is an instance + * + * @param classLoader + * + * @return A BeanInfo object which is an instance of the Class named theBeanInfoClassName null if the Class does not exist or + * if there are problems instantiating the instance + */ + private static BeanInfo loadBeanInfo (String beanInfoClassName, Class beanClass) throws Exception { + try { + ClassLoader cl = beanClass.getClassLoader(); + if (cl != null) { + return (BeanInfo)Class.forName(beanInfoClassName, true, beanClass.getClassLoader()).newInstance(); + } + } catch (Exception e) { + // fall through + } + try { + return (BeanInfo)Class.forName(beanInfoClassName, true, ClassLoader.getSystemClassLoader()).newInstance(); + } catch (Exception e) { + // fall through + } + return (BeanInfo)Class.forName(beanInfoClassName, true, Thread.currentThread().getContextClassLoader()).newInstance(); + } + private static StandardBeanInfo getBeanInfoImplAndInit (Class beanClass, Class stopClass, int flag) + throws IntrospectionException { + StandardBeanInfo standardBeanInfo = getBeanInfoImpl(beanClass, stopClass, flag); + standardBeanInfo.init(); + return standardBeanInfo; + } +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/MethodDescriptor.java b/extensions/beans/src/com/badlogic/gdx/beans/MethodDescriptor.java index 934db519ea2..cc695246c77 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/MethodDescriptor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/MethodDescriptor.java @@ -17,97 +17,76 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.FeatureDescriptor; -import com.badlogic.gdx.beans.MethodDescriptor; -import com.badlogic.gdx.beans.ParameterDescriptor; - import java.lang.reflect.Method; -/** - * Describes a bean's method. - */ +/** Describes a bean's method. */ public class MethodDescriptor extends FeatureDescriptor { - private Method method; + private Method method; + + private ParameterDescriptor[] parameterDescriptors; - private ParameterDescriptor[] parameterDescriptors; + /**

        + * Constructs an instance with the given {@link Method} and {@link ParameterDescriptor}s. The {@link #getName()} is set as the + * name of the method passed. + *

        + * + * @param method The Method to set. + * @param parameterDescriptors An array of parameter descriptors. */ + public MethodDescriptor (Method method, ParameterDescriptor[] parameterDescriptors) { + super(); - /** - *

        - * Constructs an instance with the given {@link Method} and - * {@link ParameterDescriptor}s. The {@link #getName()} is set as the name - * of the method passed. - *

        - * - * @param method - * The Method to set. - * @param parameterDescriptors - * An array of parameter descriptors. - */ - public MethodDescriptor(Method method, - ParameterDescriptor[] parameterDescriptors) { - super(); + if (method == null) { + throw new NullPointerException(); + } + this.method = method; + this.parameterDescriptors = parameterDescriptors; - if (method == null) { - throw new NullPointerException(); - } - this.method = method; - this.parameterDescriptors = parameterDescriptors; + setName(method.getName()); + } - setName(method.getName()); - } + /**

        + * Constructs an instance with the given {@link Method}. The {@link #getName()} is set as the name of the method + * passed. + *

        + * + * @param method The Method to set. */ + public MethodDescriptor (Method method) { + super(); - /** - *

        - * Constructs an instance with the given {@link Method}. The - * {@link #getName()} is set as the name of the method - * passed. - *

        - * - * @param method - * The Method to set. - */ - public MethodDescriptor(Method method) { - super(); + if (method == null) { + throw new NullPointerException(); + } + this.method = method; - if (method == null) { - throw new NullPointerException(); - } - this.method = method; + setName(method.getName()); + } - setName(method.getName()); - } + /**

        + * Gets the method. + *

        + * + * @return A {@link Method} instance. */ + public Method getMethod () { + return method; + } - /** - *

        - * Gets the method. - *

        - * - * @return A {@link Method} instance. - */ - public Method getMethod() { - return method; - } + /**

        + * Gets the parameter descriptors. + *

        + * + * @return An array of {@link ParameterDescriptor} instance or null. */ + public ParameterDescriptor[] getParameterDescriptors () { + return parameterDescriptors; + } - /** - *

        - * Gets the parameter descriptors. - *

        - * - * @return An array of {@link ParameterDescriptor} instance or - * null. - */ - public ParameterDescriptor[] getParameterDescriptors() { - return parameterDescriptors; - } - - void merge(MethodDescriptor anotherMethod){ - super.merge(anotherMethod); - if(method == null){ - method = anotherMethod.method; - } - if(parameterDescriptors == null){ - parameterDescriptors = anotherMethod.parameterDescriptors; - } - } + void merge (MethodDescriptor anotherMethod) { + super.merge(anotherMethod); + if (method == null) { + method = anotherMethod.method; + } + if (parameterDescriptors == null) { + parameterDescriptors = anotherMethod.parameterDescriptors; + } + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/MethodPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/MethodPersistenceDelegate.java index beaaf68b2ee..12a43dd3313 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/MethodPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/MethodPersistenceDelegate.java @@ -17,41 +17,35 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - import java.lang.reflect.Method; -/** - * Persistence delegate for {@link java.lang.reflect.Method} class. - */ +/** Persistence delegate for {@link java.lang.reflect.Method} class. */ class MethodPersistenceDelegate extends PersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder out) { - // should not be null or have a type other than Method - assert oldInstance instanceof Method : oldInstance; - Method oldMethod = (Method) oldInstance; - Class declClass = oldMethod.getDeclaringClass(); - return new Expression(oldMethod, declClass, "getMethod", //$NON-NLS-1$ - new Object[] { oldMethod.getName(), oldMethod.getParameterTypes() }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder out) { + // should not be null or have a type other than Method + assert oldInstance instanceof Method : oldInstance; + Method oldMethod = (Method)oldInstance; + Class declClass = oldMethod.getDeclaringClass(); + return new Expression(oldMethod, declClass, "getMethod", //$NON-NLS-1$ + new Object[] {oldMethod.getName(), oldMethod.getParameterTypes()}); + } - @Override - protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { - // check for consistency - assert oldInstance instanceof Method : oldInstance; - assert newInstance instanceof Method : newInstance; - assert newInstance.equals(oldInstance); - } + @Override + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder out) { + // check for consistency + assert oldInstance instanceof Method : oldInstance; + assert newInstance instanceof Method : newInstance; + assert newInstance.equals(oldInstance); + } - @Override - protected boolean mutatesTo(Object oldInstance, Object newInstance) { - assert oldInstance instanceof Method : oldInstance; - if (!(newInstance instanceof Method)) { - // if null or not a Method - return false; - } - return oldInstance.equals(newInstance); - } + @Override + protected boolean mutatesTo (Object oldInstance, Object newInstance) { + assert oldInstance instanceof Method : oldInstance; + if (!(newInstance instanceof Method)) { + // if null or not a Method + return false; + } + return oldInstance.equals(newInstance); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/NullPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/NullPersistenceDelegate.java index 2eb13097baa..8334d99be39 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/NullPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/NullPersistenceDelegate.java @@ -17,28 +17,22 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - class NullPersistenceDelegate extends PersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder out) { - return null; - } + @Override + protected Expression instantiate (Object oldInstance, Encoder out) { + return null; + } - @Override - /* - * It's unnecessary to do anything for initialization, because two mutatable - * strings are actually equivalent already. - */ - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder out) { - // do nothing - } + @Override + /* + * It's unnecessary to do anything for initialization, because two mutatable strings are actually equivalent already. + */ + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder out) { + // do nothing + } - @Override - public void writeObject(Object oldInstance, Encoder out) { - // do nothing - } + @Override + public void writeObject (Object oldInstance, Encoder out) { + // do nothing + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/ParameterDescriptor.java b/extensions/beans/src/com/badlogic/gdx/beans/ParameterDescriptor.java index 114eb6e68cb..e64dfca3620 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/ParameterDescriptor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/ParameterDescriptor.java @@ -17,11 +17,9 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.FeatureDescriptor; - public class ParameterDescriptor extends FeatureDescriptor { - public ParameterDescriptor() { - // do nothing - } + public ParameterDescriptor () { + // do nothing + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/PersistenceDelegate.java index 7ebda184e53..141d2863a44 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PersistenceDelegate.java @@ -15,114 +15,73 @@ * limitations under the License. */ - package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - -/** - * PersistenceDelegate instances write received bean objects to - * encoders in the form of expressions and statements, which can be evaluated or - * executed to reconstruct the recorded bean objects in a new environment during - * decoding. Expressions are usually used to instantiate bean objects in the new - * environment, and statements are used to initialize their properties if - * necessary. As a result, the reconstructed bean objects become equivalent to - * the original recorded ones in terms of their public states. - * - */ +/** PersistenceDelegate instances write received bean objects to encoders in the form of expressions and statements, + * which can be evaluated or executed to reconstruct the recorded bean objects in a new environment during decoding. Expressions + * are usually used to instantiate bean objects in the new environment, and statements are used to initialize their properties if + * necessary. As a result, the reconstructed bean objects become equivalent to the original recorded ones in terms of their public + * states. */ public abstract class PersistenceDelegate { - /** - * Default constructor. - */ - public PersistenceDelegate() { - // empty - } + /** Default constructor. */ + public PersistenceDelegate () { + // empty + } - /** - * Produces a series of expressions and statements for the initialization of - * a bean object's properties. The default implementation simply invokes the - * initialization provided by the super class's - * PersisteneceDelegate instance. - * - * @param type - * the type of the bean - * @param oldInstance - * the original bean object to be recorded - * @param newInstance - * the simmulating new bean object to be initialized - * @param enc - * the encoder to write the outputs to - */ - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - Class c = type.getSuperclass(); - if (null != c) { - PersistenceDelegate pd = enc.getPersistenceDelegate(c); - pd.initialize(c, oldInstance, newInstance, enc); - } - } + /** Produces a series of expressions and statements for the initialization of a bean object's properties. The default + * implementation simply invokes the initialization provided by the super class's PersisteneceDelegate instance. + * + * @param type the type of the bean + * @param oldInstance the original bean object to be recorded + * @param newInstance the simmulating new bean object to be initialized + * @param enc the encoder to write the outputs to */ + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + Class c = type.getSuperclass(); + if (null != c) { + PersistenceDelegate pd = enc.getPersistenceDelegate(c); + pd.initialize(c, oldInstance, newInstance, enc); + } + } - /** - * Constructs an expression for instantiating an object of the same type as - * the old instance. Any exceptions occured during this process could be - * reported to the exception listener registered in the given encoder. - * - * @param oldInstance - * the old instance - * @param enc - * the encoder that wants to record the old instance - * @return an expression for instantiating an object of the same type as the - * old instance - */ - protected abstract Expression instantiate(Object oldInstance, Encoder enc); + /** Constructs an expression for instantiating an object of the same type as the old instance. Any exceptions occured during + * this process could be reported to the exception listener registered in the given encoder. + * + * @param oldInstance the old instance + * @param enc the encoder that wants to record the old instance + * @return an expression for instantiating an object of the same type as the old instance */ + protected abstract Expression instantiate (Object oldInstance, Encoder enc); - /** - * Determines whether one object mutates to the other object. One object is - * considered able to mutate to another object if they are indistinguishable - * in terms of behaviors of all public APIs. The default implementation here - * is to return true only if the two objects are instances of the same - * class. - * - * @param o1 - * one object - * @param o2 - * the other object - * @return true if second object mutates to the first object, otherwise - * false - */ - protected boolean mutatesTo(Object o1, Object o2) { - return null != o1 && null != o2 && o1.getClass() == o2.getClass(); - } + /** Determines whether one object mutates to the other object. One object is considered able to mutate to another object if they + * are indistinguishable in terms of behaviors of all public APIs. The default implementation here is to return true only if + * the two objects are instances of the same class. + * + * @param o1 one object + * @param o2 the other object + * @return true if second object mutates to the first object, otherwise false */ + protected boolean mutatesTo (Object o1, Object o2) { + return null != o1 && null != o2 && o1.getClass() == o2.getClass(); + } - /** - * Writes a bean object to the given encoder. First it is checked whether - * the simulating new object can be mutated to the old instance. If yes, it - * is initialized to produce a series of expressions and statements that can - * be used to restore the old instance. Otherwise, remove the new object in - * the simulating new environment and writes an expression that can - * instantiate a new instance of the same type as the old one to the given - * encoder. - * - * @param oldInstance - * the old instance to be written - * @param out - * the encoder that the old instance will be written to - */ - public void writeObject(Object oldInstance, Encoder out) { - Object newInstance = out.get(oldInstance); - Class clazz = oldInstance.getClass(); - if (mutatesTo(oldInstance, newInstance)) { - initialize(clazz, oldInstance, newInstance, out); - } else { - out.remove(oldInstance); - out.writeExpression(instantiate(oldInstance, out)); - newInstance = out.get(oldInstance); - if (newInstance != null) { - initialize(clazz, oldInstance, newInstance, out); - } - } - } -} \ No newline at end of file + /** Writes a bean object to the given encoder. First it is checked whether the simulating new object can be mutated to the old + * instance. If yes, it is initialized to produce a series of expressions and statements that can be used to restore the old + * instance. Otherwise, remove the new object in the simulating new environment and writes an expression that can instantiate a + * new instance of the same type as the old one to the given encoder. + * + * @param oldInstance the old instance to be written + * @param out the encoder that the old instance will be written to */ + public void writeObject (Object oldInstance, Encoder out) { + Object newInstance = out.get(oldInstance); + Class clazz = oldInstance.getClass(); + if (mutatesTo(oldInstance, newInstance)) { + initialize(clazz, oldInstance, newInstance, out); + } else { + out.remove(oldInstance); + out.writeExpression(instantiate(oldInstance, out)); + newInstance = out.get(oldInstance); + if (newInstance != null) { + initialize(clazz, oldInstance, newInstance, out); + } + } + } +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PrimitiveWrapperPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/PrimitiveWrapperPersistenceDelegate.java index 7082d35d121..f9d319f8962 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PrimitiveWrapperPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PrimitiveWrapperPersistenceDelegate.java @@ -15,56 +15,40 @@ * limitations under the License. */ - package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - - -/** - * A special internal PersistenceDelegate for wrapper classes of - * primitive types like int. - * - */ +/** A special internal PersistenceDelegate for wrapper classes of primitive types like int. */ class PrimitiveWrapperPersistenceDelegate extends PersistenceDelegate { - /* - * It's unnecessary to do anything for initialization, because two mutatable - * wrapper objects are actually equivalent already. - */ - @Override - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - // do nothing - } - - /* - * Instantiates a wrapper object using the constructor taking one String - * parameter except for Character. - */ - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - if (oldInstance instanceof Character) { - return new Expression(oldInstance, oldInstance.toString(), - "charAt", new Object[] { Integer.valueOf(0) }); //$NON-NLS-1$ - } - return new Expression(oldInstance, oldInstance.getClass(), - "new", new Object[] { oldInstance //$NON-NLS-1$ - .toString() }); - } - - /* - * Two wrapper objects are regarded mutatable if they are equal. - */ - @Override - protected boolean mutatesTo(Object o1, Object o2) { - if (null == o2) { - return false; - } - return o1.equals(o2); - } + /* + * It's unnecessary to do anything for initialization, because two mutatable wrapper objects are actually equivalent already. + */ + @Override + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + // do nothing + } + + /* + * Instantiates a wrapper object using the constructor taking one String parameter except for Character. + */ + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + if (oldInstance instanceof Character) { + return new Expression(oldInstance, oldInstance.toString(), "charAt", new Object[] {Integer.valueOf(0)}); //$NON-NLS-1$ + } + return new Expression(oldInstance, oldInstance.getClass(), "new", new Object[] {oldInstance //$NON-NLS-1$ + .toString()}); + } + + /* + * Two wrapper objects are regarded mutatable if they are equal. + */ + @Override + protected boolean mutatesTo (Object o1, Object o2) { + if (null == o2) { + return false; + } + return o1.equals(o2); + } } - diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeEvent.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeEvent.java index 572c0486127..b97afe85b5d 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeEvent.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeEvent.java @@ -21,42 +21,41 @@ public class PropertyChangeEvent extends EventObject { - private static final long serialVersionUID = 7042693688939648123L; + private static final long serialVersionUID = 7042693688939648123L; - String propertyName; + String propertyName; - Object oldValue; + Object oldValue; - Object newValue; + Object newValue; - Object propagationId; + Object propagationId; - public PropertyChangeEvent(Object source, String propertyName, - Object oldValue, Object newValue) { - super(source); + public PropertyChangeEvent (Object source, String propertyName, Object oldValue, Object newValue) { + super(source); - this.propertyName = propertyName; - this.oldValue = oldValue; - this.newValue = newValue; - } + this.propertyName = propertyName; + this.oldValue = oldValue; + this.newValue = newValue; + } - public String getPropertyName() { - return propertyName; - } + public String getPropertyName () { + return propertyName; + } - public void setPropagationId(Object propagationId) { - this.propagationId = propagationId; - } + public void setPropagationId (Object propagationId) { + this.propagationId = propagationId; + } - public Object getPropagationId() { - return propagationId; - } + public Object getPropagationId () { + return propagationId; + } - public Object getOldValue() { - return oldValue; - } + public Object getOldValue () { + return oldValue; + } - public Object getNewValue() { - return newValue; - } + public Object getNewValue () { + return newValue; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListener.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListener.java index c9884060ca4..fdd2cbde369 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListener.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListener.java @@ -17,11 +17,9 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; - import java.util.EventListener; public interface PropertyChangeListener extends EventListener { - public void propertyChange(PropertyChangeEvent event); + public void propertyChange (PropertyChangeEvent event); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListenerProxy.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListenerProxy.java index 02c3723d029..d933b29fbee 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListenerProxy.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeListenerProxy.java @@ -17,28 +17,23 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyChangeListener; - import java.util.EventListenerProxy; -public class PropertyChangeListenerProxy extends EventListenerProxy implements - PropertyChangeListener { +public class PropertyChangeListenerProxy extends EventListenerProxy implements PropertyChangeListener { - String propertyName; + String propertyName; - public PropertyChangeListenerProxy(String propertyName, - PropertyChangeListener listener) { - super(listener); - this.propertyName = propertyName; - } + public PropertyChangeListenerProxy (String propertyName, PropertyChangeListener listener) { + super(listener); + this.propertyName = propertyName; + } - public String getPropertyName() { - return propertyName; - } + public String getPropertyName () { + return propertyName; + } - public void propertyChange(PropertyChangeEvent event) { - PropertyChangeListener listener = (PropertyChangeListener) getListener(); - listener.propertyChange(event); - } + public void propertyChange (PropertyChangeEvent event) { + PropertyChangeListener listener = (PropertyChangeListener)getListener(); + listener.propertyChange(event); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeSupport.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeSupport.java index 000454c4867..2d6366aff2a 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeSupport.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyChangeSupport.java @@ -17,12 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.IndexedPropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyChangeListener; -import com.badlogic.gdx.beans.PropertyChangeListenerProxy; -import com.badlogic.gdx.beans.PropertyChangeSupport; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -34,253 +28,219 @@ public class PropertyChangeSupport implements Serializable { - private static final long serialVersionUID = 6401253773779951803l; - - private transient List globalListeners = new ArrayList(); - - private Hashtable children = new Hashtable(); - - private Object source; - - @SuppressWarnings("unused") - // for serialization compatibility - private int propertyChangeSupportSerializedDataVersion = 1; - - public PropertyChangeSupport(Object sourceBean) { - if (sourceBean == null) { - throw new NullPointerException(); - } - this.source = sourceBean; - } - - public void firePropertyChange(String propertyName, Object oldValue, - Object newValue) { - PropertyChangeEvent event = createPropertyChangeEvent(propertyName, - oldValue, newValue); - doFirePropertyChange(event); - } - - public void fireIndexedPropertyChange(String propertyName, int index, - Object oldValue, Object newValue) { - - // nulls and equals check done in doFire... - doFirePropertyChange(new IndexedPropertyChangeEvent(source, - propertyName, oldValue, newValue, index)); - } - - public synchronized void removePropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - if ((propertyName != null) && (listener != null)) { - PropertyChangeSupport listeners = children.get(propertyName); - - if (listeners != null) { - listeners.removePropertyChangeListener(listener); - } - } - } - - public synchronized void addPropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - if ((listener != null) && (propertyName != null)) { - PropertyChangeSupport listeners = children.get(propertyName); - - if (listeners == null) { - listeners = new PropertyChangeSupport(source); - children.put(propertyName, listeners); - } - - // RI compatibility - if (listener instanceof PropertyChangeListenerProxy) { - PropertyChangeListenerProxy proxy = (PropertyChangeListenerProxy) listener; - - listeners - .addPropertyChangeListener(new PropertyChangeListenerProxy( - proxy.getPropertyName(), - (PropertyChangeListener) proxy.getListener())); - } else { - listeners.addPropertyChangeListener(listener); - } - } - } - - public synchronized PropertyChangeListener[] getPropertyChangeListeners( - String propertyName) { - PropertyChangeSupport listeners = null; - - if (propertyName != null) { - listeners = children.get(propertyName); - } - - return (listeners == null) ? new PropertyChangeListener[0] - : listeners.getPropertyChangeListeners(); - } - - public void firePropertyChange(String propertyName, boolean oldValue, - boolean newValue) { - PropertyChangeEvent event = createPropertyChangeEvent(propertyName, - oldValue, newValue); - doFirePropertyChange(event); - } - - public void fireIndexedPropertyChange(String propertyName, int index, - boolean oldValue, boolean newValue) { - - if (oldValue != newValue) { - fireIndexedPropertyChange(propertyName, index, Boolean - .valueOf(oldValue), Boolean.valueOf(newValue)); - } - } - - public void firePropertyChange(String propertyName, int oldValue, - int newValue) { - PropertyChangeEvent event = createPropertyChangeEvent(propertyName, - oldValue, newValue); - doFirePropertyChange(event); - } - - public void fireIndexedPropertyChange(String propertyName, int index, - int oldValue, int newValue) { - - if (oldValue != newValue) { - fireIndexedPropertyChange(propertyName, index, - Integer.valueOf(oldValue), Integer.valueOf(newValue)); - } - } - - public synchronized boolean hasListeners(String propertyName) { - if(globalListeners.size() > 0){ - return true; - } - boolean result = false; - if (propertyName != null) { - PropertyChangeSupport listeners = children.get(propertyName); - result = (listeners != null && listeners.hasListeners(propertyName)); - } - return result; - } - - public synchronized void removePropertyChangeListener( - PropertyChangeListener listener) { - if (listener instanceof PropertyChangeListenerProxy) { - String name = ((PropertyChangeListenerProxy) listener) - .getPropertyName(); - PropertyChangeListener lst = (PropertyChangeListener) ((PropertyChangeListenerProxy) listener) - .getListener(); - - removePropertyChangeListener(name, lst); - } else { - globalListeners.remove(listener); - } - } - - public synchronized void addPropertyChangeListener( - PropertyChangeListener listener) { - if (listener instanceof PropertyChangeListenerProxy) { - String name = ((PropertyChangeListenerProxy) listener) - .getPropertyName(); - PropertyChangeListener lst = (PropertyChangeListener) ((PropertyChangeListenerProxy) listener) - .getListener(); - addPropertyChangeListener(name, lst); - } else if(listener != null){ - globalListeners.add(listener); - } - } - - public synchronized PropertyChangeListener[] getPropertyChangeListeners() { - ArrayList result = new ArrayList( - globalListeners); - for (String propertyName : children.keySet()) { - PropertyChangeSupport namedListener = children - .get(propertyName); - PropertyChangeListener[] listeners = namedListener - .getPropertyChangeListeners(); - for (int i = 0; i < listeners.length; i++) { - result.add(new PropertyChangeListenerProxy(propertyName, - listeners[i])); - } - } - return result.toArray(new PropertyChangeListener[0]); - } - - private void writeObject(ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - PropertyChangeListener[] gListeners = globalListeners - .toArray(new PropertyChangeListener[0]); - for (int i = 0; i < gListeners.length; i++) { - if (gListeners[i] instanceof Serializable) { - oos.writeObject(gListeners[i]); - } - } - // Denotes end of list - oos.writeObject(null); - - } - - private void readObject(ObjectInputStream ois) throws IOException, - ClassNotFoundException { - ois.defaultReadObject(); - this.globalListeners = new LinkedList(); - if (null == this.children) { - this.children = new Hashtable(); - } - Object listener = null; - do { - // Reads a listener _or_ proxy - listener = ois.readObject(); - if (listener != null) { - addPropertyChangeListener((PropertyChangeListener) listener); - } - } while (listener != null); - } - - public void firePropertyChange(PropertyChangeEvent event) { - doFirePropertyChange(event); - } - - private PropertyChangeEvent createPropertyChangeEvent(String propertyName, - Object oldValue, Object newValue) { - return new PropertyChangeEvent(source, propertyName, oldValue, newValue); - } - - @SuppressWarnings("boxing") - private PropertyChangeEvent createPropertyChangeEvent(String propertyName, - boolean oldValue, boolean newValue) { - return new PropertyChangeEvent(source, propertyName, oldValue, newValue); - } - - @SuppressWarnings("boxing") - private PropertyChangeEvent createPropertyChangeEvent(String propertyName, - int oldValue, int newValue) { - return new PropertyChangeEvent(source, propertyName, oldValue, newValue); - } - - private void doFirePropertyChange(PropertyChangeEvent event) { - Object oldValue = event.getOldValue(); - Object newValue = event.getNewValue(); - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; - } - - // Collect up the global listeners - PropertyChangeListener[] gListeners; - synchronized(this) { - gListeners = globalListeners.toArray(new PropertyChangeListener[0]); - } - - // Fire the events for global listeners - for (int i = 0; i < gListeners.length; i++) { - gListeners[i].propertyChange(event); - } - - // Fire the events for the property specific listeners if any - if (event.getPropertyName() != null) { - PropertyChangeSupport namedListener = children - .get(event.getPropertyName()); - if (namedListener != null) { - namedListener.firePropertyChange(event); - } - } - - } + private static final long serialVersionUID = 6401253773779951803l; + + private transient List globalListeners = new ArrayList(); + + private Hashtable children = new Hashtable(); + + private Object source; + + @SuppressWarnings("unused") + // for serialization compatibility + private int propertyChangeSupportSerializedDataVersion = 1; + + public PropertyChangeSupport (Object sourceBean) { + if (sourceBean == null) { + throw new NullPointerException(); + } + this.source = sourceBean; + } + + public void firePropertyChange (String propertyName, Object oldValue, Object newValue) { + PropertyChangeEvent event = createPropertyChangeEvent(propertyName, oldValue, newValue); + doFirePropertyChange(event); + } + + public void fireIndexedPropertyChange (String propertyName, int index, Object oldValue, Object newValue) { + + // nulls and equals check done in doFire... + doFirePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index)); + } + + public synchronized void removePropertyChangeListener (String propertyName, PropertyChangeListener listener) { + if ((propertyName != null) && (listener != null)) { + PropertyChangeSupport listeners = children.get(propertyName); + + if (listeners != null) { + listeners.removePropertyChangeListener(listener); + } + } + } + + public synchronized void addPropertyChangeListener (String propertyName, PropertyChangeListener listener) { + if ((listener != null) && (propertyName != null)) { + PropertyChangeSupport listeners = children.get(propertyName); + + if (listeners == null) { + listeners = new PropertyChangeSupport(source); + children.put(propertyName, listeners); + } + + // RI compatibility + if (listener instanceof PropertyChangeListenerProxy) { + PropertyChangeListenerProxy proxy = (PropertyChangeListenerProxy)listener; + + listeners.addPropertyChangeListener(new PropertyChangeListenerProxy(proxy.getPropertyName(), + (PropertyChangeListener)proxy.getListener())); + } else { + listeners.addPropertyChangeListener(listener); + } + } + } + + public synchronized PropertyChangeListener[] getPropertyChangeListeners (String propertyName) { + PropertyChangeSupport listeners = null; + + if (propertyName != null) { + listeners = children.get(propertyName); + } + + return (listeners == null) ? new PropertyChangeListener[0] : listeners.getPropertyChangeListeners(); + } + + public void firePropertyChange (String propertyName, boolean oldValue, boolean newValue) { + PropertyChangeEvent event = createPropertyChangeEvent(propertyName, oldValue, newValue); + doFirePropertyChange(event); + } + + public void fireIndexedPropertyChange (String propertyName, int index, boolean oldValue, boolean newValue) { + + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); + } + } + + public void firePropertyChange (String propertyName, int oldValue, int newValue) { + PropertyChangeEvent event = createPropertyChangeEvent(propertyName, oldValue, newValue); + doFirePropertyChange(event); + } + + public void fireIndexedPropertyChange (String propertyName, int index, int oldValue, int newValue) { + + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Integer.valueOf(oldValue), Integer.valueOf(newValue)); + } + } + + public synchronized boolean hasListeners (String propertyName) { + if (globalListeners.size() > 0) { + return true; + } + boolean result = false; + if (propertyName != null) { + PropertyChangeSupport listeners = children.get(propertyName); + result = (listeners != null && listeners.hasListeners(propertyName)); + } + return result; + } + + public synchronized void removePropertyChangeListener (PropertyChangeListener listener) { + if (listener instanceof PropertyChangeListenerProxy) { + String name = ((PropertyChangeListenerProxy)listener).getPropertyName(); + PropertyChangeListener lst = (PropertyChangeListener)((PropertyChangeListenerProxy)listener).getListener(); + + removePropertyChangeListener(name, lst); + } else { + globalListeners.remove(listener); + } + } + + public synchronized void addPropertyChangeListener (PropertyChangeListener listener) { + if (listener instanceof PropertyChangeListenerProxy) { + String name = ((PropertyChangeListenerProxy)listener).getPropertyName(); + PropertyChangeListener lst = (PropertyChangeListener)((PropertyChangeListenerProxy)listener).getListener(); + addPropertyChangeListener(name, lst); + } else if (listener != null) { + globalListeners.add(listener); + } + } + + public synchronized PropertyChangeListener[] getPropertyChangeListeners () { + ArrayList result = new ArrayList(globalListeners); + for (String propertyName : children.keySet()) { + PropertyChangeSupport namedListener = children.get(propertyName); + PropertyChangeListener[] listeners = namedListener.getPropertyChangeListeners(); + for (int i = 0; i < listeners.length; i++) { + result.add(new PropertyChangeListenerProxy(propertyName, listeners[i])); + } + } + return result.toArray(new PropertyChangeListener[0]); + } + + private void writeObject (ObjectOutputStream oos) throws IOException { + oos.defaultWriteObject(); + PropertyChangeListener[] gListeners = globalListeners.toArray(new PropertyChangeListener[0]); + for (int i = 0; i < gListeners.length; i++) { + if (gListeners[i] instanceof Serializable) { + oos.writeObject(gListeners[i]); + } + } + // Denotes end of list + oos.writeObject(null); + + } + + private void readObject (ObjectInputStream ois) throws IOException, ClassNotFoundException { + ois.defaultReadObject(); + this.globalListeners = new LinkedList(); + if (null == this.children) { + this.children = new Hashtable(); + } + Object listener = null; + do { + // Reads a listener _or_ proxy + listener = ois.readObject(); + if (listener != null) { + addPropertyChangeListener((PropertyChangeListener)listener); + } + } while (listener != null); + } + + public void firePropertyChange (PropertyChangeEvent event) { + doFirePropertyChange(event); + } + + private PropertyChangeEvent createPropertyChangeEvent (String propertyName, Object oldValue, Object newValue) { + return new PropertyChangeEvent(source, propertyName, oldValue, newValue); + } + + @SuppressWarnings("boxing") + private PropertyChangeEvent createPropertyChangeEvent (String propertyName, boolean oldValue, boolean newValue) { + return new PropertyChangeEvent(source, propertyName, oldValue, newValue); + } + + @SuppressWarnings("boxing") + private PropertyChangeEvent createPropertyChangeEvent (String propertyName, int oldValue, int newValue) { + return new PropertyChangeEvent(source, propertyName, oldValue, newValue); + } + + private void doFirePropertyChange (PropertyChangeEvent event) { + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + if (oldValue != null && newValue != null && oldValue.equals(newValue)) { + return; + } + + // Collect up the global listeners + PropertyChangeListener[] gListeners; + synchronized (this) { + gListeners = globalListeners.toArray(new PropertyChangeListener[0]); + } + + // Fire the events for global listeners + for (int i = 0; i < gListeners.length; i++) { + gListeners[i].propertyChange(event); + } + + // Fire the events for the property specific listeners if any + if (event.getPropertyName() != null) { + PropertyChangeSupport namedListener = children.get(event.getPropertyName()); + if (namedListener != null) { + namedListener.firePropertyChange(event); + } + } + + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyDescriptor.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyDescriptor.java index 5cc1d4c9b07..67ef4c3d9c1 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyDescriptor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyDescriptor.java @@ -17,11 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.FeatureDescriptor; -import com.badlogic.gdx.beans.IntrospectionException; -import com.badlogic.gdx.beans.PropertyDescriptor; -import com.badlogic.gdx.beans.PropertyEditor; - import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -30,276 +25,256 @@ import org.apache.harmony.beans.internal.nls.Messages; public class PropertyDescriptor extends FeatureDescriptor { - private Method getter; + private Method getter; - private Method setter; + private Method setter; - private Class propertyEditorClass; + private Class propertyEditorClass; - boolean constrained; + boolean constrained; - boolean bound; + boolean bound; - public PropertyDescriptor(String propertyName, Class beanClass, - String getterName, String setterName) throws IntrospectionException { - super(); - if (beanClass == null) { - throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$ - } - if (propertyName == null || propertyName.length() == 0) { - throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$ - } - this.setName(propertyName); - if (getterName != null) { - if (getterName.length() == 0) { - throw new IntrospectionException( - "read or write method cannot be empty."); //$NON-NLS-1$ - } - try { - setReadMethod(beanClass, getterName); - } catch (IntrospectionException e) { - setReadMethod(beanClass, createDefaultMethodName(propertyName, - "get")); //$NON-NLS-1$ - } - } - if (setterName != null) { - if (setterName.length() == 0) { - throw new IntrospectionException( - "read or write method cannot be empty."); //$NON-NLS-1$ - } - setWriteMethod(beanClass, setterName); - } - } + public PropertyDescriptor (String propertyName, Class beanClass, String getterName, String setterName) + throws IntrospectionException { + super(); + if (beanClass == null) { + throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$ + } + if (propertyName == null || propertyName.length() == 0) { + throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$ + } + this.setName(propertyName); + if (getterName != null) { + if (getterName.length() == 0) { + throw new IntrospectionException("read or write method cannot be empty."); //$NON-NLS-1$ + } + try { + setReadMethod(beanClass, getterName); + } catch (IntrospectionException e) { + setReadMethod(beanClass, createDefaultMethodName(propertyName, "get")); //$NON-NLS-1$ + } + } + if (setterName != null) { + if (setterName.length() == 0) { + throw new IntrospectionException("read or write method cannot be empty."); //$NON-NLS-1$ + } + setWriteMethod(beanClass, setterName); + } + } - public PropertyDescriptor(String propertyName, Method getter, Method setter) - throws IntrospectionException { - super(); - if (propertyName == null || propertyName.length() == 0) { - throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$ - } - this.setName(propertyName); - setReadMethod(getter); - setWriteMethod(setter); - } + public PropertyDescriptor (String propertyName, Method getter, Method setter) throws IntrospectionException { + super(); + if (propertyName == null || propertyName.length() == 0) { + throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$ + } + this.setName(propertyName); + setReadMethod(getter); + setWriteMethod(setter); + } - public PropertyDescriptor(String propertyName, Class beanClass) - throws IntrospectionException { - if (beanClass == null) { - throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$ - } - if (propertyName == null || propertyName.length() == 0) { - throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$ - } - this.setName(propertyName); - try { - setReadMethod(beanClass, - createDefaultMethodName(propertyName, "is")); //$NON-NLS-1$ - } catch (Exception e) { - setReadMethod(beanClass, createDefaultMethodName(propertyName, - "get")); //$NON-NLS-1$ - } + public PropertyDescriptor (String propertyName, Class beanClass) throws IntrospectionException { + if (beanClass == null) { + throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$ + } + if (propertyName == null || propertyName.length() == 0) { + throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$ + } + this.setName(propertyName); + try { + setReadMethod(beanClass, createDefaultMethodName(propertyName, "is")); //$NON-NLS-1$ + } catch (Exception e) { + setReadMethod(beanClass, createDefaultMethodName(propertyName, "get")); //$NON-NLS-1$ + } - setWriteMethod(beanClass, createDefaultMethodName(propertyName, "set")); //$NON-NLS-1$ - } + setWriteMethod(beanClass, createDefaultMethodName(propertyName, "set")); //$NON-NLS-1$ + } - public void setWriteMethod(Method setter) throws IntrospectionException { - if (setter != null) { - int modifiers = setter.getModifiers(); - if (!Modifier.isPublic(modifiers)) { - throw new IntrospectionException(Messages.getString("beans.05")); //$NON-NLS-1$ - } - Class[] parameterTypes = setter.getParameterTypes(); - if (parameterTypes.length != 1) { - throw new IntrospectionException(Messages.getString("beans.06")); //$NON-NLS-1$ - } - Class parameterType = parameterTypes[0]; - Class propertyType = getPropertyType(); - if (propertyType != null && !propertyType.equals(parameterType)) { - throw new IntrospectionException(Messages.getString("beans.07")); //$NON-NLS-1$ - } - } - this.setter = setter; - } + public void setWriteMethod (Method setter) throws IntrospectionException { + if (setter != null) { + int modifiers = setter.getModifiers(); + if (!Modifier.isPublic(modifiers)) { + throw new IntrospectionException(Messages.getString("beans.05")); //$NON-NLS-1$ + } + Class[] parameterTypes = setter.getParameterTypes(); + if (parameterTypes.length != 1) { + throw new IntrospectionException(Messages.getString("beans.06")); //$NON-NLS-1$ + } + Class parameterType = parameterTypes[0]; + Class propertyType = getPropertyType(); + if (propertyType != null && !propertyType.equals(parameterType)) { + throw new IntrospectionException(Messages.getString("beans.07")); //$NON-NLS-1$ + } + } + this.setter = setter; + } - public void setReadMethod(Method getter) throws IntrospectionException { - if (getter != null) { - int modifiers = getter.getModifiers(); - if (!Modifier.isPublic(modifiers)) { - throw new IntrospectionException(Messages.getString("beans.0A")); //$NON-NLS-1$ - } - Class[] parameterTypes = getter.getParameterTypes(); - if (parameterTypes.length != 0) { - throw new IntrospectionException(Messages.getString("beans.08")); //$NON-NLS-1$ - } - Class returnType = getter.getReturnType(); - if (returnType.equals(Void.TYPE)) { - throw new IntrospectionException(Messages.getString("beans.33")); //$NON-NLS-1$ - } - Class propertyType = getPropertyType(); - if ((propertyType != null) && !returnType.equals(propertyType)) { - throw new IntrospectionException(Messages.getString("beans.09")); //$NON-NLS-1$ - } - } - this.getter = getter; - } + public void setReadMethod (Method getter) throws IntrospectionException { + if (getter != null) { + int modifiers = getter.getModifiers(); + if (!Modifier.isPublic(modifiers)) { + throw new IntrospectionException(Messages.getString("beans.0A")); //$NON-NLS-1$ + } + Class[] parameterTypes = getter.getParameterTypes(); + if (parameterTypes.length != 0) { + throw new IntrospectionException(Messages.getString("beans.08")); //$NON-NLS-1$ + } + Class returnType = getter.getReturnType(); + if (returnType.equals(Void.TYPE)) { + throw new IntrospectionException(Messages.getString("beans.33")); //$NON-NLS-1$ + } + Class propertyType = getPropertyType(); + if ((propertyType != null) && !returnType.equals(propertyType)) { + throw new IntrospectionException(Messages.getString("beans.09")); //$NON-NLS-1$ + } + } + this.getter = getter; + } - public Method getWriteMethod() { - return setter; - } + public Method getWriteMethod () { + return setter; + } - public Method getReadMethod() { - return getter; - } + public Method getReadMethod () { + return getter; + } - @Override - public boolean equals(Object object) { - boolean result = object instanceof PropertyDescriptor; - if (result) { - PropertyDescriptor pd = (PropertyDescriptor) object; - boolean gettersAreEqual = (this.getter == null) - && (pd.getReadMethod() == null) || (this.getter != null) - && (this.getter.equals(pd.getReadMethod())); - boolean settersAreEqual = (this.setter == null) - && (pd.getWriteMethod() == null) || (this.setter != null) - && (this.setter.equals(pd.getWriteMethod())); - boolean propertyTypesAreEqual = this.getPropertyType() == pd - .getPropertyType(); - boolean propertyEditorClassesAreEqual = this - .getPropertyEditorClass() == pd.getPropertyEditorClass(); - boolean boundPropertyAreEqual = this.isBound() == pd.isBound(); - boolean constrainedPropertyAreEqual = this.isConstrained() == pd - .isConstrained(); - result = gettersAreEqual && settersAreEqual - && propertyTypesAreEqual && propertyEditorClassesAreEqual - && boundPropertyAreEqual && constrainedPropertyAreEqual; - } - return result; - } + @Override + public boolean equals (Object object) { + boolean result = object instanceof PropertyDescriptor; + if (result) { + PropertyDescriptor pd = (PropertyDescriptor)object; + boolean gettersAreEqual = (this.getter == null) && (pd.getReadMethod() == null) || (this.getter != null) + && (this.getter.equals(pd.getReadMethod())); + boolean settersAreEqual = (this.setter == null) && (pd.getWriteMethod() == null) || (this.setter != null) + && (this.setter.equals(pd.getWriteMethod())); + boolean propertyTypesAreEqual = this.getPropertyType() == pd.getPropertyType(); + boolean propertyEditorClassesAreEqual = this.getPropertyEditorClass() == pd.getPropertyEditorClass(); + boolean boundPropertyAreEqual = this.isBound() == pd.isBound(); + boolean constrainedPropertyAreEqual = this.isConstrained() == pd.isConstrained(); + result = gettersAreEqual && settersAreEqual && propertyTypesAreEqual && propertyEditorClassesAreEqual + && boundPropertyAreEqual && constrainedPropertyAreEqual; + } + return result; + } - @Override - public int hashCode() { - return BeansUtils.getHashCode(getter) + BeansUtils.getHashCode(setter) - + BeansUtils.getHashCode(getPropertyType()) - + BeansUtils.getHashCode(getPropertyEditorClass()) - + BeansUtils.getHashCode(isBound()) - + BeansUtils.getHashCode(isConstrained()); - } + @Override + public int hashCode () { + return BeansUtils.getHashCode(getter) + BeansUtils.getHashCode(setter) + BeansUtils.getHashCode(getPropertyType()) + + BeansUtils.getHashCode(getPropertyEditorClass()) + BeansUtils.getHashCode(isBound()) + + BeansUtils.getHashCode(isConstrained()); + } - public void setPropertyEditorClass(Class propertyEditorClass) { - this.propertyEditorClass = propertyEditorClass; - } + public void setPropertyEditorClass (Class propertyEditorClass) { + this.propertyEditorClass = propertyEditorClass; + } - public Class getPropertyType() { - Class result = null; - if (getter != null) { - result = getter.getReturnType(); - } else if (setter != null) { - Class[] parameterTypes = setter.getParameterTypes(); - result = parameterTypes[0]; - } - return result; - } + public Class getPropertyType () { + Class result = null; + if (getter != null) { + result = getter.getReturnType(); + } else if (setter != null) { + Class[] parameterTypes = setter.getParameterTypes(); + result = parameterTypes[0]; + } + return result; + } - public Class getPropertyEditorClass() { - return propertyEditorClass; - } + public Class getPropertyEditorClass () { + return propertyEditorClass; + } - public void setConstrained(boolean constrained) { - this.constrained = constrained; - } + public void setConstrained (boolean constrained) { + this.constrained = constrained; + } - public void setBound(boolean bound) { - this.bound = bound; - } + public void setBound (boolean bound) { + this.bound = bound; + } - public boolean isConstrained() { - return constrained; - } + public boolean isConstrained () { + return constrained; + } - public boolean isBound() { - return bound; - } + public boolean isBound () { + return bound; + } - String createDefaultMethodName(String propertyName, String prefix) { - String result = null; - if (propertyName != null) { - String bos = BeansUtils.toASCIIUpperCase(propertyName.substring(0, 1)); - String eos = propertyName.substring(1, propertyName.length()); - result = prefix + bos + eos; - } - return result; - } + String createDefaultMethodName (String propertyName, String prefix) { + String result = null; + if (propertyName != null) { + String bos = BeansUtils.toASCIIUpperCase(propertyName.substring(0, 1)); + String eos = propertyName.substring(1, propertyName.length()); + result = prefix + bos + eos; + } + return result; + } - void setReadMethod(Class beanClass, String getterName) - throws IntrospectionException { - try { - Method readMethod = beanClass.getMethod(getterName, new Class[] {}); - setReadMethod(readMethod); - } catch (Exception e) { - throw new IntrospectionException(e.getLocalizedMessage()); - } - } + void setReadMethod (Class beanClass, String getterName) throws IntrospectionException { + try { + Method readMethod = beanClass.getMethod(getterName, new Class[] {}); + setReadMethod(readMethod); + } catch (Exception e) { + throw new IntrospectionException(e.getLocalizedMessage()); + } + } - void setWriteMethod(Class beanClass, String setterName) - throws IntrospectionException { - Method writeMethod = null; - try { - if (getter != null) { - writeMethod = beanClass.getMethod(setterName, - new Class[] { getter.getReturnType() }); - } else { - Class clazz = beanClass; - Method[] methods = null; - while (clazz != null && writeMethod == null) { - methods = clazz.getDeclaredMethods(); - for (Method method : methods) { - if (setterName.equals(method.getName())) { - if (method.getParameterTypes().length == 1) { - writeMethod = method; - break; - } - } - } - clazz = clazz.getSuperclass(); - } - } - } catch (Exception e) { - throw new IntrospectionException(e.getLocalizedMessage()); - } - if (writeMethod == null) { - throw new IntrospectionException(Messages.getString( - "beans.64", setterName)); //$NON-NLS-1$ - } - setWriteMethod(writeMethod); - } + void setWriteMethod (Class beanClass, String setterName) throws IntrospectionException { + Method writeMethod = null; + try { + if (getter != null) { + writeMethod = beanClass.getMethod(setterName, new Class[] {getter.getReturnType()}); + } else { + Class clazz = beanClass; + Method[] methods = null; + while (clazz != null && writeMethod == null) { + methods = clazz.getDeclaredMethods(); + for (Method method : methods) { + if (setterName.equals(method.getName())) { + if (method.getParameterTypes().length == 1) { + writeMethod = method; + break; + } + } + } + clazz = clazz.getSuperclass(); + } + } + } catch (Exception e) { + throw new IntrospectionException(e.getLocalizedMessage()); + } + if (writeMethod == null) { + throw new IntrospectionException(Messages.getString("beans.64", setterName)); //$NON-NLS-1$ + } + setWriteMethod(writeMethod); + } - public PropertyEditor createPropertyEditor(Object bean) { - PropertyEditor editor; - if (propertyEditorClass == null) { - return null; - } - if (!PropertyEditor.class.isAssignableFrom(propertyEditorClass)) { - // beans.48=Property editor is not assignable from the - // PropertyEditor interface - throw new ClassCastException(Messages.getString("beans.48")); //$NON-NLS-1$ - } - try { - Constructor constr; - try { - // try to look for the constructor with single Object argument - constr = propertyEditorClass.getConstructor(Object.class); - editor = (PropertyEditor) constr.newInstance(bean); - } catch (NoSuchMethodException e) { - // try no-argument constructor - constr = propertyEditorClass.getConstructor(); - editor = (PropertyEditor) constr.newInstance(); - } - } catch (Exception e) { - // beans.47=Unable to instantiate property editor - RuntimeException re = new RuntimeException(Messages - .getString("beans.47"), e); //$NON-NLS-1$ - throw re; - } - return editor; - } + public PropertyEditor createPropertyEditor (Object bean) { + PropertyEditor editor; + if (propertyEditorClass == null) { + return null; + } + if (!PropertyEditor.class.isAssignableFrom(propertyEditorClass)) { + // beans.48=Property editor is not assignable from the + // PropertyEditor interface + throw new ClassCastException(Messages.getString("beans.48")); //$NON-NLS-1$ + } + try { + Constructor constr; + try { + // try to look for the constructor with single Object argument + constr = propertyEditorClass.getConstructor(Object.class); + editor = (PropertyEditor)constr.newInstance(bean); + } catch (NoSuchMethodException e) { + // try no-argument constructor + constr = propertyEditorClass.getConstructor(); + editor = (PropertyEditor)constr.newInstance(); + } + } catch (Exception e) { + // beans.47=Unable to instantiate property editor + RuntimeException re = new RuntimeException(Messages.getString("beans.47"), e); //$NON-NLS-1$ + throw re; + } + return editor; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditor.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditor.java index 0ccf7ee141b..7d0b7745bc4 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditor.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditor.java @@ -21,31 +21,29 @@ import java.awt.Graphics; import java.awt.Rectangle; -import com.badlogic.gdx.beans.PropertyChangeListener; - public interface PropertyEditor { - public void paintValue(Graphics gfx, Rectangle box); + public void paintValue (Graphics gfx, Rectangle box); - public void setAsText(String text) throws IllegalArgumentException; + public void setAsText (String text) throws IllegalArgumentException; - public String[] getTags(); + public String[] getTags (); - public String getJavaInitializationString(); + public String getJavaInitializationString (); - public String getAsText(); + public String getAsText (); - public void setValue(Object value); + public void setValue (Object value); - public Object getValue(); + public Object getValue (); - public void removePropertyChangeListener(PropertyChangeListener listener); + public void removePropertyChangeListener (PropertyChangeListener listener); - public void addPropertyChangeListener(PropertyChangeListener listener); + public void addPropertyChangeListener (PropertyChangeListener listener); - public Component getCustomEditor(); + public Component getCustomEditor (); - public boolean supportsCustomEditor(); + public boolean supportsCustomEditor (); - public boolean isPaintable(); + public boolean isPaintable (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorManager.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorManager.java index 8ad98a75f61..630d759f77b 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorManager.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorManager.java @@ -17,107 +17,98 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyEditor; -import com.badlogic.gdx.beans.PropertyEditorManager; - import java.util.HashMap; import java.util.Map; public class PropertyEditorManager { - private static String[] path = { "org.apache.harmony.beans.editors" }; //$NON-NLS-1$ - - private static final Map, Class> registeredEditors = new HashMap, Class>(); - - public PropertyEditorManager() { - // expected - } - - public static void registerEditor(Class targetType, Class editorClass) { - if (targetType == null) { - throw new NullPointerException(); - } - SecurityManager sm = System.getSecurityManager(); - - if (sm != null) { - sm.checkPropertiesAccess(); - } - - if (editorClass != null) { - registeredEditors.put(targetType, editorClass); - } else { - registeredEditors.remove(targetType); - } - } - - private static PropertyEditor loadEditor(Class targetType, - String className) throws ClassNotFoundException, - IllegalAccessException, InstantiationException { - ClassLoader loader = targetType.getClassLoader(); - if (loader == null) { - loader = ClassLoader.getSystemClassLoader(); - } - try { - return (PropertyEditor) loader.loadClass(className).newInstance(); - } catch (ClassNotFoundException e) { - // Ignored - } - - return (PropertyEditor) Thread.currentThread().getContextClassLoader() - .loadClass(className).newInstance(); - } - - public static synchronized PropertyEditor findEditor(Class targetType) { - if (targetType == null) { - throw new NullPointerException(); - } - Class editorClass = registeredEditors.get(targetType); - - if (editorClass != null) { - try { - return (PropertyEditor) editorClass.newInstance(); - } catch (Exception e) { - // expected - } - } - String editorClassName = targetType.getName() + "Editor"; //$NON-NLS-1$ - - try { - return loadEditor(targetType, editorClassName); - } catch (Exception exception) { - // expected - } - String shortEditorClassName = (targetType.isPrimitive() - ? (editorClassName.substring(0, 1).toUpperCase() - + editorClassName.substring(1)) - : editorClassName.substring( - editorClassName.lastIndexOf('.') + 1)); - - for (String element : path) { - if (element == null) { - continue; - } - try { - return loadEditor(targetType, element + '.' - + shortEditorClassName); - } catch (Exception e) { - // expected - } - } - return null; - } - - public static void setEditorSearchPath(String[] apath) { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPropertiesAccess(); - } - synchronized(PropertyEditorManager.class){ - path = (apath == null)? new String[0] : apath; - } - } - - public static synchronized String[] getEditorSearchPath() { - return path.clone(); - } + private static String[] path = {"org.apache.harmony.beans.editors"}; //$NON-NLS-1$ + + private static final Map, Class> registeredEditors = new HashMap, Class>(); + + public PropertyEditorManager () { + // expected + } + + public static void registerEditor (Class targetType, Class editorClass) { + if (targetType == null) { + throw new NullPointerException(); + } + SecurityManager sm = System.getSecurityManager(); + + if (sm != null) { + sm.checkPropertiesAccess(); + } + + if (editorClass != null) { + registeredEditors.put(targetType, editorClass); + } else { + registeredEditors.remove(targetType); + } + } + + private static PropertyEditor loadEditor (Class targetType, String className) throws ClassNotFoundException, + IllegalAccessException, InstantiationException { + ClassLoader loader = targetType.getClassLoader(); + if (loader == null) { + loader = ClassLoader.getSystemClassLoader(); + } + try { + return (PropertyEditor)loader.loadClass(className).newInstance(); + } catch (ClassNotFoundException e) { + // Ignored + } + + return (PropertyEditor)Thread.currentThread().getContextClassLoader().loadClass(className).newInstance(); + } + + public static synchronized PropertyEditor findEditor (Class targetType) { + if (targetType == null) { + throw new NullPointerException(); + } + Class editorClass = registeredEditors.get(targetType); + + if (editorClass != null) { + try { + return (PropertyEditor)editorClass.newInstance(); + } catch (Exception e) { + // expected + } + } + String editorClassName = targetType.getName() + "Editor"; //$NON-NLS-1$ + + try { + return loadEditor(targetType, editorClassName); + } catch (Exception exception) { + // expected + } + String shortEditorClassName = (targetType.isPrimitive() ? (editorClassName.substring(0, 1).toUpperCase() + editorClassName + .substring(1)) : editorClassName.substring(editorClassName.lastIndexOf('.') + 1)); + + for (String element : path) { + if (element == null) { + continue; + } + try { + return loadEditor(targetType, element + '.' + shortEditorClassName); + } catch (Exception e) { + // expected + } + } + return null; + } + + public static void setEditorSearchPath (String[] apath) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPropertiesAccess(); + } + synchronized (PropertyEditorManager.class) { + path = (apath == null) ? new String[0] : apath; + } + } + + public static synchronized String[] getEditorSearchPath () { + return path.clone(); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorSupport.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorSupport.java index ea54ac32085..a4885cd7cec 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorSupport.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyEditorSupport.java @@ -14,16 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.badlogic.gdx.beans; import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; - -import com.badlogic.gdx.beans.PropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyChangeListener; -import com.badlogic.gdx.beans.PropertyEditor; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -32,105 +28,100 @@ public class PropertyEditorSupport implements PropertyEditor { - Object source = null; - - List listeners = new ArrayList(); - - Object newValue = null; - - public PropertyEditorSupport(Object source) { - if (source == null) { - throw new NullPointerException(Messages.getString("beans.0C")); //$NON-NLS-1$ - } - this.source = source; - } - - public PropertyEditorSupport() { - source = this; - } - - public void paintValue(Graphics gfx, Rectangle box) { - // expected - } - - public void setAsText(String text) throws IllegalArgumentException { - if (newValue instanceof String) { - setValue(text); - } else { - throw new IllegalArgumentException(text); - } - } - - public String[] getTags() { - return null; - } - - public String getJavaInitializationString() { - return "???"; //$NON-NLS-1$ - } - - public String getAsText() { - return newValue == null ? "null" : newValue.toString(); //$NON-NLS-1$ - } - - public void setValue(Object value) { - this.newValue = value; - firePropertyChange(); - } - - public Object getValue() { - return newValue; - } - - public void setSource(Object source) { - this.source = source; - } - - public Object getSource() { - return source; - } - - public synchronized void removePropertyChangeListener( - PropertyChangeListener listener) { - if (listeners != null) { - listeners.remove(listener); - } - } - - public synchronized void addPropertyChangeListener( - PropertyChangeListener listener) { - listeners.add(listener); - } - - public Component getCustomEditor() { - return null; - } - - public boolean supportsCustomEditor() { - return false; - } - - public boolean isPaintable() { - return false; - } - - public void firePropertyChange() { - if (listeners.isEmpty()) { - return; - } - - List copy = new ArrayList( - listeners.size()); - synchronized (listeners) { - copy.addAll(listeners); - } - - PropertyChangeEvent changeAllEvent = new PropertyChangeEvent(source, - null, null, null); - for (Iterator listenersItr = copy.iterator(); listenersItr - .hasNext();) { - PropertyChangeListener listna = listenersItr.next(); - listna.propertyChange(changeAllEvent); - } - } + Object source = null; + + List listeners = new ArrayList(); + + Object newValue = null; + + public PropertyEditorSupport (Object source) { + if (source == null) { + throw new NullPointerException(Messages.getString("beans.0C")); //$NON-NLS-1$ + } + this.source = source; + } + + public PropertyEditorSupport () { + source = this; + } + + public void paintValue (Graphics gfx, Rectangle box) { + // expected + } + + public void setAsText (String text) throws IllegalArgumentException { + if (newValue instanceof String) { + setValue(text); + } else { + throw new IllegalArgumentException(text); + } + } + + public String[] getTags () { + return null; + } + + public String getJavaInitializationString () { + return "???"; //$NON-NLS-1$ + } + + public String getAsText () { + return newValue == null ? "null" : newValue.toString(); //$NON-NLS-1$ + } + + public void setValue (Object value) { + this.newValue = value; + firePropertyChange(); + } + + public Object getValue () { + return newValue; + } + + public void setSource (Object source) { + this.source = source; + } + + public Object getSource () { + return source; + } + + public synchronized void removePropertyChangeListener (PropertyChangeListener listener) { + if (listeners != null) { + listeners.remove(listener); + } + } + + public synchronized void addPropertyChangeListener (PropertyChangeListener listener) { + listeners.add(listener); + } + + public Component getCustomEditor () { + return null; + } + + public boolean supportsCustomEditor () { + return false; + } + + public boolean isPaintable () { + return false; + } + + public void firePropertyChange () { + if (listeners.isEmpty()) { + return; + } + + List copy = new ArrayList(listeners.size()); + synchronized (listeners) { + copy.addAll(listeners); + } + + PropertyChangeEvent changeAllEvent = new PropertyChangeEvent(source, null, null, null); + for (Iterator listenersItr = copy.iterator(); listenersItr.hasNext();) { + PropertyChangeListener listna = listenersItr.next(); + listna.propertyChange(changeAllEvent); + } + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/PropertyVetoException.java b/extensions/beans/src/com/badlogic/gdx/beans/PropertyVetoException.java index d541b5cf409..8060b6ca513 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/PropertyVetoException.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/PropertyVetoException.java @@ -17,40 +17,30 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; - -/** - * Indicates that a proposed property change is unacceptable. - */ +/** Indicates that a proposed property change is unacceptable. */ public class PropertyVetoException extends Exception { - private static final long serialVersionUID = 129596057694162164L; + private static final long serialVersionUID = 129596057694162164L; - private final PropertyChangeEvent evt; + private final PropertyChangeEvent evt; - /** - *

        - * Constructs an instance with a message and the change event. - *

        - * - * @param message - * A description of the veto. - * @param event - * The event that was vetoed. - */ - public PropertyVetoException(String message, PropertyChangeEvent event) { - super(message); - this.evt = event; - } + /**

        + * Constructs an instance with a message and the change event. + *

        + * + * @param message A description of the veto. + * @param event The event that was vetoed. */ + public PropertyVetoException (String message, PropertyChangeEvent event) { + super(message); + this.evt = event; + } - /** - *

        - * Gets the property change event. - *

        - * - * @return An instance of {@link PropertyChangeEvent} - */ - public PropertyChangeEvent getPropertyChangeEvent() { - return evt; - } + /**

        + * Gets the property change event. + *

        + * + * @return An instance of {@link PropertyChangeEvent} */ + public PropertyChangeEvent getPropertyChangeEvent () { + return evt; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/ProxyPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/ProxyPersistenceDelegate.java index ddfe22bd3a9..85d83ae5a08 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/ProxyPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/ProxyPersistenceDelegate.java @@ -17,37 +17,33 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; class ProxyPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder out) { - assert oldInstance instanceof Proxy : oldInstance; - Class[] interfaces = oldInstance.getClass().getInterfaces(); - InvocationHandler handler = Proxy.getInvocationHandler(oldInstance); - return new Expression(oldInstance, Proxy.class, "newProxyInstance", //$NON-NLS-1$ - new Object[] { oldInstance.getClass().getClassLoader(), interfaces, handler }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder out) { + assert oldInstance instanceof Proxy : oldInstance; + Class[] interfaces = oldInstance.getClass().getInterfaces(); + InvocationHandler handler = Proxy.getInvocationHandler(oldInstance); + return new Expression(oldInstance, Proxy.class, "newProxyInstance", //$NON-NLS-1$ + new Object[] {oldInstance.getClass().getClassLoader(), interfaces, handler}); + } + + @Override + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder out) { + // check for consistency + assert oldInstance instanceof Proxy : oldInstance; + assert newInstance instanceof Proxy : newInstance; + super.initialize(type, oldInstance, newInstance, out); + } - @Override - protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { - // check for consistency - assert oldInstance instanceof Proxy : oldInstance; - assert newInstance instanceof Proxy : newInstance; - super.initialize(type, oldInstance, newInstance, out); - } + @Override + protected boolean mutatesTo (Object oldInstance, Object newInstance) { + if ((oldInstance instanceof Proxy) && (newInstance instanceof Proxy)) { + return super.mutatesTo(oldInstance, newInstance); + } - @Override - protected boolean mutatesTo(Object oldInstance, Object newInstance) { - if((oldInstance instanceof Proxy) && (newInstance instanceof Proxy)){ - return super.mutatesTo(oldInstance, newInstance); - } - - return false; - } + return false; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/SimpleBeanInfo.java b/extensions/beans/src/com/badlogic/gdx/beans/SimpleBeanInfo.java index 8414c96ce9e..e3c3134dcd1 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/SimpleBeanInfo.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/SimpleBeanInfo.java @@ -19,63 +19,56 @@ import java.awt.Image; import java.awt.Toolkit; - -import com.badlogic.gdx.beans.BeanDescriptor; -import com.badlogic.gdx.beans.BeanInfo; -import com.badlogic.gdx.beans.EventSetDescriptor; -import com.badlogic.gdx.beans.MethodDescriptor; -import com.badlogic.gdx.beans.PropertyDescriptor; - import java.net.URL; public class SimpleBeanInfo implements BeanInfo { - public SimpleBeanInfo() { - // expected - } + public SimpleBeanInfo () { + // expected + } + + public Image loadImage (String resourceName) { + if (null == resourceName) { + return null; + } + + URL file = getClass().getResource(resourceName); - public Image loadImage(String resourceName) { - if (null == resourceName) { - return null; - } - - URL file = getClass().getResource(resourceName); - - if (file != null) { - return Toolkit.getDefaultToolkit().createImage(file); - } - return null; - } + if (file != null) { + return Toolkit.getDefaultToolkit().createImage(file); + } + return null; + } - public PropertyDescriptor[] getPropertyDescriptors() { - return null; - } + public PropertyDescriptor[] getPropertyDescriptors () { + return null; + } - public MethodDescriptor[] getMethodDescriptors() { - return null; - } + public MethodDescriptor[] getMethodDescriptors () { + return null; + } - public EventSetDescriptor[] getEventSetDescriptors() { - return null; - } + public EventSetDescriptor[] getEventSetDescriptors () { + return null; + } - public BeanInfo[] getAdditionalBeanInfo() { - return null; - } + public BeanInfo[] getAdditionalBeanInfo () { + return null; + } - public BeanDescriptor getBeanDescriptor() { - return null; - } + public BeanDescriptor getBeanDescriptor () { + return null; + } - public Image getIcon(int iconKind) { - return null; - } + public Image getIcon (int iconKind) { + return null; + } - public int getDefaultPropertyIndex() { - return -1; - } + public int getDefaultPropertyIndex () { + return -1; + } - public int getDefaultEventIndex() { - return -1; - } + public int getDefaultEventIndex () { + return -1; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/StandardBeanInfo.java b/extensions/beans/src/com/badlogic/gdx/beans/StandardBeanInfo.java index bfcebbc567a..d329ae07641 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/StandardBeanInfo.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/StandardBeanInfo.java @@ -17,21 +17,7 @@ package com.badlogic.gdx.beans; -import static com.badlogic.gdx.beans.Introspector.decapitalize; - import java.awt.Image; - -import com.badlogic.gdx.beans.BeanDescriptor; -import com.badlogic.gdx.beans.BeanInfo; -import com.badlogic.gdx.beans.EventSetDescriptor; -import com.badlogic.gdx.beans.IndexedPropertyDescriptor; -import com.badlogic.gdx.beans.IntrospectionException; -import com.badlogic.gdx.beans.MethodDescriptor; -import com.badlogic.gdx.beans.PropertyChangeListener; -import com.badlogic.gdx.beans.PropertyDescriptor; -import com.badlogic.gdx.beans.PropertyVetoException; -import com.badlogic.gdx.beans.SimpleBeanInfo; - import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; @@ -43,1485 +29,1340 @@ import java.util.Map; import java.util.TooManyListenersException; +import static com.badlogic.gdx.beans.Introspector.*; + class StandardBeanInfo extends SimpleBeanInfo { - // Prefixes for methods that set or get a Property - private static final String PREFIX_IS = "is"; //$NON-NLS-1$ + // Prefixes for methods that set or get a Property + private static final String PREFIX_IS = "is"; //$NON-NLS-1$ - private static final String PREFIX_GET = "get"; //$NON-NLS-1$ + private static final String PREFIX_GET = "get"; //$NON-NLS-1$ - private static final String PREFIX_SET = "set"; //$NON-NLS-1$ + private static final String PREFIX_SET = "set"; //$NON-NLS-1$ - // Prefix and suffix for Event related methods - private static final String PREFIX_ADD = "add"; //$NON-NLS-1$ + // Prefix and suffix for Event related methods + private static final String PREFIX_ADD = "add"; //$NON-NLS-1$ - private static final String PREFIX_REMOVE = "remove"; //$NON-NLS-1$ + private static final String PREFIX_REMOVE = "remove"; //$NON-NLS-1$ - private static final String SUFFIX_LISTEN = "Listener"; //$NON-NLS-1$ + private static final String SUFFIX_LISTEN = "Listener"; //$NON-NLS-1$ - private static final String STR_NORMAL = "normal"; //$NON-NLS-1$ + private static final String STR_NORMAL = "normal"; //$NON-NLS-1$ - private static final String STR_INDEXED = "indexed"; //$NON-NLS-1$ + private static final String STR_INDEXED = "indexed"; //$NON-NLS-1$ - private static final String STR_VALID = "valid"; //$NON-NLS-1$ + private static final String STR_VALID = "valid"; //$NON-NLS-1$ - private static final String STR_INVALID = "invalid"; //$NON-NLS-1$ + private static final String STR_INVALID = "invalid"; //$NON-NLS-1$ - private static final String STR_PROPERTY_TYPE = "PropertyType"; //$NON-NLS-1$ + private static final String STR_PROPERTY_TYPE = "PropertyType"; //$NON-NLS-1$ - private static final String STR_IS_CONSTRAINED = "isConstrained"; //$NON-NLS-1$ + private static final String STR_IS_CONSTRAINED = "isConstrained"; //$NON-NLS-1$ - private static final String STR_SETTERS = "setters"; //$NON-NLS-1$ + private static final String STR_SETTERS = "setters"; //$NON-NLS-1$ - private static final String STR_GETTERS = "getters"; //$NON-NLS-1$ + private static final String STR_GETTERS = "getters"; //$NON-NLS-1$ - private boolean explicitMethods = false; + private boolean explicitMethods = false; - private boolean explicitProperties = false; + private boolean explicitProperties = false; - private boolean explicitEvents = false; + private boolean explicitEvents = false; - private BeanInfo explicitBeanInfo = null; + private BeanInfo explicitBeanInfo = null; - private EventSetDescriptor[] events = null; + private EventSetDescriptor[] events = null; - private MethodDescriptor[] methods = null; + private MethodDescriptor[] methods = null; - private PropertyDescriptor[] properties = null; + private PropertyDescriptor[] properties = null; - private BeanDescriptor beanDescriptor = null; + private BeanDescriptor beanDescriptor = null; - BeanInfo[] additionalBeanInfo = null; + BeanInfo[] additionalBeanInfo = null; - private Class beanClass; + private Class beanClass; - private int defaultEventIndex = -1; + private int defaultEventIndex = -1; - private int defaultPropertyIndex = -1; + private int defaultPropertyIndex = -1; - private static PropertyComparator comparator = new PropertyComparator(); + private static PropertyComparator comparator = new PropertyComparator(); - private Object[] icon = new Object[4]; + private Object[] icon = new Object[4]; - private boolean canAddPropertyChangeListener; + private boolean canAddPropertyChangeListener; - private boolean canRemovePropertyChangeListener; + private boolean canRemovePropertyChangeListener; - StandardBeanInfo(Class beanClass, BeanInfo explicitBeanInfo, Class stopClass) - throws IntrospectionException { - this.beanClass = beanClass; - /*-------------------------------------------------------------------------------------- - * There are 3 aspects of BeanInfo that must be supplied: - * a) PropertyDescriptors - * b) MethodDescriptors - * c) EventSetDescriptors - * Each of these may be optionally provided in the explicitBeanInfo object relating to - * this bean. Where the explicitBeanInfo provides one of these aspects, it is used - * without question and no introspection of the beanClass is performed for that aspect. - * There are also 3 optional items of BeanInfo that may be provided by the - * explicitBeanInfo object: - * 1) BeanDescriptor - * 2) DefaultEventIndex - * 3) DefaultPropertyIndex - * These aspects of the beanClass cannot be derived through introspection of the class. - * If they are not provided by the explicitBeanInfo, then they must be left null in the - * returned BeanInfo, otherwise they will be copied from the explicitBeanInfo - --------------------------------------------------------------------------------------*/ - if (explicitBeanInfo != null) { - this.explicitBeanInfo = explicitBeanInfo; - events = explicitBeanInfo.getEventSetDescriptors(); - methods = explicitBeanInfo.getMethodDescriptors(); - properties = explicitBeanInfo.getPropertyDescriptors(); - defaultEventIndex = explicitBeanInfo.getDefaultEventIndex(); - if (defaultEventIndex < 0 || defaultEventIndex >= events.length) { - defaultEventIndex = -1; - } - defaultPropertyIndex = explicitBeanInfo.getDefaultPropertyIndex(); - if (defaultPropertyIndex < 0 - || defaultPropertyIndex >= properties.length) { - defaultPropertyIndex = -1; - } - additionalBeanInfo = explicitBeanInfo.getAdditionalBeanInfo(); - for (int i = 0; i < 4; i++) { - icon[i] = explicitBeanInfo.getIcon(i + 1); - } - - if (events != null) - explicitEvents = true; - if (methods != null) - explicitMethods = true; - if (properties != null) - explicitProperties = true; - } - - if (methods == null) { - methods = introspectMethods(); - } - - if (properties == null) { - properties = introspectProperties(stopClass); - } - - if (events == null) { - events = introspectEvents(); - } - } - - @Override - public BeanInfo[] getAdditionalBeanInfo() { - return null; - } - - @Override - public EventSetDescriptor[] getEventSetDescriptors() { - return events; - } - - @Override - public MethodDescriptor[] getMethodDescriptors() { - return methods; - } - - @Override - public PropertyDescriptor[] getPropertyDescriptors() { - return properties; - } - - @Override - public BeanDescriptor getBeanDescriptor() { - if (beanDescriptor == null) { - if (explicitBeanInfo != null) { - beanDescriptor = explicitBeanInfo.getBeanDescriptor(); - } - if (beanDescriptor == null) { - beanDescriptor = new BeanDescriptor(beanClass); - } - } - return beanDescriptor; - } - - @Override - public int getDefaultEventIndex() { - return this.defaultEventIndex; - } - - @Override - public int getDefaultPropertyIndex() { - return this.defaultPropertyIndex; - } - - @Override - public Image getIcon(int iconKind) { - return (Image)icon[iconKind - 1]; - } - - void mergeBeanInfo(BeanInfo beanInfo, boolean force) - throws IntrospectionException { - if (force || !explicitProperties) { - PropertyDescriptor[] superDescs = beanInfo.getPropertyDescriptors(); - if (superDescs != null) { - if (getPropertyDescriptors() != null) { - properties = mergeProps(superDescs, beanInfo - .getDefaultPropertyIndex()); - } else { - properties = superDescs; - defaultPropertyIndex = beanInfo.getDefaultPropertyIndex(); - } - } - } - - if (force || !explicitMethods) { - MethodDescriptor[] superMethods = beanInfo.getMethodDescriptors(); - if (superMethods != null) { - if (methods != null) { - methods = mergeMethods(superMethods); - } else { - methods = superMethods; - } - } - } - - if (force || !explicitEvents) { - EventSetDescriptor[] superEvents = beanInfo - .getEventSetDescriptors(); - if (superEvents != null) { - if (events != null) { - events = mergeEvents(superEvents, beanInfo - .getDefaultEventIndex()); - } else { - events = superEvents; - defaultEventIndex = beanInfo.getDefaultEventIndex(); - } - } - } - } - - /* - * merge the PropertyDescriptor with superclass - */ - private PropertyDescriptor[] mergeProps(PropertyDescriptor[] superDescs, - int superDefaultIndex) throws IntrospectionException { - // FIXME:change to OO way as EventSetD and MethodD - HashMap subMap = internalAsMap(properties); - String defaultPropertyName = null; - if (defaultPropertyIndex >= 0 - && defaultPropertyIndex < properties.length) { - defaultPropertyName = properties[defaultPropertyIndex].getName(); - } else if (superDefaultIndex >= 0 - && superDefaultIndex < superDescs.length) { - defaultPropertyName = superDescs[superDefaultIndex].getName(); - } - - for (int i = 0; i < superDescs.length; i++) { - PropertyDescriptor superDesc = superDescs[i]; - String propertyName = superDesc.getName(); - if (!subMap.containsKey(propertyName)) { - subMap.put(propertyName, superDesc); - continue; - } - - Object value = subMap.get(propertyName); - // if sub and super are both PropertyDescriptor - Method subGet = ((PropertyDescriptor) value).getReadMethod(); - Method subSet = ((PropertyDescriptor) value).getWriteMethod(); - Method superGet = superDesc.getReadMethod(); - Method superSet = superDesc.getWriteMethod(); - - Class superType = superDesc.getPropertyType(); - Class superIndexedType = null; - Class subType = ((PropertyDescriptor) value).getPropertyType(); - Class subIndexedType = null; - - if (value instanceof IndexedPropertyDescriptor) { - subIndexedType = ((IndexedPropertyDescriptor) value) - .getIndexedPropertyType(); - } - if (superDesc instanceof IndexedPropertyDescriptor) { - superIndexedType = ((IndexedPropertyDescriptor) superDesc) - .getIndexedPropertyType(); - } - - // if superDesc is PropertyDescriptor - if (superIndexedType == null) { - PropertyDescriptor subDesc = (PropertyDescriptor) value; - // Sub is PropertyDescriptor - if (subIndexedType == null) { - // Same property type - if (subType != null && superType != null - && subType.getName() != null - && subType.getName().equals(superType.getName())) { - if (superGet != null - && (subGet == null || superGet.equals(subGet))) { - subDesc.setReadMethod(superGet); - } - if (superSet != null - && (subSet == null || superSet.equals(subSet))) { - subDesc.setWriteMethod(superSet); - } - if (subType == boolean.class && subGet != null - && superGet != null) { - if (superGet.getName().startsWith(PREFIX_IS)) { - subDesc.setReadMethod(superGet); - } - } - } else { // Different type - if ((subGet == null || subSet == null) - && (superGet != null)) { - subDesc = new PropertyDescriptor(propertyName, - superGet, superSet); - if (subGet != null) { - String subGetName = subGet.getName(); - Method method = null; - MethodDescriptor[] introspectMethods = introspectMethods(); - for (MethodDescriptor methodDesc : introspectMethods) { - method = methodDesc.getMethod(); - if (method != subGet - && subGetName.equals(method - .getName()) - && method.getParameterTypes().length == 0 - && method.getReturnType() == superType) { - subDesc.setReadMethod(method); - break; - } - } - } - } - } - } else { // Sub is IndexedPropertyDescriptor and super is PropertyDescriptor - if (superType != null - && (superType.isArray()) - && (superType.getComponentType().getName() - .equals(subIndexedType.getName()))) { - if ((subGet == null) && (superGet != null)) { - subDesc.setReadMethod(superGet); - } - if ((subSet == null) && (superSet != null)) { - subDesc.setWriteMethod(superSet); - } - } // different type do nothing - // sub is indexed pd and super is normal pd - if (subIndexedType == boolean.class - && superType == boolean.class) { - Method subIndexedSet = ((IndexedPropertyDescriptor) subDesc) - .getIndexedWriteMethod(); - if (subGet == null && subSet == null - && subIndexedSet != null && superGet != null) { - try { - subSet = beanClass.getDeclaredMethod( - subIndexedSet.getName(), boolean.class); - } catch (Exception e) { - // ignored - } - if (subSet != null) { - // Cast sub into PropertyDescriptor - subDesc = new PropertyDescriptor(propertyName, - superGet, subSet); - } - } - } - } - subMap.put(propertyName, subDesc); - } else { // Super is IndexedPropertyDescriptor - if (subIndexedType == null) { // Sub is PropertyDescriptor - if (subType != null - && subType.isArray() - && (subType.getComponentType().getName() - .equals(superIndexedType.getName()))) { - // Same type - if (subGet != null) { - superDesc.setReadMethod(subGet); - } - if (subSet != null) { - superDesc.setWriteMethod(subSet); - } - subMap.put(propertyName, superDesc); - } else { - // subDesc is PropertyDescriptor - // superDesc is IndexedPropertyDescriptor - - // fill null subGet or subSet method with superClass's - if (subGet == null || subSet == null) { - Class beanSuperClass = beanClass.getSuperclass(); - String methodSuffix = capitalize(propertyName); - Method method = null; - if (subGet == null) { - // subGet is null - if (subType == boolean.class) { - try { - method = beanSuperClass - .getDeclaredMethod(PREFIX_IS - + methodSuffix); - } catch (Exception e) { - // ignored - } - } else { - try { - method = beanSuperClass - .getDeclaredMethod(PREFIX_GET - + methodSuffix); - } catch (Exception e) { - // ignored - } - } - if (method != null - && !Modifier.isStatic(method - .getModifiers()) - && method.getReturnType() == subType) { - ((PropertyDescriptor) value) - .setReadMethod(method); - } - } else { - // subSet is null - try { - method = beanSuperClass.getDeclaredMethod( - PREFIX_SET + methodSuffix, subType); - } catch (Exception e) { - // ignored - } - if (method != null - && !Modifier.isStatic(method - .getModifiers()) - && method.getReturnType() == void.class) { - ((PropertyDescriptor) value) - .setWriteMethod(method); - } - } - } - subMap.put(propertyName, (PropertyDescriptor) value); - } - } else if (subIndexedType.getName().equals( - superIndexedType.getName())) { - // Sub is IndexedPropertyDescriptor and Same type - IndexedPropertyDescriptor subDesc = (IndexedPropertyDescriptor) value; - if ((subGet == null) && (superGet != null)) { - subDesc.setReadMethod(superGet); - } - if ((subSet == null) && (superSet != null)) { - subDesc.setWriteMethod(superSet); - } - IndexedPropertyDescriptor superIndexedDesc = (IndexedPropertyDescriptor) superDesc; - - if ((subDesc.getIndexedReadMethod() == null) - && (superIndexedDesc.getIndexedReadMethod() != null)) { - subDesc.setIndexedReadMethod(superIndexedDesc - .getIndexedReadMethod()); - } - - if ((subDesc.getIndexedWriteMethod() == null) - && (superIndexedDesc.getIndexedWriteMethod() != null)) { - subDesc.setIndexedWriteMethod(superIndexedDesc - .getIndexedWriteMethod()); - } - - subMap.put(propertyName, subDesc); - } // Different indexed type, do nothing - } - mergeAttributes((PropertyDescriptor) value, superDesc); - } - - PropertyDescriptor[] theDescs = new PropertyDescriptor[subMap.size()]; - subMap.values().toArray(theDescs); - - if (defaultPropertyName != null && !explicitProperties) { - for (int i = 0; i < theDescs.length; i++) { - if (defaultPropertyName.equals(theDescs[i].getName())) { - defaultPropertyIndex = i; - break; - } - } - } - return theDescs; - } - - private String capitalize(String name) { - if (name == null) { - return null; - } - // The rule for decapitalize is that: - // If the first letter of the string is Upper Case, make it lower case - // UNLESS the second letter of the string is also Upper Case, in which case no - // changes are made. - if (name.length() == 0 || (name.length() > 1 && Character.isUpperCase(name.charAt(1)))) { - return name; - } - - char[] chars = name.toCharArray(); - chars[0] = Character.toUpperCase(chars[0]); - return new String(chars); - } - - private static void mergeAttributes(PropertyDescriptor subDesc, - PropertyDescriptor superDesc) { - // FIXME: this is just temp workaround, need more elegant solution to - // handle this - subDesc.hidden |= superDesc.hidden; - subDesc.expert |= superDesc.expert; - subDesc.preferred |= superDesc.preferred; - subDesc.bound |= superDesc.bound; - subDesc.constrained |= superDesc.constrained; - subDesc.name = superDesc.name; - if (subDesc.shortDescription == null - && superDesc.shortDescription != null) { - subDesc.shortDescription = superDesc.shortDescription; - } - if (subDesc.displayName == null && superDesc.displayName != null) { - subDesc.displayName = superDesc.displayName; - } - } - - /* - * merge the MethodDescriptor - */ - private MethodDescriptor[] mergeMethods(MethodDescriptor[] superDescs) { - HashMap subMap = internalAsMap(methods); - - for (MethodDescriptor superMethod : superDescs) { - String methodName = getQualifiedName(superMethod.getMethod()); - MethodDescriptor method = subMap.get(methodName); - if (method == null) { - subMap.put(methodName, superMethod); - } else { - method.merge(superMethod); - } - } - MethodDescriptor[] theMethods = new MethodDescriptor[subMap.size()]; - subMap.values().toArray(theMethods); - return theMethods; - } - - private EventSetDescriptor[] mergeEvents(EventSetDescriptor[] otherEvents, - int otherDefaultIndex) { - HashMap subMap = internalAsMap(events); - String defaultEventName = null; - if (defaultEventIndex >= 0 && defaultEventIndex < events.length) { - defaultEventName = events[defaultEventIndex].getName(); - } else if (otherDefaultIndex >= 0 - && otherDefaultIndex < otherEvents.length) { - defaultEventName = otherEvents[otherDefaultIndex].getName(); - } - - for (EventSetDescriptor event : otherEvents) { - String eventName = event.getName(); - EventSetDescriptor subEvent = subMap.get(eventName); - if (subEvent == null) { - subMap.put(eventName, event); - } else { - subEvent.merge(event); - } - } - - EventSetDescriptor[] theEvents = new EventSetDescriptor[subMap.size()]; - subMap.values().toArray(theEvents); - - if (defaultEventName != null && !explicitEvents) { - for (int i = 0; i < theEvents.length; i++) { - if (defaultEventName.equals(theEvents[i].getName())) { - defaultEventIndex = i; - break; - } - } - } - return theEvents; - } - - private static HashMap internalAsMap( - PropertyDescriptor[] propertyDescs) { - HashMap map = new HashMap(); - for (int i = 0; i < propertyDescs.length; i++) { - map.put(propertyDescs[i].getName(), propertyDescs[i]); - } - return map; - } - - private static HashMap internalAsMap( - MethodDescriptor[] theDescs) { - HashMap map = new HashMap(); - for (int i = 0; i < theDescs.length; i++) { - String qualifiedName = getQualifiedName(theDescs[i].getMethod()); - map.put(qualifiedName, theDescs[i]); - } - return map; - } - - private static HashMap internalAsMap( - EventSetDescriptor[] theDescs) { - HashMap map = new HashMap(); - for (int i = 0; i < theDescs.length; i++) { - map.put(theDescs[i].getName(), theDescs[i]); - } - return map; - } - - private static String getQualifiedName(Method method) { - String qualifiedName = method.getName(); - Class[] paramTypes = method.getParameterTypes(); - if (paramTypes != null) { - for (int i = 0; i < paramTypes.length; i++) { - qualifiedName += "_" + paramTypes[i].getName(); //$NON-NLS-1$ - } - } - return qualifiedName; - } - - /** - * Introspects the supplied class and returns a list of the public methods - * of the class - * - * @return An array of MethodDescriptors with the public methods. null if - * there are no public methods - */ - private MethodDescriptor[] introspectMethods() { - return introspectMethods(false, beanClass); - } - - private MethodDescriptor[] introspectMethods(boolean includeSuper) { - return introspectMethods(includeSuper, beanClass); - } - - private MethodDescriptor[] introspectMethods(boolean includeSuper, - Class introspectorClass) { - - // Get the list of methods belonging to this class - Method[] basicMethods = includeSuper ? introspectorClass.getMethods() - : introspectorClass.getDeclaredMethods(); - - if (basicMethods == null || basicMethods.length == 0) - return null; - - ArrayList methodList = new ArrayList( - basicMethods.length); - - // Loop over the methods found, looking for public non-static methods - for (int i = 0; i < basicMethods.length; i++) { - int modifiers = basicMethods[i].getModifiers(); - if (Modifier.isPublic(modifiers)) { - // Allocate a MethodDescriptor for this method - MethodDescriptor theDescriptor = new MethodDescriptor( - basicMethods[i]); - methodList.add(theDescriptor); - } - } - - // Get the list of public methods into the returned array - int methodCount = methodList.size(); - MethodDescriptor[] theMethods = null; - if (methodCount > 0) { - theMethods = new MethodDescriptor[methodCount]; - theMethods = methodList.toArray(theMethods); - } - - return theMethods; - } - - /** - * Introspects the supplied class and returns a list of the Properties of - * the class - * - * @param stopClass - - * the to introspecting at - * @return The list of Properties as an array of PropertyDescriptors - * @throws IntrospectionException - */ - @SuppressWarnings("unchecked") - private PropertyDescriptor[] introspectProperties(Class stopClass) - throws IntrospectionException { - - // Get descriptors for the public methods - MethodDescriptor[] methodDescriptors = introspectMethods(); - - if (methodDescriptors == null) { - return null; - } - - ArrayList methodList = new ArrayList(); - // Loop over the methods found, looking for public non-static methods - for (int index = 0; index < methodDescriptors.length; index++) { - int modifiers = methodDescriptors[index].getMethod().getModifiers(); - if (!Modifier.isStatic(modifiers)) { - methodList.add(methodDescriptors[index]); - } - } - - // Get the list of public non-static methods into an array - int methodCount = methodList.size(); - MethodDescriptor[] theMethods = null; - if (methodCount > 0) { - theMethods = new MethodDescriptor[methodCount]; - theMethods = methodList.toArray(theMethods); - } - - if (theMethods == null) { - return null; - } - - HashMap propertyTable = new HashMap( - theMethods.length); - - // Search for methods that either get or set a Property - for (int i = 0; i < theMethods.length; i++) { - introspectGet(theMethods[i].getMethod(), propertyTable); - introspectSet(theMethods[i].getMethod(), propertyTable); - } - - // fix possible getter & setter collisions - fixGetSet(propertyTable); - - // If there are listener methods, should be bound. - MethodDescriptor[] allMethods = introspectMethods(true); - if (stopClass != null) { - MethodDescriptor[] excludeMethods = introspectMethods(true, - stopClass); - if (excludeMethods != null) { - ArrayList tempMethods = new ArrayList(); - for (MethodDescriptor method : allMethods) { - if (!isInSuper(method, excludeMethods)) { - tempMethods.add(method); - } - } - allMethods = tempMethods - .toArray(new MethodDescriptor[0]); - } - } - for (int i = 0; i < allMethods.length; i++) { - introspectPropertyListener(allMethods[i].getMethod()); - } - // Put the properties found into the PropertyDescriptor array - ArrayList propertyList = new ArrayList(); - - for (Map.Entry entry : propertyTable.entrySet()) { - String propertyName = entry.getKey(); - HashMap table = entry.getValue(); - if (table == null) { - continue; - } - String normalTag = (String) table.get(STR_NORMAL); - String indexedTag = (String) table.get(STR_INDEXED); - - if ((normalTag == null) && (indexedTag == null)) { - continue; - } - - Method get = (Method) table.get(STR_NORMAL + PREFIX_GET); - Method set = (Method) table.get(STR_NORMAL + PREFIX_SET); - Method indexedGet = (Method) table.get(STR_INDEXED + PREFIX_GET); - Method indexedSet = (Method) table.get(STR_INDEXED + PREFIX_SET); - - PropertyDescriptor propertyDesc = null; - if (indexedTag == null) { - propertyDesc = new PropertyDescriptor(propertyName, get, set); - } else { - try { - propertyDesc = new IndexedPropertyDescriptor(propertyName, - get, set, indexedGet, indexedSet); - } catch (IntrospectionException e) { - // If the getter and the indexGetter is not compatible, try - // getter/setter is null; - propertyDesc = new IndexedPropertyDescriptor(propertyName, - null, null, indexedGet, indexedSet); - } - } - // RI set propretyDescriptor as bound. FIXME - // propertyDesc.setBound(true); - if (canAddPropertyChangeListener && canRemovePropertyChangeListener) { - propertyDesc.setBound(true); - } else { - propertyDesc.setBound(false); - } - if (table.get(STR_IS_CONSTRAINED) == Boolean.TRUE) { //$NON-NLS-1$ - propertyDesc.setConstrained(true); - } - propertyList.add(propertyDesc); - } - - PropertyDescriptor[] theProperties = new PropertyDescriptor[propertyList - .size()]; - propertyList.toArray(theProperties); - return theProperties; - } - - private boolean isInSuper(MethodDescriptor method, - MethodDescriptor[] excludeMethods) { - for (MethodDescriptor m : excludeMethods) { - if (method.getMethod().equals(m.getMethod())) { - return true; - } - } - return false; - } - - @SuppressWarnings("nls") - private void introspectPropertyListener(Method theMethod) { - String methodName = theMethod.getName(); - Class[] param = theMethod.getParameterTypes(); - if (param.length != 1) { - return; - } - if (methodName.equals("addPropertyChangeListener") - && param[0].equals(PropertyChangeListener.class)) - canAddPropertyChangeListener = true; - if (methodName.equals("removePropertyChangeListener") - && param[0].equals(PropertyChangeListener.class)) - canRemovePropertyChangeListener = true; - } - - @SuppressWarnings("unchecked") - private static void introspectGet(Method theMethod, - HashMap propertyTable) { - - String methodName = theMethod.getName(); - int prefixLength = 0; - String propertyName; - Class propertyType; - Class[] paramTypes; - HashMap table; - ArrayList getters; - - if (methodName == null) { - return; - } - - if (methodName.startsWith(PREFIX_GET)) { - prefixLength = PREFIX_GET.length(); - } - - if (methodName.startsWith(PREFIX_IS)) { - prefixLength = PREFIX_IS.length(); - } - - if (prefixLength == 0) { - return; - } - - propertyName = decapitalize(methodName.substring(prefixLength)); - - // validate property name - if (!isValidProperty(propertyName)) { - return; - } - - // validate return type - propertyType = theMethod.getReturnType(); - - if (propertyType == null || propertyType == void.class) { - return; - } - - // isXXX return boolean - if (prefixLength == 2) { - if (!(propertyType == boolean.class)) { - return; - } - } - - // validate parameter types - paramTypes = theMethod.getParameterTypes(); - if (paramTypes.length > 1 - || (paramTypes.length == 1 && paramTypes[0] != int.class)) { - return; - } - - table = propertyTable.get(propertyName); - if (table == null) { - table = new HashMap(); - propertyTable.put(propertyName, table); - } - - getters = (ArrayList) table.get(STR_GETTERS); - if (getters == null) { - getters = new ArrayList(); - table.put(STR_GETTERS, getters); - } - - // add current method as a valid getter - getters.add(theMethod); - } - - @SuppressWarnings("unchecked") - private static void introspectSet(Method theMethod, - HashMap propertyTable) { - - String methodName = theMethod.getName(); - if (methodName == null) { - return; - } - String propertyName; - Class returnType; - Class[] paramTypes; - - // setter method should never return type other than void - returnType = theMethod.getReturnType(); - if (returnType != void.class) { - return; - } - - if (methodName == null || !methodName.startsWith(PREFIX_SET)) { - return; - } - - propertyName = decapitalize(methodName.substring(PREFIX_SET.length())); - - // validate property name - if (!isValidProperty(propertyName)) { - return; - } - - // It seems we do not need to validate return type - - // validate param types - paramTypes = theMethod.getParameterTypes(); - - if (paramTypes.length == 0 || paramTypes.length > 2 - || (paramTypes.length == 2 && paramTypes[0] != int.class)) { - return; - } - - HashMap table = propertyTable.get(propertyName); - if (table == null) { - table = new HashMap(); - propertyTable.put(propertyName, table); - } - - ArrayList setters = (ArrayList) table.get(STR_SETTERS); - if (setters == null) { - setters = new ArrayList(); - table.put(STR_SETTERS, setters); - } - - // handle constrained - Class[] exceptions = theMethod.getExceptionTypes(); - for (Class e : exceptions) { - if (e.equals(PropertyVetoException.class)) { - table.put(STR_IS_CONSTRAINED, Boolean.TRUE); //$NON-NLS-1$ - } - } - - // add new setter - setters.add(theMethod); - } - - /** - * Checks and fixs all cases when several incompatible checkers / getters - * were specified for single property. - * - * @param propertyTable - * @throws IntrospectionException - */ - private void fixGetSet(HashMap propertyTable) - throws IntrospectionException { - - if (propertyTable == null) { - return; - } - - for (Map.Entry entry : propertyTable.entrySet()) { - HashMap table = entry.getValue(); - ArrayList getters = (ArrayList) table - .get(STR_GETTERS); - ArrayList setters = (ArrayList) table - .get(STR_SETTERS); - - Method normalGetter = null; - Method indexedGetter = null; - Method normalSetter = null; - Method indexedSetter = null; - - Class normalPropType = null; - Class indexedPropType = null; - - if (getters == null) { - getters = new ArrayList(); - } - - if (setters == null) { - setters = new ArrayList(); - } - - // retrieve getters - Class[] paramTypes = null; - String methodName = null; - for (Method getter : getters) { - paramTypes = getter.getParameterTypes(); - methodName = getter.getName(); - // checks if it's a normal getter - if (paramTypes == null || paramTypes.length == 0) { - // normal getter found - if (normalGetter == null - || methodName.startsWith(PREFIX_IS)) { - normalGetter = getter; - } - } - - // checks if it's an indexed getter - if (paramTypes != null && paramTypes.length == 1 - && paramTypes[0] == int.class) { - // indexed getter found - if (indexedGetter == null - || methodName.startsWith(PREFIX_GET) - || (methodName.startsWith(PREFIX_IS) && !indexedGetter - .getName().startsWith(PREFIX_GET))) { - indexedGetter = getter; - } - } - } - - // retrieve normal setter - if (normalGetter != null) { - // Now we will try to look for normal setter of the same type. - Class propertyType = normalGetter.getReturnType(); - - for (Method setter : setters) { - if (setter.getParameterTypes().length == 1 - && propertyType - .equals(setter.getParameterTypes()[0])) { - normalSetter = setter; - break; - } - } - } else { - // Normal getter wasn't defined. Let's look for the last - // defined setter - - for (Method setter : setters) { - if (setter.getParameterTypes().length == 1) { - normalSetter = setter; - } - } - } - - // retrieve indexed setter - if (indexedGetter != null) { - // Now we will try to look for indexed setter of the same type. - Class propertyType = indexedGetter.getReturnType(); - - for (Method setter : setters) { - if (setter.getParameterTypes().length == 2 - && setter.getParameterTypes()[0] == int.class - && propertyType - .equals(setter.getParameterTypes()[1])) { - indexedSetter = setter; - break; - } - } - } else { - // Indexed getter wasn't defined. Let's look for the last - // defined indexed setter - - for (Method setter : setters) { - if (setter.getParameterTypes().length == 2 - && setter.getParameterTypes()[0] == int.class) { - indexedSetter = setter; - } - } - } - - // determine property type - if (normalGetter != null) { - normalPropType = normalGetter.getReturnType(); - } else if (normalSetter != null) { - normalPropType = normalSetter.getParameterTypes()[0]; - } - - // determine indexed getter/setter type - if (indexedGetter != null) { - indexedPropType = indexedGetter.getReturnType(); - } else if (indexedSetter != null) { - indexedPropType = indexedSetter.getParameterTypes()[1]; - } - - // convert array-typed normal getters to indexed getters - if (normalGetter != null && normalGetter.getReturnType().isArray()) { - - } - - // RULES - // These rules were created after performing extensive black-box - // testing of RI - - // RULE1 - // Both normal getter and setter of the same type were defined; - // no indexed getter/setter *PAIR* of the other type defined - if (normalGetter != null && normalSetter != null - && (indexedGetter == null || indexedSetter == null)) { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); - continue; - } - - // RULE2 - // normal getter and/or setter was defined; no indexed - // getters & setters defined - if ((normalGetter != null || normalSetter != null) - && indexedGetter == null && indexedSetter == null) { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); - continue; - } - - // RULE3 - // mix of normal / indexed getters and setters are defined. Types - // are compatible - if ((normalGetter != null || normalSetter != null) - && (indexedGetter != null || indexedSetter != null)) { - // (1)!A!B!C!D - if (normalGetter != null && normalSetter != null - && indexedGetter != null && indexedSetter != null) { - if (indexedGetter.getName().startsWith(PREFIX_GET)) { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, - normalPropType); - - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, - indexedPropType); - } else { - if (normalPropType != boolean.class - && normalGetter.getName().startsWith(PREFIX_IS)) { - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, - indexedPropType); - } else { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, - normalPropType); - } - } - continue; - } - - // (2)!AB!C!D - if (normalGetter != null && normalSetter == null - && indexedGetter != null && indexedSetter != null) { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); - - table.put(STR_INDEXED, STR_VALID); - if (indexedGetter.getName().startsWith(PREFIX_GET)) { - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - } - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); - continue; - } - - // (3)A!B!C!D - if (normalGetter == null && normalSetter != null - && indexedGetter != null && indexedSetter != null) { - table.put(STR_INDEXED, STR_VALID); - if (indexedGetter.getName().startsWith(PREFIX_GET)) { - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - } - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); - continue; - } - - // (4)!AB!CD - if (normalGetter != null && normalSetter == null - && indexedGetter != null && indexedSetter == null) { - if (indexedGetter.getName().startsWith(PREFIX_GET)) { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, - normalPropType); - - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, - indexedPropType); - } else { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, - normalPropType); - } - continue; - } - - // (5)A!B!CD - if (normalGetter == null && normalSetter != null - && indexedGetter != null && indexedSetter == null) { - if (indexedGetter.getName().startsWith(PREFIX_GET)) { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, - normalPropType); - - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, - indexedPropType); - } else { - table.put(STR_NORMAL, STR_VALID); - table.put(STR_NORMAL + PREFIX_GET, normalGetter); - table.put(STR_NORMAL + PREFIX_SET, normalSetter); - table.put(STR_NORMAL + STR_PROPERTY_TYPE, - normalPropType); - } - continue; - } - - // (6)!ABC!D - if (normalGetter != null && normalSetter == null - && indexedGetter == null && indexedSetter != null) { - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); - continue; - } - - // (7)A!BC!D - if (normalGetter == null && normalSetter != null - && indexedGetter == null && indexedSetter != null) { - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); - continue; - } - } - - // RULE4 - // no normal normal getter / setter. - // Only indexed getter and/or setter is given - // no normal setters / getters defined - if (normalSetter == null && normalGetter == null - && (indexedGetter != null || indexedSetter != null)) { - if (indexedGetter != null - && indexedGetter.getName().startsWith(PREFIX_IS)) { - if (indexedSetter != null) { - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, - indexedPropType); - } - continue; - } - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); - continue; - } - - // RULE5 - // Both indexed getter and setter methods are defined - // no normal getter/setter *PAIR* of the other type defined - if ((normalSetter != null || normalGetter != null) - && indexedGetter != null && indexedSetter != null) { - table.put(STR_INDEXED, STR_VALID); - table.put(STR_INDEXED + PREFIX_GET, indexedGetter); - table.put(STR_INDEXED + PREFIX_SET, indexedSetter); - table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); - continue; - } - - // default rule - invalid property - table.put(STR_NORMAL, STR_INVALID); - table.put(STR_INDEXED, STR_INVALID); - } - - } - - /** - * Introspects the supplied Bean class and returns a list of the Events of - * the class - * - * @return the events - * @throws IntrospectionException - */ - @SuppressWarnings("unchecked") - private EventSetDescriptor[] introspectEvents() throws IntrospectionException { - // Get descriptors for the public methods - // FIXME: performance - MethodDescriptor[] theMethods = introspectMethods(); - - if (theMethods == null) - return null; - - HashMap eventTable = new HashMap( - theMethods.length); - - // Search for methods that add an Event Listener - for (int i = 0; i < theMethods.length; i++) { - introspectListenerMethods(PREFIX_ADD, theMethods[i].getMethod(), - eventTable); - introspectListenerMethods(PREFIX_REMOVE, theMethods[i].getMethod(), - eventTable); - introspectGetListenerMethods(theMethods[i].getMethod(), eventTable); - } - - ArrayList eventList = new ArrayList(); - for (Map.Entry entry : eventTable.entrySet()) { - HashMap table = entry.getValue(); - Method add = (Method) table.get(PREFIX_ADD); - Method remove = (Method) table.get(PREFIX_REMOVE); - - if ((add == null) || (remove == null)) { - continue; - } - - Method get = (Method) table.get(PREFIX_GET); - Class listenerType = (Class) table.get("listenerType"); //$NON-NLS-1$ - Method[] listenerMethods = (Method[]) table.get("listenerMethods"); //$NON-NLS-1$ - EventSetDescriptor eventSetDescriptor = new EventSetDescriptor( - decapitalize(entry.getKey()), listenerType, listenerMethods, add, - remove, get); - - eventSetDescriptor.setUnicast(table.get("isUnicast") != null); //$NON-NLS-1$ - eventList.add(eventSetDescriptor); - } - - EventSetDescriptor[] theEvents = new EventSetDescriptor[eventList - .size()]; - eventList.toArray(theEvents); - - return theEvents; - } - - /* - * find the add, remove listener method - */ - @SuppressWarnings("unchecked") - private static void introspectListenerMethods(String type, - Method theMethod, HashMap methodsTable) { - String methodName = theMethod.getName(); - if (methodName == null) { - return; - } - - if (!((methodName.startsWith(type)) && (methodName - .endsWith(SUFFIX_LISTEN)))) { - return; - } - - String listenerName = methodName.substring(type.length()); - String eventName = listenerName.substring(0, listenerName - .lastIndexOf(SUFFIX_LISTEN)); - if ((eventName == null) || (eventName.length() == 0)) { - return; - } - - Class[] paramTypes = theMethod.getParameterTypes(); - if ((paramTypes == null) || (paramTypes.length != 1)) { - return; - } - - Class listenerType = paramTypes[0]; - - if (!EventListener.class.isAssignableFrom(listenerType)) { - return; - } - - if (!listenerType.getName().endsWith(listenerName)) { - return; - } - - HashMap table = methodsTable.get(eventName); - if (table == null) { - table = new HashMap(); - } - // put listener type - if (table.get("listenerType") == null) { //$NON-NLS-1$ - table.put("listenerType", listenerType); //$NON-NLS-1$ - table.put("listenerMethods", //$NON-NLS-1$ - introspectListenerMethods(listenerType)); - } - // put add / remove - table.put(type, theMethod); - - // determine isUnicast() - if (type.equals(PREFIX_ADD)) { - Class[] exceptionTypes = theMethod.getExceptionTypes(); - if (exceptionTypes != null) { - for (int i = 0; i < exceptionTypes.length; i++) { - if (exceptionTypes[i].getName().equals( - TooManyListenersException.class.getName())) { - table.put("isUnicast", "true"); //$NON-NLS-1$//$NON-NLS-2$ - break; - } - } - } - } - - methodsTable.put(eventName, table); - } - - private static Method[] introspectListenerMethods(Class listenerType) { - Method[] methods = listenerType.getDeclaredMethods(); - ArrayList list = new ArrayList(); - for (int i = 0; i < methods.length; i++) { - Class[] paramTypes = methods[i].getParameterTypes(); - if (paramTypes.length != 1) { - continue; - } - - if (EventObject.class.isAssignableFrom(paramTypes[0])) { - list.add(methods[i]); - } - } - Method[] matchedMethods = new Method[list.size()]; - list.toArray(matchedMethods); - return matchedMethods; - } - - @SuppressWarnings("unchecked") - private static void introspectGetListenerMethods(Method theMethod, - HashMap methodsTable) { - String type = PREFIX_GET; - - String methodName = theMethod.getName(); - if (methodName == null) { - return; - } - - if (!((methodName.startsWith(type)) && (methodName - .endsWith(SUFFIX_LISTEN + "s")))) { //$NON-NLS-1$ - return; - } - - String listenerName = methodName.substring(type.length(), methodName - .length() - 1); - String eventName = listenerName.substring(0, listenerName - .lastIndexOf(SUFFIX_LISTEN)); - if ((eventName == null) || (eventName.length() == 0)) { - return; - } - - Class[] paramTypes = theMethod.getParameterTypes(); - if ((paramTypes == null) || (paramTypes.length != 0)) { - return; - } - - Class returnType = theMethod.getReturnType(); - if ((returnType.getComponentType() == null) - || (!returnType.getComponentType().getName().endsWith( - listenerName))) { - return; - } - - HashMap table = methodsTable.get(eventName); - if (table == null) { - table = new HashMap(); - } - // put add / remove - table.put(type, theMethod); - methodsTable.put(eventName, table); - } - - private static boolean isValidProperty(String propertyName) { - return (propertyName != null) && (propertyName.length() != 0); - } - - private static class PropertyComparator implements - Comparator { - public int compare(PropertyDescriptor object1, - PropertyDescriptor object2) { - return object1.getName().compareTo(object2.getName()); - } - - } - - // TODO - void init() { - if (this.events == null) { - events = new EventSetDescriptor[0]; - } - if (this.properties == null) { - this.properties = new PropertyDescriptor[0]; - } - - if (properties != null) { - String defaultPropertyName = (defaultPropertyIndex != -1 ? properties[defaultPropertyIndex] - .getName() - : null); - Arrays.sort(properties, comparator); - if (null != defaultPropertyName) { - for (int i = 0; i < properties.length; i++) { - if (defaultPropertyName.equals(properties[i].getName())) { - defaultPropertyIndex = i; - break; - } - } - } - } - } + StandardBeanInfo (Class beanClass, BeanInfo explicitBeanInfo, Class stopClass) throws IntrospectionException { + this.beanClass = beanClass; + /*-------------------------------------------------------------------------------------- + * There are 3 aspects of BeanInfo that must be supplied: + * a) PropertyDescriptors + * b) MethodDescriptors + * c) EventSetDescriptors + * Each of these may be optionally provided in the explicitBeanInfo object relating to + * this bean. Where the explicitBeanInfo provides one of these aspects, it is used + * without question and no introspection of the beanClass is performed for that aspect. + * There are also 3 optional items of BeanInfo that may be provided by the + * explicitBeanInfo object: + * 1) BeanDescriptor + * 2) DefaultEventIndex + * 3) DefaultPropertyIndex + * These aspects of the beanClass cannot be derived through introspection of the class. + * If they are not provided by the explicitBeanInfo, then they must be left null in the + * returned BeanInfo, otherwise they will be copied from the explicitBeanInfo + --------------------------------------------------------------------------------------*/ + if (explicitBeanInfo != null) { + this.explicitBeanInfo = explicitBeanInfo; + events = explicitBeanInfo.getEventSetDescriptors(); + methods = explicitBeanInfo.getMethodDescriptors(); + properties = explicitBeanInfo.getPropertyDescriptors(); + defaultEventIndex = explicitBeanInfo.getDefaultEventIndex(); + if (defaultEventIndex < 0 || defaultEventIndex >= events.length) { + defaultEventIndex = -1; + } + defaultPropertyIndex = explicitBeanInfo.getDefaultPropertyIndex(); + if (defaultPropertyIndex < 0 || defaultPropertyIndex >= properties.length) { + defaultPropertyIndex = -1; + } + additionalBeanInfo = explicitBeanInfo.getAdditionalBeanInfo(); + for (int i = 0; i < 4; i++) { + icon[i] = explicitBeanInfo.getIcon(i + 1); + } + + if (events != null) explicitEvents = true; + if (methods != null) explicitMethods = true; + if (properties != null) explicitProperties = true; + } + + if (methods == null) { + methods = introspectMethods(); + } + + if (properties == null) { + properties = introspectProperties(stopClass); + } + + if (events == null) { + events = introspectEvents(); + } + } + + @Override + public BeanInfo[] getAdditionalBeanInfo () { + return null; + } + + @Override + public EventSetDescriptor[] getEventSetDescriptors () { + return events; + } + + @Override + public MethodDescriptor[] getMethodDescriptors () { + return methods; + } + + @Override + public PropertyDescriptor[] getPropertyDescriptors () { + return properties; + } + + @Override + public BeanDescriptor getBeanDescriptor () { + if (beanDescriptor == null) { + if (explicitBeanInfo != null) { + beanDescriptor = explicitBeanInfo.getBeanDescriptor(); + } + if (beanDescriptor == null) { + beanDescriptor = new BeanDescriptor(beanClass); + } + } + return beanDescriptor; + } + + @Override + public int getDefaultEventIndex () { + return this.defaultEventIndex; + } + + @Override + public int getDefaultPropertyIndex () { + return this.defaultPropertyIndex; + } + + @Override + public Image getIcon (int iconKind) { + return (Image)icon[iconKind - 1]; + } + + void mergeBeanInfo (BeanInfo beanInfo, boolean force) throws IntrospectionException { + if (force || !explicitProperties) { + PropertyDescriptor[] superDescs = beanInfo.getPropertyDescriptors(); + if (superDescs != null) { + if (getPropertyDescriptors() != null) { + properties = mergeProps(superDescs, beanInfo.getDefaultPropertyIndex()); + } else { + properties = superDescs; + defaultPropertyIndex = beanInfo.getDefaultPropertyIndex(); + } + } + } + + if (force || !explicitMethods) { + MethodDescriptor[] superMethods = beanInfo.getMethodDescriptors(); + if (superMethods != null) { + if (methods != null) { + methods = mergeMethods(superMethods); + } else { + methods = superMethods; + } + } + } + + if (force || !explicitEvents) { + EventSetDescriptor[] superEvents = beanInfo.getEventSetDescriptors(); + if (superEvents != null) { + if (events != null) { + events = mergeEvents(superEvents, beanInfo.getDefaultEventIndex()); + } else { + events = superEvents; + defaultEventIndex = beanInfo.getDefaultEventIndex(); + } + } + } + } + + /* + * merge the PropertyDescriptor with superclass + */ + private PropertyDescriptor[] mergeProps (PropertyDescriptor[] superDescs, int superDefaultIndex) throws IntrospectionException { + // FIXME:change to OO way as EventSetD and MethodD + HashMap subMap = internalAsMap(properties); + String defaultPropertyName = null; + if (defaultPropertyIndex >= 0 && defaultPropertyIndex < properties.length) { + defaultPropertyName = properties[defaultPropertyIndex].getName(); + } else if (superDefaultIndex >= 0 && superDefaultIndex < superDescs.length) { + defaultPropertyName = superDescs[superDefaultIndex].getName(); + } + + for (int i = 0; i < superDescs.length; i++) { + PropertyDescriptor superDesc = superDescs[i]; + String propertyName = superDesc.getName(); + if (!subMap.containsKey(propertyName)) { + subMap.put(propertyName, superDesc); + continue; + } + + Object value = subMap.get(propertyName); + // if sub and super are both PropertyDescriptor + Method subGet = ((PropertyDescriptor)value).getReadMethod(); + Method subSet = ((PropertyDescriptor)value).getWriteMethod(); + Method superGet = superDesc.getReadMethod(); + Method superSet = superDesc.getWriteMethod(); + + Class superType = superDesc.getPropertyType(); + Class superIndexedType = null; + Class subType = ((PropertyDescriptor)value).getPropertyType(); + Class subIndexedType = null; + + if (value instanceof IndexedPropertyDescriptor) { + subIndexedType = ((IndexedPropertyDescriptor)value).getIndexedPropertyType(); + } + if (superDesc instanceof IndexedPropertyDescriptor) { + superIndexedType = ((IndexedPropertyDescriptor)superDesc).getIndexedPropertyType(); + } + + // if superDesc is PropertyDescriptor + if (superIndexedType == null) { + PropertyDescriptor subDesc = (PropertyDescriptor)value; + // Sub is PropertyDescriptor + if (subIndexedType == null) { + // Same property type + if (subType != null && superType != null && subType.getName() != null + && subType.getName().equals(superType.getName())) { + if (superGet != null && (subGet == null || superGet.equals(subGet))) { + subDesc.setReadMethod(superGet); + } + if (superSet != null && (subSet == null || superSet.equals(subSet))) { + subDesc.setWriteMethod(superSet); + } + if (subType == boolean.class && subGet != null && superGet != null) { + if (superGet.getName().startsWith(PREFIX_IS)) { + subDesc.setReadMethod(superGet); + } + } + } else { // Different type + if ((subGet == null || subSet == null) && (superGet != null)) { + subDesc = new PropertyDescriptor(propertyName, superGet, superSet); + if (subGet != null) { + String subGetName = subGet.getName(); + Method method = null; + MethodDescriptor[] introspectMethods = introspectMethods(); + for (MethodDescriptor methodDesc : introspectMethods) { + method = methodDesc.getMethod(); + if (method != subGet && subGetName.equals(method.getName()) && method.getParameterTypes().length == 0 + && method.getReturnType() == superType) { + subDesc.setReadMethod(method); + break; + } + } + } + } + } + } else { // Sub is IndexedPropertyDescriptor and super is PropertyDescriptor + if (superType != null && (superType.isArray()) + && (superType.getComponentType().getName().equals(subIndexedType.getName()))) { + if ((subGet == null) && (superGet != null)) { + subDesc.setReadMethod(superGet); + } + if ((subSet == null) && (superSet != null)) { + subDesc.setWriteMethod(superSet); + } + } // different type do nothing + // sub is indexed pd and super is normal pd + if (subIndexedType == boolean.class && superType == boolean.class) { + Method subIndexedSet = ((IndexedPropertyDescriptor)subDesc).getIndexedWriteMethod(); + if (subGet == null && subSet == null && subIndexedSet != null && superGet != null) { + try { + subSet = beanClass.getDeclaredMethod(subIndexedSet.getName(), boolean.class); + } catch (Exception e) { + // ignored + } + if (subSet != null) { + // Cast sub into PropertyDescriptor + subDesc = new PropertyDescriptor(propertyName, superGet, subSet); + } + } + } + } + subMap.put(propertyName, subDesc); + } else { // Super is IndexedPropertyDescriptor + if (subIndexedType == null) { // Sub is PropertyDescriptor + if (subType != null && subType.isArray() + && (subType.getComponentType().getName().equals(superIndexedType.getName()))) { + // Same type + if (subGet != null) { + superDesc.setReadMethod(subGet); + } + if (subSet != null) { + superDesc.setWriteMethod(subSet); + } + subMap.put(propertyName, superDesc); + } else { + // subDesc is PropertyDescriptor + // superDesc is IndexedPropertyDescriptor + + // fill null subGet or subSet method with superClass's + if (subGet == null || subSet == null) { + Class beanSuperClass = beanClass.getSuperclass(); + String methodSuffix = capitalize(propertyName); + Method method = null; + if (subGet == null) { + // subGet is null + if (subType == boolean.class) { + try { + method = beanSuperClass.getDeclaredMethod(PREFIX_IS + methodSuffix); + } catch (Exception e) { + // ignored + } + } else { + try { + method = beanSuperClass.getDeclaredMethod(PREFIX_GET + methodSuffix); + } catch (Exception e) { + // ignored + } + } + if (method != null && !Modifier.isStatic(method.getModifiers()) && method.getReturnType() == subType) { + ((PropertyDescriptor)value).setReadMethod(method); + } + } else { + // subSet is null + try { + method = beanSuperClass.getDeclaredMethod(PREFIX_SET + methodSuffix, subType); + } catch (Exception e) { + // ignored + } + if (method != null && !Modifier.isStatic(method.getModifiers()) && method.getReturnType() == void.class) { + ((PropertyDescriptor)value).setWriteMethod(method); + } + } + } + subMap.put(propertyName, (PropertyDescriptor)value); + } + } else if (subIndexedType.getName().equals(superIndexedType.getName())) { + // Sub is IndexedPropertyDescriptor and Same type + IndexedPropertyDescriptor subDesc = (IndexedPropertyDescriptor)value; + if ((subGet == null) && (superGet != null)) { + subDesc.setReadMethod(superGet); + } + if ((subSet == null) && (superSet != null)) { + subDesc.setWriteMethod(superSet); + } + IndexedPropertyDescriptor superIndexedDesc = (IndexedPropertyDescriptor)superDesc; + + if ((subDesc.getIndexedReadMethod() == null) && (superIndexedDesc.getIndexedReadMethod() != null)) { + subDesc.setIndexedReadMethod(superIndexedDesc.getIndexedReadMethod()); + } + + if ((subDesc.getIndexedWriteMethod() == null) && (superIndexedDesc.getIndexedWriteMethod() != null)) { + subDesc.setIndexedWriteMethod(superIndexedDesc.getIndexedWriteMethod()); + } + + subMap.put(propertyName, subDesc); + } // Different indexed type, do nothing + } + mergeAttributes((PropertyDescriptor)value, superDesc); + } + + PropertyDescriptor[] theDescs = new PropertyDescriptor[subMap.size()]; + subMap.values().toArray(theDescs); + + if (defaultPropertyName != null && !explicitProperties) { + for (int i = 0; i < theDescs.length; i++) { + if (defaultPropertyName.equals(theDescs[i].getName())) { + defaultPropertyIndex = i; + break; + } + } + } + return theDescs; + } + + private String capitalize (String name) { + if (name == null) { + return null; + } + // The rule for decapitalize is that: + // If the first letter of the string is Upper Case, make it lower case + // UNLESS the second letter of the string is also Upper Case, in which case no + // changes are made. + if (name.length() == 0 || (name.length() > 1 && Character.isUpperCase(name.charAt(1)))) { + return name; + } + + char[] chars = name.toCharArray(); + chars[0] = Character.toUpperCase(chars[0]); + return new String(chars); + } + + private static void mergeAttributes (PropertyDescriptor subDesc, PropertyDescriptor superDesc) { + // FIXME: this is just temp workaround, need more elegant solution to + // handle this + subDesc.hidden |= superDesc.hidden; + subDesc.expert |= superDesc.expert; + subDesc.preferred |= superDesc.preferred; + subDesc.bound |= superDesc.bound; + subDesc.constrained |= superDesc.constrained; + subDesc.name = superDesc.name; + if (subDesc.shortDescription == null && superDesc.shortDescription != null) { + subDesc.shortDescription = superDesc.shortDescription; + } + if (subDesc.displayName == null && superDesc.displayName != null) { + subDesc.displayName = superDesc.displayName; + } + } + + /* + * merge the MethodDescriptor + */ + private MethodDescriptor[] mergeMethods (MethodDescriptor[] superDescs) { + HashMap subMap = internalAsMap(methods); + + for (MethodDescriptor superMethod : superDescs) { + String methodName = getQualifiedName(superMethod.getMethod()); + MethodDescriptor method = subMap.get(methodName); + if (method == null) { + subMap.put(methodName, superMethod); + } else { + method.merge(superMethod); + } + } + MethodDescriptor[] theMethods = new MethodDescriptor[subMap.size()]; + subMap.values().toArray(theMethods); + return theMethods; + } + + private EventSetDescriptor[] mergeEvents (EventSetDescriptor[] otherEvents, int otherDefaultIndex) { + HashMap subMap = internalAsMap(events); + String defaultEventName = null; + if (defaultEventIndex >= 0 && defaultEventIndex < events.length) { + defaultEventName = events[defaultEventIndex].getName(); + } else if (otherDefaultIndex >= 0 && otherDefaultIndex < otherEvents.length) { + defaultEventName = otherEvents[otherDefaultIndex].getName(); + } + + for (EventSetDescriptor event : otherEvents) { + String eventName = event.getName(); + EventSetDescriptor subEvent = subMap.get(eventName); + if (subEvent == null) { + subMap.put(eventName, event); + } else { + subEvent.merge(event); + } + } + + EventSetDescriptor[] theEvents = new EventSetDescriptor[subMap.size()]; + subMap.values().toArray(theEvents); + + if (defaultEventName != null && !explicitEvents) { + for (int i = 0; i < theEvents.length; i++) { + if (defaultEventName.equals(theEvents[i].getName())) { + defaultEventIndex = i; + break; + } + } + } + return theEvents; + } + + private static HashMap internalAsMap (PropertyDescriptor[] propertyDescs) { + HashMap map = new HashMap(); + for (int i = 0; i < propertyDescs.length; i++) { + map.put(propertyDescs[i].getName(), propertyDescs[i]); + } + return map; + } + + private static HashMap internalAsMap (MethodDescriptor[] theDescs) { + HashMap map = new HashMap(); + for (int i = 0; i < theDescs.length; i++) { + String qualifiedName = getQualifiedName(theDescs[i].getMethod()); + map.put(qualifiedName, theDescs[i]); + } + return map; + } + + private static HashMap internalAsMap (EventSetDescriptor[] theDescs) { + HashMap map = new HashMap(); + for (int i = 0; i < theDescs.length; i++) { + map.put(theDescs[i].getName(), theDescs[i]); + } + return map; + } + + private static String getQualifiedName (Method method) { + String qualifiedName = method.getName(); + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes != null) { + for (int i = 0; i < paramTypes.length; i++) { + qualifiedName += "_" + paramTypes[i].getName(); //$NON-NLS-1$ + } + } + return qualifiedName; + } + + /** Introspects the supplied class and returns a list of the public methods of the class + * + * @return An array of MethodDescriptors with the public methods. null if there are no public methods */ + private MethodDescriptor[] introspectMethods () { + return introspectMethods(false, beanClass); + } + + private MethodDescriptor[] introspectMethods (boolean includeSuper) { + return introspectMethods(includeSuper, beanClass); + } + + private MethodDescriptor[] introspectMethods (boolean includeSuper, Class introspectorClass) { + + // Get the list of methods belonging to this class + Method[] basicMethods = includeSuper ? introspectorClass.getMethods() : introspectorClass.getDeclaredMethods(); + + if (basicMethods == null || basicMethods.length == 0) return null; + + ArrayList methodList = new ArrayList(basicMethods.length); + + // Loop over the methods found, looking for public non-static methods + for (int i = 0; i < basicMethods.length; i++) { + int modifiers = basicMethods[i].getModifiers(); + if (Modifier.isPublic(modifiers)) { + // Allocate a MethodDescriptor for this method + MethodDescriptor theDescriptor = new MethodDescriptor(basicMethods[i]); + methodList.add(theDescriptor); + } + } + + // Get the list of public methods into the returned array + int methodCount = methodList.size(); + MethodDescriptor[] theMethods = null; + if (methodCount > 0) { + theMethods = new MethodDescriptor[methodCount]; + theMethods = methodList.toArray(theMethods); + } + + return theMethods; + } + + /** Introspects the supplied class and returns a list of the Properties of the class + * + * @param stopClass - the to introspecting at + * @return The list of Properties as an array of PropertyDescriptors + * @throws IntrospectionException */ + @SuppressWarnings("unchecked") + private PropertyDescriptor[] introspectProperties (Class stopClass) throws IntrospectionException { + + // Get descriptors for the public methods + MethodDescriptor[] methodDescriptors = introspectMethods(); + + if (methodDescriptors == null) { + return null; + } + + ArrayList methodList = new ArrayList(); + // Loop over the methods found, looking for public non-static methods + for (int index = 0; index < methodDescriptors.length; index++) { + int modifiers = methodDescriptors[index].getMethod().getModifiers(); + if (!Modifier.isStatic(modifiers)) { + methodList.add(methodDescriptors[index]); + } + } + + // Get the list of public non-static methods into an array + int methodCount = methodList.size(); + MethodDescriptor[] theMethods = null; + if (methodCount > 0) { + theMethods = new MethodDescriptor[methodCount]; + theMethods = methodList.toArray(theMethods); + } + + if (theMethods == null) { + return null; + } + + HashMap propertyTable = new HashMap(theMethods.length); + + // Search for methods that either get or set a Property + for (int i = 0; i < theMethods.length; i++) { + introspectGet(theMethods[i].getMethod(), propertyTable); + introspectSet(theMethods[i].getMethod(), propertyTable); + } + + // fix possible getter & setter collisions + fixGetSet(propertyTable); + + // If there are listener methods, should be bound. + MethodDescriptor[] allMethods = introspectMethods(true); + if (stopClass != null) { + MethodDescriptor[] excludeMethods = introspectMethods(true, stopClass); + if (excludeMethods != null) { + ArrayList tempMethods = new ArrayList(); + for (MethodDescriptor method : allMethods) { + if (!isInSuper(method, excludeMethods)) { + tempMethods.add(method); + } + } + allMethods = tempMethods.toArray(new MethodDescriptor[0]); + } + } + for (int i = 0; i < allMethods.length; i++) { + introspectPropertyListener(allMethods[i].getMethod()); + } + // Put the properties found into the PropertyDescriptor array + ArrayList propertyList = new ArrayList(); + + for (Map.Entry entry : propertyTable.entrySet()) { + String propertyName = entry.getKey(); + HashMap table = entry.getValue(); + if (table == null) { + continue; + } + String normalTag = (String)table.get(STR_NORMAL); + String indexedTag = (String)table.get(STR_INDEXED); + + if ((normalTag == null) && (indexedTag == null)) { + continue; + } + + Method get = (Method)table.get(STR_NORMAL + PREFIX_GET); + Method set = (Method)table.get(STR_NORMAL + PREFIX_SET); + Method indexedGet = (Method)table.get(STR_INDEXED + PREFIX_GET); + Method indexedSet = (Method)table.get(STR_INDEXED + PREFIX_SET); + + PropertyDescriptor propertyDesc = null; + if (indexedTag == null) { + propertyDesc = new PropertyDescriptor(propertyName, get, set); + } else { + try { + propertyDesc = new IndexedPropertyDescriptor(propertyName, get, set, indexedGet, indexedSet); + } catch (IntrospectionException e) { + // If the getter and the indexGetter is not compatible, try + // getter/setter is null; + propertyDesc = new IndexedPropertyDescriptor(propertyName, null, null, indexedGet, indexedSet); + } + } + // RI set propretyDescriptor as bound. FIXME + // propertyDesc.setBound(true); + if (canAddPropertyChangeListener && canRemovePropertyChangeListener) { + propertyDesc.setBound(true); + } else { + propertyDesc.setBound(false); + } + if (table.get(STR_IS_CONSTRAINED) == Boolean.TRUE) { //$NON-NLS-1$ + propertyDesc.setConstrained(true); + } + propertyList.add(propertyDesc); + } + + PropertyDescriptor[] theProperties = new PropertyDescriptor[propertyList.size()]; + propertyList.toArray(theProperties); + return theProperties; + } + + private boolean isInSuper (MethodDescriptor method, MethodDescriptor[] excludeMethods) { + for (MethodDescriptor m : excludeMethods) { + if (method.getMethod().equals(m.getMethod())) { + return true; + } + } + return false; + } + + @SuppressWarnings("nls") + private void introspectPropertyListener (Method theMethod) { + String methodName = theMethod.getName(); + Class[] param = theMethod.getParameterTypes(); + if (param.length != 1) { + return; + } + if (methodName.equals("addPropertyChangeListener") && param[0].equals(PropertyChangeListener.class)) + canAddPropertyChangeListener = true; + if (methodName.equals("removePropertyChangeListener") && param[0].equals(PropertyChangeListener.class)) + canRemovePropertyChangeListener = true; + } + + @SuppressWarnings("unchecked") + private static void introspectGet (Method theMethod, HashMap propertyTable) { + + String methodName = theMethod.getName(); + int prefixLength = 0; + String propertyName; + Class propertyType; + Class[] paramTypes; + HashMap table; + ArrayList getters; + + if (methodName == null) { + return; + } + + if (methodName.startsWith(PREFIX_GET)) { + prefixLength = PREFIX_GET.length(); + } + + if (methodName.startsWith(PREFIX_IS)) { + prefixLength = PREFIX_IS.length(); + } + + if (prefixLength == 0) { + return; + } + + propertyName = decapitalize(methodName.substring(prefixLength)); + + // validate property name + if (!isValidProperty(propertyName)) { + return; + } + + // validate return type + propertyType = theMethod.getReturnType(); + + if (propertyType == null || propertyType == void.class) { + return; + } + + // isXXX return boolean + if (prefixLength == 2) { + if (!(propertyType == boolean.class)) { + return; + } + } + + // validate parameter types + paramTypes = theMethod.getParameterTypes(); + if (paramTypes.length > 1 || (paramTypes.length == 1 && paramTypes[0] != int.class)) { + return; + } + + table = propertyTable.get(propertyName); + if (table == null) { + table = new HashMap(); + propertyTable.put(propertyName, table); + } + + getters = (ArrayList)table.get(STR_GETTERS); + if (getters == null) { + getters = new ArrayList(); + table.put(STR_GETTERS, getters); + } + + // add current method as a valid getter + getters.add(theMethod); + } + + @SuppressWarnings("unchecked") + private static void introspectSet (Method theMethod, HashMap propertyTable) { + + String methodName = theMethod.getName(); + if (methodName == null) { + return; + } + String propertyName; + Class returnType; + Class[] paramTypes; + + // setter method should never return type other than void + returnType = theMethod.getReturnType(); + if (returnType != void.class) { + return; + } + + if (methodName == null || !methodName.startsWith(PREFIX_SET)) { + return; + } + + propertyName = decapitalize(methodName.substring(PREFIX_SET.length())); + + // validate property name + if (!isValidProperty(propertyName)) { + return; + } + + // It seems we do not need to validate return type + + // validate param types + paramTypes = theMethod.getParameterTypes(); + + if (paramTypes.length == 0 || paramTypes.length > 2 || (paramTypes.length == 2 && paramTypes[0] != int.class)) { + return; + } + + HashMap table = propertyTable.get(propertyName); + if (table == null) { + table = new HashMap(); + propertyTable.put(propertyName, table); + } + + ArrayList setters = (ArrayList)table.get(STR_SETTERS); + if (setters == null) { + setters = new ArrayList(); + table.put(STR_SETTERS, setters); + } + + // handle constrained + Class[] exceptions = theMethod.getExceptionTypes(); + for (Class e : exceptions) { + if (e.equals(PropertyVetoException.class)) { + table.put(STR_IS_CONSTRAINED, Boolean.TRUE); //$NON-NLS-1$ + } + } + + // add new setter + setters.add(theMethod); + } + + /** Checks and fixs all cases when several incompatible checkers / getters were specified for single property. + * + * @param propertyTable + * @throws IntrospectionException */ + private void fixGetSet (HashMap propertyTable) throws IntrospectionException { + + if (propertyTable == null) { + return; + } + + for (Map.Entry entry : propertyTable.entrySet()) { + HashMap table = entry.getValue(); + ArrayList getters = (ArrayList)table.get(STR_GETTERS); + ArrayList setters = (ArrayList)table.get(STR_SETTERS); + + Method normalGetter = null; + Method indexedGetter = null; + Method normalSetter = null; + Method indexedSetter = null; + + Class normalPropType = null; + Class indexedPropType = null; + + if (getters == null) { + getters = new ArrayList(); + } + + if (setters == null) { + setters = new ArrayList(); + } + + // retrieve getters + Class[] paramTypes = null; + String methodName = null; + for (Method getter : getters) { + paramTypes = getter.getParameterTypes(); + methodName = getter.getName(); + // checks if it's a normal getter + if (paramTypes == null || paramTypes.length == 0) { + // normal getter found + if (normalGetter == null || methodName.startsWith(PREFIX_IS)) { + normalGetter = getter; + } + } + + // checks if it's an indexed getter + if (paramTypes != null && paramTypes.length == 1 && paramTypes[0] == int.class) { + // indexed getter found + if (indexedGetter == null || methodName.startsWith(PREFIX_GET) + || (methodName.startsWith(PREFIX_IS) && !indexedGetter.getName().startsWith(PREFIX_GET))) { + indexedGetter = getter; + } + } + } + + // retrieve normal setter + if (normalGetter != null) { + // Now we will try to look for normal setter of the same type. + Class propertyType = normalGetter.getReturnType(); + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 1 && propertyType.equals(setter.getParameterTypes()[0])) { + normalSetter = setter; + break; + } + } + } else { + // Normal getter wasn't defined. Let's look for the last + // defined setter + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 1) { + normalSetter = setter; + } + } + } + + // retrieve indexed setter + if (indexedGetter != null) { + // Now we will try to look for indexed setter of the same type. + Class propertyType = indexedGetter.getReturnType(); + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 2 && setter.getParameterTypes()[0] == int.class + && propertyType.equals(setter.getParameterTypes()[1])) { + indexedSetter = setter; + break; + } + } + } else { + // Indexed getter wasn't defined. Let's look for the last + // defined indexed setter + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 2 && setter.getParameterTypes()[0] == int.class) { + indexedSetter = setter; + } + } + } + + // determine property type + if (normalGetter != null) { + normalPropType = normalGetter.getReturnType(); + } else if (normalSetter != null) { + normalPropType = normalSetter.getParameterTypes()[0]; + } + + // determine indexed getter/setter type + if (indexedGetter != null) { + indexedPropType = indexedGetter.getReturnType(); + } else if (indexedSetter != null) { + indexedPropType = indexedSetter.getParameterTypes()[1]; + } + + // convert array-typed normal getters to indexed getters + if (normalGetter != null && normalGetter.getReturnType().isArray()) { + + } + + // RULES + // These rules were created after performing extensive black-box + // testing of RI + + // RULE1 + // Both normal getter and setter of the same type were defined; + // no indexed getter/setter *PAIR* of the other type defined + if (normalGetter != null && normalSetter != null && (indexedGetter == null || indexedSetter == null)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + continue; + } + + // RULE2 + // normal getter and/or setter was defined; no indexed + // getters & setters defined + if ((normalGetter != null || normalSetter != null) && indexedGetter == null && indexedSetter == null) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + continue; + } + + // RULE3 + // mix of normal / indexed getters and setters are defined. Types + // are compatible + if ((normalGetter != null || normalSetter != null) && (indexedGetter != null || indexedSetter != null)) { + // (1)!A!B!C!D + if (normalGetter != null && normalSetter != null && indexedGetter != null && indexedSetter != null) { + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + } else { + if (normalPropType != boolean.class && normalGetter.getName().startsWith(PREFIX_IS)) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + } else { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + } + } + continue; + } + + // (2)!AB!C!D + if (normalGetter != null && normalSetter == null && indexedGetter != null && indexedSetter != null) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + + table.put(STR_INDEXED, STR_VALID); + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + } + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // (3)A!B!C!D + if (normalGetter == null && normalSetter != null && indexedGetter != null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + } + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // (4)!AB!CD + if (normalGetter != null && normalSetter == null && indexedGetter != null && indexedSetter == null) { + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + } else { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + } + continue; + } + + // (5)A!B!CD + if (normalGetter == null && normalSetter != null && indexedGetter != null && indexedSetter == null) { + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + } else { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + } + continue; + } + + // (6)!ABC!D + if (normalGetter != null && normalSetter == null && indexedGetter == null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // (7)A!BC!D + if (normalGetter == null && normalSetter != null && indexedGetter == null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + } + + // RULE4 + // no normal normal getter / setter. + // Only indexed getter and/or setter is given + // no normal setters / getters defined + if (normalSetter == null && normalGetter == null && (indexedGetter != null || indexedSetter != null)) { + if (indexedGetter != null && indexedGetter.getName().startsWith(PREFIX_IS)) { + if (indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + } + continue; + } + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // RULE5 + // Both indexed getter and setter methods are defined + // no normal getter/setter *PAIR* of the other type defined + if ((normalSetter != null || normalGetter != null) && indexedGetter != null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // default rule - invalid property + table.put(STR_NORMAL, STR_INVALID); + table.put(STR_INDEXED, STR_INVALID); + } + + } + + /** Introspects the supplied Bean class and returns a list of the Events of the class + * + * @return the events + * @throws IntrospectionException */ + @SuppressWarnings("unchecked") + private EventSetDescriptor[] introspectEvents () throws IntrospectionException { + // Get descriptors for the public methods + // FIXME: performance + MethodDescriptor[] theMethods = introspectMethods(); + + if (theMethods == null) return null; + + HashMap eventTable = new HashMap(theMethods.length); + + // Search for methods that add an Event Listener + for (int i = 0; i < theMethods.length; i++) { + introspectListenerMethods(PREFIX_ADD, theMethods[i].getMethod(), eventTable); + introspectListenerMethods(PREFIX_REMOVE, theMethods[i].getMethod(), eventTable); + introspectGetListenerMethods(theMethods[i].getMethod(), eventTable); + } + + ArrayList eventList = new ArrayList(); + for (Map.Entry entry : eventTable.entrySet()) { + HashMap table = entry.getValue(); + Method add = (Method)table.get(PREFIX_ADD); + Method remove = (Method)table.get(PREFIX_REMOVE); + + if ((add == null) || (remove == null)) { + continue; + } + + Method get = (Method)table.get(PREFIX_GET); + Class listenerType = (Class)table.get("listenerType"); //$NON-NLS-1$ + Method[] listenerMethods = (Method[])table.get("listenerMethods"); //$NON-NLS-1$ + EventSetDescriptor eventSetDescriptor = new EventSetDescriptor(decapitalize(entry.getKey()), listenerType, + listenerMethods, add, remove, get); + + eventSetDescriptor.setUnicast(table.get("isUnicast") != null); //$NON-NLS-1$ + eventList.add(eventSetDescriptor); + } + + EventSetDescriptor[] theEvents = new EventSetDescriptor[eventList.size()]; + eventList.toArray(theEvents); + + return theEvents; + } + + /* + * find the add, remove listener method + */ + @SuppressWarnings("unchecked") + private static void introspectListenerMethods (String type, Method theMethod, HashMap methodsTable) { + String methodName = theMethod.getName(); + if (methodName == null) { + return; + } + + if (!((methodName.startsWith(type)) && (methodName.endsWith(SUFFIX_LISTEN)))) { + return; + } + + String listenerName = methodName.substring(type.length()); + String eventName = listenerName.substring(0, listenerName.lastIndexOf(SUFFIX_LISTEN)); + if ((eventName == null) || (eventName.length() == 0)) { + return; + } + + Class[] paramTypes = theMethod.getParameterTypes(); + if ((paramTypes == null) || (paramTypes.length != 1)) { + return; + } + + Class listenerType = paramTypes[0]; + + if (!EventListener.class.isAssignableFrom(listenerType)) { + return; + } + + if (!listenerType.getName().endsWith(listenerName)) { + return; + } + + HashMap table = methodsTable.get(eventName); + if (table == null) { + table = new HashMap(); + } + // put listener type + if (table.get("listenerType") == null) { //$NON-NLS-1$ + table.put("listenerType", listenerType); //$NON-NLS-1$ + table.put("listenerMethods", //$NON-NLS-1$ + introspectListenerMethods(listenerType)); + } + // put add / remove + table.put(type, theMethod); + + // determine isUnicast() + if (type.equals(PREFIX_ADD)) { + Class[] exceptionTypes = theMethod.getExceptionTypes(); + if (exceptionTypes != null) { + for (int i = 0; i < exceptionTypes.length; i++) { + if (exceptionTypes[i].getName().equals(TooManyListenersException.class.getName())) { + table.put("isUnicast", "true"); //$NON-NLS-1$//$NON-NLS-2$ + break; + } + } + } + } + + methodsTable.put(eventName, table); + } + + private static Method[] introspectListenerMethods (Class listenerType) { + Method[] methods = listenerType.getDeclaredMethods(); + ArrayList list = new ArrayList(); + for (int i = 0; i < methods.length; i++) { + Class[] paramTypes = methods[i].getParameterTypes(); + if (paramTypes.length != 1) { + continue; + } + + if (EventObject.class.isAssignableFrom(paramTypes[0])) { + list.add(methods[i]); + } + } + Method[] matchedMethods = new Method[list.size()]; + list.toArray(matchedMethods); + return matchedMethods; + } + + @SuppressWarnings("unchecked") + private static void introspectGetListenerMethods (Method theMethod, HashMap methodsTable) { + String type = PREFIX_GET; + + String methodName = theMethod.getName(); + if (methodName == null) { + return; + } + + if (!((methodName.startsWith(type)) && (methodName.endsWith(SUFFIX_LISTEN + "s")))) { //$NON-NLS-1$ + return; + } + + String listenerName = methodName.substring(type.length(), methodName.length() - 1); + String eventName = listenerName.substring(0, listenerName.lastIndexOf(SUFFIX_LISTEN)); + if ((eventName == null) || (eventName.length() == 0)) { + return; + } + + Class[] paramTypes = theMethod.getParameterTypes(); + if ((paramTypes == null) || (paramTypes.length != 0)) { + return; + } + + Class returnType = theMethod.getReturnType(); + if ((returnType.getComponentType() == null) || (!returnType.getComponentType().getName().endsWith(listenerName))) { + return; + } + + HashMap table = methodsTable.get(eventName); + if (table == null) { + table = new HashMap(); + } + // put add / remove + table.put(type, theMethod); + methodsTable.put(eventName, table); + } + + private static boolean isValidProperty (String propertyName) { + return (propertyName != null) && (propertyName.length() != 0); + } + + private static class PropertyComparator implements Comparator { + public int compare (PropertyDescriptor object1, PropertyDescriptor object2) { + return object1.getName().compareTo(object2.getName()); + } + + } + + // TODO + void init () { + if (this.events == null) { + events = new EventSetDescriptor[0]; + } + if (this.properties == null) { + this.properties = new PropertyDescriptor[0]; + } + + if (properties != null) { + String defaultPropertyName = (defaultPropertyIndex != -1 ? properties[defaultPropertyIndex].getName() : null); + Arrays.sort(properties, comparator); + if (null != defaultPropertyName) { + for (int i = 0; i < properties.length; i++) { + if (defaultPropertyName.equals(properties[i].getName())) { + defaultPropertyIndex = i; + break; + } + } + } + } + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/Statement.java b/extensions/beans/src/com/badlogic/gdx/beans/Statement.java index 8815b3f0f5a..bb59f05f6f5 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/Statement.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/Statement.java @@ -17,8 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Statement; - import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -38,575 +36,519 @@ public class Statement { - private Object target; - - private String methodName; - - private Object[] arguments; - - // cache used methods of specified target class to accelerate method search - private static WeakHashMap, Method[]> classMethodsCache = new WeakHashMap, Method[]>(); - - public Statement(Object target, String methodName, Object[] arguments) { - this.target = target; - this.methodName = methodName; - this.arguments = arguments == null ? BeansUtils.EMPTY_OBJECT_ARRAY - : arguments; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (target == null) { - sb.append(BeansUtils.NULL); - } else { - Class clazz = target.getClass(); - sb.append(clazz == String.class ? BeansUtils.QUOTE : BeansUtils - .idOfClass(clazz)); - } - sb.append('.' + methodName + '('); - if (arguments != null) { - Class clazz; - for (int index = 0; index < arguments.length; index++) { - if (index > 0) { - sb.append(", "); //$NON-NLS-1$ - } - if (arguments[index] == null) { - sb.append(BeansUtils.NULL); - } else { - clazz = arguments[index].getClass(); - sb.append(clazz == String.class ? '"' + (String) arguments[index] + '"' - : BeansUtils.idOfClass(clazz)); - } - } - } - sb.append(')'); - sb.append(';'); - return sb.toString(); - } - - public String getMethodName() { - return methodName; - } - - public Object[] getArguments() { - return arguments; - } - - public Object getTarget() { - return target; - } - - public void execute() throws Exception { - invokeMethod(); - } - - Object invokeMethod() throws Exception { - Object result = null; - try { - Object target = getTarget(); - String methodName = getMethodName(); - Object[] arguments = getArguments(); - Class targetClass = target.getClass(); - if (targetClass.isArray()) { - Method method = findArrayMethod(methodName, arguments); - Object[] copy = new Object[arguments.length + 1]; - copy[0] = target; - System.arraycopy(arguments, 0, copy, 1, arguments.length); - result = method.invoke(null, copy); - } else if (BeansUtils.NEWINSTANCE.equals(methodName) - && target == Array.class) { - result = Array.newInstance((Class) arguments[0], - ((Integer) arguments[1]).intValue()); - } else if (BeansUtils.NEW.equals(methodName) - || BeansUtils.NEWINSTANCE.equals(methodName)) { - if (target instanceof Class) { - Constructor constructor = findConstructor( - (Class) target, arguments); - result = constructor.newInstance(arguments); - } else { - if (BeansUtils.NEW.equals(methodName)) { - throw new NoSuchMethodException(this.toString()); - } - // target class declares a public named "newInstance" method - Method method = findMethod(targetClass, methodName, - arguments, false); - result = method.invoke(target, arguments); - } - } else if (methodName.equals(BeansUtils.NEWARRAY)) { - // create a new array instance without length attribute - Class clazz = (Class) target, argClass; - - // check the element types of array - for (int index = 0; index < arguments.length; index++) { - argClass = arguments[index] == null ? null - : arguments[index].getClass(); - if (argClass != null && !clazz.isAssignableFrom(argClass) - && !BeansUtils.isPrimitiveWrapper(argClass, clazz)) { - throw new IllegalArgumentException( - Messages.getString("beans.63")); //$NON-NLS-1$ - } - } - result = Array.newInstance(clazz, arguments.length); - if (clazz.isPrimitive()) { - // Copy element according to primitive types - arrayCopy(clazz, arguments, result, arguments.length); - } else { - // Copy element of Objects - System.arraycopy(arguments, 0, result, 0, arguments.length); - } - return result; - } else if (target instanceof Class) { - Method method = null; - try { - /* - * Try to look for a static method of class described by the - * given Class object at first process only if the class - * differs from Class itself - */ - if (target != Class.class) { - method = findMethod((Class) target, methodName, - arguments, true); - result = method.invoke(null, arguments); - } - } catch (NoSuchMethodException e) { - // expected - } - if (method == null) { - // static method was not found - // try to invoke method of Class object - if (BeansUtils.FORNAME.equals(methodName) - && arguments.length == 1 - && arguments[0] instanceof String) { - // special handling of Class.forName(String) - try { - result = Class.forName((String) arguments[0]); - } catch (ClassNotFoundException e2) { - result = Class.forName((String) arguments[0], true, - Thread.currentThread() - .getContextClassLoader()); - } - } else { - method = findMethod(targetClass, methodName, arguments, - false); - result = method.invoke(target, arguments); - } - } - } else if (target instanceof Iterator) { - final Iterator iterator = (Iterator) target; - final Method method = findMethod(targetClass, methodName, - arguments, false); - if (iterator.hasNext()) { - result = new PrivilegedAction() { - public Object run() { - try { - method.setAccessible(true); - return (method.invoke(iterator, new Object[0])); - } catch (Exception e) { - // ignore - } - return null; - } - - }.run(); - } - } else { - Method method = findMethod(targetClass, methodName, arguments, - false); - method.setAccessible(true); - result = method.invoke(target, arguments); - } - } catch (InvocationTargetException ite) { - Throwable t = ite.getCause(); - throw (t != null) && (t instanceof Exception) ? (Exception) t : ite; - } - return result; - } - - private void arrayCopy(Class type, Object[] src, Object dest, int length) { - if (type == boolean.class) { - boolean[] destination = (boolean[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Boolean) src[index]).booleanValue(); - } - } else if (type == short.class) { - short[] destination = (short[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Short) src[index]).shortValue(); - } - } else if (type == byte.class) { - byte[] destination = (byte[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Byte) src[index]).byteValue(); - } - } else if (type == char.class) { - char[] destination = (char[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Character) src[index]).charValue(); - } - } else if (type == int.class) { - int[] destination = (int[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Integer) src[index]).intValue(); - } - } else if (type == long.class) { - long[] destination = (long[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Long) src[index]).longValue(); - } - } else if (type == float.class) { - float[] destination = (float[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Float) src[index]).floatValue(); - } - } else if (type == double.class) { - double[] destination = (double[]) dest; - for (int index = 0; index < length; index++) { - destination[index] = ((Double) src[index]).doubleValue(); - } - } - } - - private Method findArrayMethod(String methodName, Object[] args) - throws NoSuchMethodException { - // the code below reproduces exact RI exception throwing behavior - boolean isGet = BeansUtils.GET.equals(methodName); //$NON-NLS-1$ - boolean isSet = BeansUtils.SET.equals(methodName); //$NON-NLS-1$ - if (!isGet && !isSet) { - throw new NoSuchMethodException(Messages.getString("beans.3C")); //$NON-NLS-1$ - } else if (args.length > 0 && args[0].getClass() != Integer.class) { - throw new ClassCastException(Messages.getString("beans.3D")); //$NON-NLS-1$ - } else if (isGet && args.length != 1) { - throw new ArrayIndexOutOfBoundsException( - Messages.getString("beans.3E")); //$NON-NLS-1$ - } else if (isSet && args.length != 2) { - throw new ArrayIndexOutOfBoundsException( - Messages.getString("beans.3F")); //$NON-NLS-1$ - } - - Class[] paraTypes = isGet ? new Class[] { Object.class, int.class } - : new Class[] { Object.class, int.class, Object.class }; - return Array.class.getMethod(methodName, paraTypes); - } - - private Constructor findConstructor(Class clazz, Object[] args) - throws NoSuchMethodException { - Class[] argTypes = getTypes(args), paraTypes, resultParaTypes; - Constructor result = null; - boolean isAssignable; - for (Constructor constructor : clazz.getConstructors()) { - paraTypes = constructor.getParameterTypes(); - if (match(argTypes, paraTypes)) { - if (result == null) { - // first time, set constructor - result = constructor; - continue; - } - // find out more suitable constructor - resultParaTypes = result.getParameterTypes(); - isAssignable = true; - for (int index = 0; index < paraTypes.length; index++) { - if (argTypes[index] != null - && !(isAssignable &= resultParaTypes[index] - .isAssignableFrom(paraTypes[index]))) { - break; - } - if (argTypes[index] == null - && !(isAssignable &= paraTypes[index] - .isAssignableFrom(resultParaTypes[index]))) { - break; - } - } - if (isAssignable) { - result = constructor; - } - } - } - if (result == null) { - throw new NoSuchMethodException(Messages.getString( - "beans.40", clazz.getName())); //$NON-NLS-1$ - } - return result; - } - - /** - * Searches for best matching method for given name and argument types. - */ - static Method findMethod(Class clazz, String methodName, Object[] args, - boolean isStatic) throws NoSuchMethodException { - Class[] argTypes = getTypes(args); - - Method[] methods = null; - if (classMethodsCache.containsKey(clazz)) { - methods = classMethodsCache.get(clazz); - } else { - methods = clazz.getMethods(); - classMethodsCache.put(clazz, methods); - } - - ArrayList fitMethods = new ArrayList(); - for (Method method : methods) { - if (methodName.equals(method.getName())) { - if (!isStatic || Modifier.isStatic(method.getModifiers())) { - if (match(argTypes, method.getParameterTypes())) { - fitMethods.add(method); - } - } - } - } - int fitSize = fitMethods.size(); - if (fitSize == 0) { - throw new NoSuchMethodException(Messages.getString( - "beans.41", methodName)); //$NON-NLS-1$ - } - if (fitSize == 1) { - return fitMethods.get(0); - } - // find the most relevant one - MethodComparator comparator = new MethodComparator(methodName, argTypes); - Method[] fitMethodArray = fitMethods.toArray(new Method[fitSize]); - Method onlyMethod = fitMethodArray[0]; - Class onlyReturnType, fitReturnType; - int difference; - for (int i = 1; i < fitMethodArray.length; i++) { - // if 2 methods have same relevance, check their return type - if ((difference = comparator.compare(onlyMethod, fitMethodArray[i])) == 0) { - // if 2 methods have the same signature, check their return type - onlyReturnType = onlyMethod.getReturnType(); - fitReturnType = fitMethodArray[i].getReturnType(); - if (onlyReturnType == fitReturnType) { - // if 2 methods have the same relevance and return type - throw new NoSuchMethodException(Messages.getString( - "beans.62", methodName)); //$NON-NLS-1$ - } - - if (onlyReturnType.isAssignableFrom(fitReturnType)) { - // if onlyReturnType is super class or interface of - // fitReturnType, set onlyMethod to fitMethodArray[i] - onlyMethod = fitMethodArray[i]; - } - } - if (difference > 0) { - onlyMethod = fitMethodArray[i]; - } - } - return onlyMethod; - } - - private static boolean match(Class[] argTypes, Class[] paraTypes) { - if (paraTypes.length != argTypes.length) { - return false; - } - for (int index = 0; index < paraTypes.length; index++) { - if (argTypes[index] != null - && !paraTypes[index].isAssignableFrom(argTypes[index]) - && !BeansUtils.isPrimitiveWrapper(argTypes[index], - paraTypes[index])) { - return false; - } - } - return true; - } - - static boolean isStaticMethodCall(Statement stmt) { - Object target = stmt.getTarget(); - String methodName = stmt.getMethodName(); - if (!(target instanceof Class)) { - return false; - } - try { - Statement.findMethod((Class) target, methodName, - stmt.getArguments(), true); - return true; - } catch (NoSuchMethodException e) { - return false; - } - } - - /* - * The list of "method signatures" used by persistence delegates to create - * objects. Not necessary reflects to real methods. - */ - private static final String[][] pdConstructorSignatures = { - { "java.lang.Class", "new", "java.lang.Boolean", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.Byte", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.Character", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.Double", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.Float", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.Integer", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.Long", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.Short", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "new", "java.lang.String", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "forName", "java.lang.String", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "newInstance", "java.lang.Class", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - "java.lang.Integer", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - { "java.lang.reflect.Field", "get", "null", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - { "java.lang.Class", "forName", "java.lang.String", "", "", "" } //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - }; - - static boolean isPDConstructor(Statement stmt) { - Object target = stmt.getTarget(); - String methodName = stmt.getMethodName(); - Object[] args = stmt.getArguments(); - String[] sig = new String[pdConstructorSignatures[0].length]; - if (target == null || methodName == null || args == null - || args.length == 0) { - // not a constructor for sure - return false; - } - sig[0] = target.getClass().getName(); - sig[1] = methodName; - for (int i = 2; i < sig.length; i++) { - if (args.length > i - 2) { - sig[i] = args[i - 2] != null ? args[i - 2].getClass().getName() - : "null"; //$NON-NLS-1$ - } else { - sig[i] = ""; //$NON-NLS-1$ - } - } - for (String[] element : pdConstructorSignatures) { - if (Arrays.equals(sig, element)) { - return true; - } - } - return false; - } - - private static Class getPrimitiveWrapper(Class base) { - Class res = null; - if (base == boolean.class) { - res = Boolean.class; - } else if (base == byte.class) { - res = Byte.class; - } else if (base == char.class) { - res = Character.class; - } else if (base == short.class) { - res = Short.class; - } else if (base == int.class) { - res = Integer.class; - } else if (base == long.class) { - res = Long.class; - } else if (base == float.class) { - res = Float.class; - } else if (base == double.class) { - res = Double.class; - } - return res; - } - - private static Class[] getTypes(Object[] arguments) { - Class[] types = new Class[arguments.length]; - for (int index = 0; index < arguments.length; ++index) { - types[index] = (arguments[index] == null) ? null : arguments[index] - .getClass(); - } - return types; - } - - /** - * Comparator to determine which of two methods is "closer" to the reference - * method. - */ - static class MethodComparator implements Comparator { - static int INFINITY = Integer.MAX_VALUE; - - private String referenceMethodName; - - private Class[] referenceMethodArgumentTypes; - - private final Map cache; - - public MethodComparator(String refMethodName, - Class[] refArgumentTypes) { - this.referenceMethodName = refMethodName; - this.referenceMethodArgumentTypes = refArgumentTypes; - cache = new HashMap(); - } - - public int compare(Method m1, Method m2) { - Integer norm1 = cache.get(m1); - Integer norm2 = cache.get(m2); - if (norm1 == null) { - norm1 = Integer.valueOf(getNorm(m1)); - cache.put(m1, norm1); - } - if (norm2 == null) { - norm2 = Integer.valueOf(getNorm(m2)); - cache.put(m2, norm2); - } - return (norm1.intValue() - norm2.intValue()); - } - - /** - * Returns the norm for given method. The norm is the "distance" from - * the reference method to the given method. - * - * @param m - * the method to calculate the norm for - * @return norm of given method - */ - private int getNorm(Method m) { - String methodName = m.getName(); - Class[] argumentTypes = m.getParameterTypes(); - int totalNorm = 0; - if (!referenceMethodName.equals(methodName) - || referenceMethodArgumentTypes.length != argumentTypes.length) { - return INFINITY; - } - for (int i = 0; i < referenceMethodArgumentTypes.length; i++) { - if (referenceMethodArgumentTypes[i] == null) { - // doesn't affect the norm calculation if null - continue; - } - if (referenceMethodArgumentTypes[i].isPrimitive()) { - referenceMethodArgumentTypes[i] = getPrimitiveWrapper(referenceMethodArgumentTypes[i]); - } - if (argumentTypes[i].isPrimitive()) { - argumentTypes[i] = getPrimitiveWrapper(argumentTypes[i]); - } - totalNorm += getDistance(referenceMethodArgumentTypes[i], - argumentTypes[i]); - } - return totalNorm; - } - - /** - * Returns a "hierarchy distance" between two classes. - * - * @param clz1 - * @param clz2 - * should be superclass or superinterface of clz1 - * @return hierarchy distance from clz1 to clz2, Integer.MAX_VALUE if - * clz2 is not assignable from clz1. - */ - private static int getDistance(Class clz1, Class clz2) { - Class superClz; - int superDist = INFINITY; - if (!clz2.isAssignableFrom(clz1)) { - return INFINITY; - } - if (clz1.getName().equals(clz2.getName())) { - return 0; - } - superClz = clz1.getSuperclass(); - if (superClz != null) { - superDist = getDistance(superClz, clz2); - } - if (clz2.isInterface()) { - Class[] interfaces = clz1.getInterfaces(); - int bestDist = INFINITY; - for (Class element : interfaces) { - int curDist = getDistance(element, clz2); - if (curDist < bestDist) { - bestDist = curDist; - } - } - if (superDist < bestDist) { - bestDist = superDist; - } - return (bestDist != INFINITY ? bestDist + 1 : INFINITY); - } - return (superDist != INFINITY ? superDist + 2 : INFINITY); - } - } -} \ No newline at end of file + private Object target; + + private String methodName; + + private Object[] arguments; + + // cache used methods of specified target class to accelerate method search + private static WeakHashMap, Method[]> classMethodsCache = new WeakHashMap, Method[]>(); + + public Statement (Object target, String methodName, Object[] arguments) { + this.target = target; + this.methodName = methodName; + this.arguments = arguments == null ? BeansUtils.EMPTY_OBJECT_ARRAY : arguments; + } + + @Override + public String toString () { + StringBuilder sb = new StringBuilder(); + if (target == null) { + sb.append(BeansUtils.NULL); + } else { + Class clazz = target.getClass(); + sb.append(clazz == String.class ? BeansUtils.QUOTE : BeansUtils.idOfClass(clazz)); + } + sb.append('.' + methodName + '('); + if (arguments != null) { + Class clazz; + for (int index = 0; index < arguments.length; index++) { + if (index > 0) { + sb.append(", "); //$NON-NLS-1$ + } + if (arguments[index] == null) { + sb.append(BeansUtils.NULL); + } else { + clazz = arguments[index].getClass(); + sb.append(clazz == String.class ? '"' + (String)arguments[index] + '"' : BeansUtils.idOfClass(clazz)); + } + } + } + sb.append(')'); + sb.append(';'); + return sb.toString(); + } + + public String getMethodName () { + return methodName; + } + + public Object[] getArguments () { + return arguments; + } + + public Object getTarget () { + return target; + } + + public void execute () throws Exception { + invokeMethod(); + } + + Object invokeMethod () throws Exception { + Object result = null; + try { + Object target = getTarget(); + String methodName = getMethodName(); + Object[] arguments = getArguments(); + Class targetClass = target.getClass(); + if (targetClass.isArray()) { + Method method = findArrayMethod(methodName, arguments); + Object[] copy = new Object[arguments.length + 1]; + copy[0] = target; + System.arraycopy(arguments, 0, copy, 1, arguments.length); + result = method.invoke(null, copy); + } else if (BeansUtils.NEWINSTANCE.equals(methodName) && target == Array.class) { + result = Array.newInstance((Class)arguments[0], ((Integer)arguments[1]).intValue()); + } else if (BeansUtils.NEW.equals(methodName) || BeansUtils.NEWINSTANCE.equals(methodName)) { + if (target instanceof Class) { + Constructor constructor = findConstructor((Class)target, arguments); + result = constructor.newInstance(arguments); + } else { + if (BeansUtils.NEW.equals(methodName)) { + throw new NoSuchMethodException(this.toString()); + } + // target class declares a public named "newInstance" method + Method method = findMethod(targetClass, methodName, arguments, false); + result = method.invoke(target, arguments); + } + } else if (methodName.equals(BeansUtils.NEWARRAY)) { + // create a new array instance without length attribute + Class clazz = (Class)target, argClass; + + // check the element types of array + for (int index = 0; index < arguments.length; index++) { + argClass = arguments[index] == null ? null : arguments[index].getClass(); + if (argClass != null && !clazz.isAssignableFrom(argClass) && !BeansUtils.isPrimitiveWrapper(argClass, clazz)) { + throw new IllegalArgumentException(Messages.getString("beans.63")); //$NON-NLS-1$ + } + } + result = Array.newInstance(clazz, arguments.length); + if (clazz.isPrimitive()) { + // Copy element according to primitive types + arrayCopy(clazz, arguments, result, arguments.length); + } else { + // Copy element of Objects + System.arraycopy(arguments, 0, result, 0, arguments.length); + } + return result; + } else if (target instanceof Class) { + Method method = null; + try { + /* + * Try to look for a static method of class described by the given Class object at first process only if the class + * differs from Class itself + */ + if (target != Class.class) { + method = findMethod((Class)target, methodName, arguments, true); + result = method.invoke(null, arguments); + } + } catch (NoSuchMethodException e) { + // expected + } + if (method == null) { + // static method was not found + // try to invoke method of Class object + if (BeansUtils.FORNAME.equals(methodName) && arguments.length == 1 && arguments[0] instanceof String) { + // special handling of Class.forName(String) + try { + result = Class.forName((String)arguments[0]); + } catch (ClassNotFoundException e2) { + result = Class.forName((String)arguments[0], true, Thread.currentThread().getContextClassLoader()); + } + } else { + method = findMethod(targetClass, methodName, arguments, false); + result = method.invoke(target, arguments); + } + } + } else if (target instanceof Iterator) { + final Iterator iterator = (Iterator)target; + final Method method = findMethod(targetClass, methodName, arguments, false); + if (iterator.hasNext()) { + result = new PrivilegedAction() { + public Object run () { + try { + method.setAccessible(true); + return (method.invoke(iterator, new Object[0])); + } catch (Exception e) { + // ignore + } + return null; + } + + }.run(); + } + } else { + Method method = findMethod(targetClass, methodName, arguments, false); + method.setAccessible(true); + result = method.invoke(target, arguments); + } + } catch (InvocationTargetException ite) { + Throwable t = ite.getCause(); + throw (t != null) && (t instanceof Exception) ? (Exception)t : ite; + } + return result; + } + + private void arrayCopy (Class type, Object[] src, Object dest, int length) { + if (type == boolean.class) { + boolean[] destination = (boolean[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Boolean)src[index]).booleanValue(); + } + } else if (type == short.class) { + short[] destination = (short[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Short)src[index]).shortValue(); + } + } else if (type == byte.class) { + byte[] destination = (byte[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Byte)src[index]).byteValue(); + } + } else if (type == char.class) { + char[] destination = (char[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Character)src[index]).charValue(); + } + } else if (type == int.class) { + int[] destination = (int[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Integer)src[index]).intValue(); + } + } else if (type == long.class) { + long[] destination = (long[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Long)src[index]).longValue(); + } + } else if (type == float.class) { + float[] destination = (float[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Float)src[index]).floatValue(); + } + } else if (type == double.class) { + double[] destination = (double[])dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Double)src[index]).doubleValue(); + } + } + } + + private Method findArrayMethod (String methodName, Object[] args) throws NoSuchMethodException { + // the code below reproduces exact RI exception throwing behavior + boolean isGet = BeansUtils.GET.equals(methodName); //$NON-NLS-1$ + boolean isSet = BeansUtils.SET.equals(methodName); //$NON-NLS-1$ + if (!isGet && !isSet) { + throw new NoSuchMethodException(Messages.getString("beans.3C")); //$NON-NLS-1$ + } else if (args.length > 0 && args[0].getClass() != Integer.class) { + throw new ClassCastException(Messages.getString("beans.3D")); //$NON-NLS-1$ + } else if (isGet && args.length != 1) { + throw new ArrayIndexOutOfBoundsException(Messages.getString("beans.3E")); //$NON-NLS-1$ + } else if (isSet && args.length != 2) { + throw new ArrayIndexOutOfBoundsException(Messages.getString("beans.3F")); //$NON-NLS-1$ + } + + Class[] paraTypes = isGet ? new Class[] {Object.class, int.class} : new Class[] {Object.class, int.class, + Object.class}; + return Array.class.getMethod(methodName, paraTypes); + } + + private Constructor findConstructor (Class clazz, Object[] args) throws NoSuchMethodException { + Class[] argTypes = getTypes(args), paraTypes, resultParaTypes; + Constructor result = null; + boolean isAssignable; + for (Constructor constructor : clazz.getConstructors()) { + paraTypes = constructor.getParameterTypes(); + if (match(argTypes, paraTypes)) { + if (result == null) { + // first time, set constructor + result = constructor; + continue; + } + // find out more suitable constructor + resultParaTypes = result.getParameterTypes(); + isAssignable = true; + for (int index = 0; index < paraTypes.length; index++) { + if (argTypes[index] != null && !(isAssignable &= resultParaTypes[index].isAssignableFrom(paraTypes[index]))) { + break; + } + if (argTypes[index] == null && !(isAssignable &= paraTypes[index].isAssignableFrom(resultParaTypes[index]))) { + break; + } + } + if (isAssignable) { + result = constructor; + } + } + } + if (result == null) { + throw new NoSuchMethodException(Messages.getString("beans.40", clazz.getName())); //$NON-NLS-1$ + } + return result; + } + + /** Searches for best matching method for given name and argument types. */ + static Method findMethod (Class clazz, String methodName, Object[] args, boolean isStatic) throws NoSuchMethodException { + Class[] argTypes = getTypes(args); + + Method[] methods = null; + if (classMethodsCache.containsKey(clazz)) { + methods = classMethodsCache.get(clazz); + } else { + methods = clazz.getMethods(); + classMethodsCache.put(clazz, methods); + } + + ArrayList fitMethods = new ArrayList(); + for (Method method : methods) { + if (methodName.equals(method.getName())) { + if (!isStatic || Modifier.isStatic(method.getModifiers())) { + if (match(argTypes, method.getParameterTypes())) { + fitMethods.add(method); + } + } + } + } + int fitSize = fitMethods.size(); + if (fitSize == 0) { + throw new NoSuchMethodException(Messages.getString("beans.41", methodName)); //$NON-NLS-1$ + } + if (fitSize == 1) { + return fitMethods.get(0); + } + // find the most relevant one + MethodComparator comparator = new MethodComparator(methodName, argTypes); + Method[] fitMethodArray = fitMethods.toArray(new Method[fitSize]); + Method onlyMethod = fitMethodArray[0]; + Class onlyReturnType, fitReturnType; + int difference; + for (int i = 1; i < fitMethodArray.length; i++) { + // if 2 methods have same relevance, check their return type + if ((difference = comparator.compare(onlyMethod, fitMethodArray[i])) == 0) { + // if 2 methods have the same signature, check their return type + onlyReturnType = onlyMethod.getReturnType(); + fitReturnType = fitMethodArray[i].getReturnType(); + if (onlyReturnType == fitReturnType) { + // if 2 methods have the same relevance and return type + throw new NoSuchMethodException(Messages.getString("beans.62", methodName)); //$NON-NLS-1$ + } + + if (onlyReturnType.isAssignableFrom(fitReturnType)) { + // if onlyReturnType is super class or interface of + // fitReturnType, set onlyMethod to fitMethodArray[i] + onlyMethod = fitMethodArray[i]; + } + } + if (difference > 0) { + onlyMethod = fitMethodArray[i]; + } + } + return onlyMethod; + } + + private static boolean match (Class[] argTypes, Class[] paraTypes) { + if (paraTypes.length != argTypes.length) { + return false; + } + for (int index = 0; index < paraTypes.length; index++) { + if (argTypes[index] != null && !paraTypes[index].isAssignableFrom(argTypes[index]) + && !BeansUtils.isPrimitiveWrapper(argTypes[index], paraTypes[index])) { + return false; + } + } + return true; + } + + static boolean isStaticMethodCall (Statement stmt) { + Object target = stmt.getTarget(); + String methodName = stmt.getMethodName(); + if (!(target instanceof Class)) { + return false; + } + try { + Statement.findMethod((Class)target, methodName, stmt.getArguments(), true); + return true; + } catch (NoSuchMethodException e) { + return false; + } + } + + /* + * The list of "method signatures" used by persistence delegates to create objects. Not necessary reflects to real methods. + */ + private static final String[][] pdConstructorSignatures = { {"java.lang.Class", "new", "java.lang.Boolean", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.Byte", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.Character", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.Double", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.Float", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.Integer", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.Long", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.Short", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "new", "java.lang.String", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "forName", "java.lang.String", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "newInstance", "java.lang.Class", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "java.lang.Integer", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + {"java.lang.reflect.Field", "get", "null", "", "", ""}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + {"java.lang.Class", "forName", "java.lang.String", "", "", ""} //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + }; + + static boolean isPDConstructor (Statement stmt) { + Object target = stmt.getTarget(); + String methodName = stmt.getMethodName(); + Object[] args = stmt.getArguments(); + String[] sig = new String[pdConstructorSignatures[0].length]; + if (target == null || methodName == null || args == null || args.length == 0) { + // not a constructor for sure + return false; + } + sig[0] = target.getClass().getName(); + sig[1] = methodName; + for (int i = 2; i < sig.length; i++) { + if (args.length > i - 2) { + sig[i] = args[i - 2] != null ? args[i - 2].getClass().getName() : "null"; //$NON-NLS-1$ + } else { + sig[i] = ""; //$NON-NLS-1$ + } + } + for (String[] element : pdConstructorSignatures) { + if (Arrays.equals(sig, element)) { + return true; + } + } + return false; + } + + private static Class getPrimitiveWrapper (Class base) { + Class res = null; + if (base == boolean.class) { + res = Boolean.class; + } else if (base == byte.class) { + res = Byte.class; + } else if (base == char.class) { + res = Character.class; + } else if (base == short.class) { + res = Short.class; + } else if (base == int.class) { + res = Integer.class; + } else if (base == long.class) { + res = Long.class; + } else if (base == float.class) { + res = Float.class; + } else if (base == double.class) { + res = Double.class; + } + return res; + } + + private static Class[] getTypes (Object[] arguments) { + Class[] types = new Class[arguments.length]; + for (int index = 0; index < arguments.length; ++index) { + types[index] = (arguments[index] == null) ? null : arguments[index].getClass(); + } + return types; + } + + /** Comparator to determine which of two methods is "closer" to the reference method. */ + static class MethodComparator implements Comparator { + static int INFINITY = Integer.MAX_VALUE; + + private String referenceMethodName; + + private Class[] referenceMethodArgumentTypes; + + private final Map cache; + + public MethodComparator (String refMethodName, Class[] refArgumentTypes) { + this.referenceMethodName = refMethodName; + this.referenceMethodArgumentTypes = refArgumentTypes; + cache = new HashMap(); + } + + public int compare (Method m1, Method m2) { + Integer norm1 = cache.get(m1); + Integer norm2 = cache.get(m2); + if (norm1 == null) { + norm1 = Integer.valueOf(getNorm(m1)); + cache.put(m1, norm1); + } + if (norm2 == null) { + norm2 = Integer.valueOf(getNorm(m2)); + cache.put(m2, norm2); + } + return (norm1.intValue() - norm2.intValue()); + } + + /** Returns the norm for given method. The norm is the "distance" from the reference method to the given method. + * + * @param m the method to calculate the norm for + * @return norm of given method */ + private int getNorm (Method m) { + String methodName = m.getName(); + Class[] argumentTypes = m.getParameterTypes(); + int totalNorm = 0; + if (!referenceMethodName.equals(methodName) || referenceMethodArgumentTypes.length != argumentTypes.length) { + return INFINITY; + } + for (int i = 0; i < referenceMethodArgumentTypes.length; i++) { + if (referenceMethodArgumentTypes[i] == null) { + // doesn't affect the norm calculation if null + continue; + } + if (referenceMethodArgumentTypes[i].isPrimitive()) { + referenceMethodArgumentTypes[i] = getPrimitiveWrapper(referenceMethodArgumentTypes[i]); + } + if (argumentTypes[i].isPrimitive()) { + argumentTypes[i] = getPrimitiveWrapper(argumentTypes[i]); + } + totalNorm += getDistance(referenceMethodArgumentTypes[i], argumentTypes[i]); + } + return totalNorm; + } + + /** Returns a "hierarchy distance" between two classes. + * + * @param clz1 + * @param clz2 should be superclass or superinterface of clz1 + * @return hierarchy distance from clz1 to clz2, Integer.MAX_VALUE if clz2 is not assignable from clz1. */ + private static int getDistance (Class clz1, Class clz2) { + Class superClz; + int superDist = INFINITY; + if (!clz2.isAssignableFrom(clz1)) { + return INFINITY; + } + if (clz1.getName().equals(clz2.getName())) { + return 0; + } + superClz = clz1.getSuperclass(); + if (superClz != null) { + superDist = getDistance(superClz, clz2); + } + if (clz2.isInterface()) { + Class[] interfaces = clz1.getInterfaces(); + int bestDist = INFINITY; + for (Class element : interfaces) { + int curDist = getDistance(element, clz2); + if (curDist < bestDist) { + bestDist = curDist; + } + } + if (superDist < bestDist) { + bestDist = superDist; + } + return (bestDist != INFINITY ? bestDist + 1 : INFINITY); + } + return (superDist != INFINITY ? superDist + 2 : INFINITY); + } + } +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/StaticFieldPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/StaticFieldPersistenceDelegate.java index fa566eaf623..0510cafa416 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/StaticFieldPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/StaticFieldPersistenceDelegate.java @@ -17,22 +17,18 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - import java.lang.reflect.Field; import java.util.HashMap; -class StaticFieldPersistenceDelegate extends - PersistenceDelegate { +class StaticFieldPersistenceDelegate extends PersistenceDelegate { - public StaticFieldPersistenceDelegate() { + public StaticFieldPersistenceDelegate () { super(); } - + static HashMap pairs = new HashMap(); - static void init(Class clz) { + + static void init (Class clz) { Field[] field = clz.getFields(); for (int i = 0; i < field.length; i++) { Object value = null; @@ -48,7 +44,7 @@ static void init(Class clz) { } @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { + protected Expression instantiate (Object oldInstance, Encoder enc) { Field field = null; try { field = oldInstance.getClass().getDeclaredField(pairs.get(oldInstance)); @@ -56,7 +52,7 @@ protected Expression instantiate(Object oldInstance, Encoder enc) { enc.getExceptionListener().exceptionThrown(e); } return new Expression(oldInstance, field, "get", //$NON-NLS-1$ - new Object[] { oldInstance.getClass() }); + new Object[] {oldInstance.getClass()}); } -} \ No newline at end of file +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/StringPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/StringPersistenceDelegate.java index 02b3b73f49d..1b1465f91a3 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/StringPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/StringPersistenceDelegate.java @@ -17,33 +17,26 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - class StringPersistenceDelegate extends PersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder out) { - String value = (String) oldInstance; - return new Expression(oldInstance, String.class, - "new", new Object[] { value }); //$NON-NLS-1$ - } + @Override + protected Expression instantiate (Object oldInstance, Encoder out) { + String value = (String)oldInstance; + return new Expression(oldInstance, String.class, "new", new Object[] {value}); //$NON-NLS-1$ + } - @Override - /* - * It's unnecessary to do anything for initialization, because two mutatable - * strings are actually equivalent already. - */ - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder out) { - // do nothing - } + @Override + /* + * It's unnecessary to do anything for initialization, because two mutatable strings are actually equivalent already. + */ + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder out) { + // do nothing + } - @Override - protected boolean mutatesTo(Object oldInstance, Object newInstance) { - if (oldInstance instanceof String && newInstance instanceof String) { - return newInstance.equals(oldInstance); - } - return super.mutatesTo(oldInstance, newInstance); - } + @Override + protected boolean mutatesTo (Object oldInstance, Object newInstance) { + if (oldInstance instanceof String && newInstance instanceof String) { + return newInstance.equals(oldInstance); + } + return super.mutatesTo(oldInstance, newInstance); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/SwingAbstractButtonPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/SwingAbstractButtonPersistenceDelegate.java index 243cfdd6992..b50035354d6 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/SwingAbstractButtonPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/SwingAbstractButtonPersistenceDelegate.java @@ -17,78 +17,59 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import javax.swing.JComponent; -/** - * A special internal PersistenceDelegate for java.awt.JComponent - * class. - * - */ -class SwingAbstractButtonPersistenceDelegate extends DefaultPersistenceDelegate{ - @Override - @SuppressWarnings({ "boxing", "nls" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - // Call the initialization of the super type - super.initialize(type, oldInstance, newInstance, enc); - // Continue only if initializing the "current" type - if (type != oldInstance.getClass()) { - return; - } - - - JComponent container = (JComponent) oldInstance; - int count = container.getComponentCount(); +/** A special internal PersistenceDelegate for java.awt.JComponent class. */ +class SwingAbstractButtonPersistenceDelegate extends DefaultPersistenceDelegate { + @Override + @SuppressWarnings({"boxing", "nls"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + // Call the initialization of the super type + super.initialize(type, oldInstance, newInstance, enc); + // Continue only if initializing the "current" type + if (type != oldInstance.getClass()) { + return; + } + + JComponent container = (JComponent)oldInstance; + int count = container.getComponentCount(); for (int i = 0; i < count; i++) { - Expression getterExp = new Expression(container, - "getComponent", new Object[] { i }); + Expression getterExp = new Expression(container, "getComponent", new Object[] {i}); try { - // Calculate the old value of the property - Object oldVal = getterExp.getValue(); - // Write the getter expression to the encoder - enc.writeExpression(getterExp); - // Get the target value that exists in the new environment - Object targetVal = enc.get(oldVal); - // Get the current property value in the new environment - Object newVal = null; - try { - JComponent newJComponent = (JComponent) newInstance; - newVal = new Expression(newJComponent.getComponent(i), - newJComponent, "getComponent", - new Object[] { i }).getValue(); + // Calculate the old value of the property + Object oldVal = getterExp.getValue(); + // Write the getter expression to the encoder + enc.writeExpression(getterExp); + // Get the target value that exists in the new environment + Object targetVal = enc.get(oldVal); + // Get the current property value in the new environment + Object newVal = null; + try { + JComponent newJComponent = (JComponent)newInstance; + newVal = new Expression(newJComponent.getComponent(i), newJComponent, "getComponent", new Object[] {i}).getValue(); } catch (ArrayIndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } - /* - * Make the target value and current property value equivalent - * in the new environment + /* + * Make the target value and current property value equivalent in the new environment */ - if (null == targetVal) { - if (null != newVal) { - // Set to null - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { null }); - enc.writeStatement(setterStm); - } - } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); - if (!pd.mutatesTo(targetVal, newVal)) { - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { oldVal }); - enc.writeStatement(setterStm); - } - } - } catch (Exception ex) { - enc.getExceptionListener().exceptionThrown(ex); - } + if (null == targetVal) { + if (null != newVal) { + // Set to null + Statement setterStm = new Statement(oldInstance, "add", new Object[] {null}); + enc.writeStatement(setterStm); + } + } else { + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); + if (!pd.mutatesTo(targetVal, newVal)) { + Statement setterStm = new Statement(oldInstance, "add", new Object[] {oldVal}); + enc.writeStatement(setterStm); + } + } + } catch (Exception ex) { + enc.getExceptionListener().exceptionThrown(ex); + } } } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/SwingBoxPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/SwingBoxPersistenceDelegate.java index 1e3e9f5de2a..2019ea3b277 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/SwingBoxPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/SwingBoxPersistenceDelegate.java @@ -17,27 +17,19 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import javax.swing.Box; class SwingBoxPersistenceDelegate extends PersistenceDelegate { @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - return new Expression(oldInstance, oldInstance.getClass(), - "createVerticalBox", null); //$NON-NLS-1$ + protected Expression instantiate (Object oldInstance, Encoder enc) { + return new Expression(oldInstance, oldInstance.getClass(), "createVerticalBox", null); //$NON-NLS-1$ } - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - Box box = (Box) oldInstance; - Expression getterExp = new Expression(box.getAlignmentX(), box, - "getAlignmentX", null); + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + Box box = (Box)oldInstance; + Expression getterExp = new Expression(box.getAlignmentX(), box, "getAlignmentX", null); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); @@ -47,26 +39,21 @@ protected void initialize(Class type, Object oldInstance, Object targetVal = enc.get(oldVal); // Get the current property value in the new environment Object newVal = null; - Box newBox = (Box) newInstance; - newVal = new Expression(newBox.getAlignmentX(), newBox, - "AlignmentX", null).getValue(); + Box newBox = (Box)newInstance; + newVal = new Expression(newBox.getAlignmentX(), newBox, "AlignmentX", null).getValue(); /* - * Make the target value and current property value equivalent in - * the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null - Statement setterStm = new Statement(oldInstance, "setAlignmentX", - new Object[] { null }); + Statement setterStm = new Statement(oldInstance, "setAlignmentX", new Object[] {null}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal - .getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - Statement setterStm = new Statement(oldInstance, - "setAlignmentX", new Object[] { oldVal }); + Statement setterStm = new Statement(oldInstance, "setAlignmentX", new Object[] {oldVal}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/SwingDefaultComboBoxModelPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/SwingDefaultComboBoxModelPersistenceDelegate.java index 0d3f234ace0..d462c76e901 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/SwingDefaultComboBoxModelPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/SwingDefaultComboBoxModelPersistenceDelegate.java @@ -17,29 +17,20 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import javax.swing.DefaultComboBoxModel; - -class SwingDefaultComboBoxModelPersistenceDelegate extends - DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { +class SwingDefaultComboBoxModelPersistenceDelegate extends DefaultPersistenceDelegate { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { super.initialize(type, oldInstance, newInstance, enc); - DefaultComboBoxModel model = (DefaultComboBoxModel) oldInstance; + DefaultComboBoxModel model = (DefaultComboBoxModel)oldInstance; int count = model.getSize(); Expression getterExp = null; for (int i = 0; i < count; i++) { - getterExp = new Expression(model, "getElementAt", new Object[] { i }); + getterExp = new Expression(model, "getElementAt", new Object[] {i}); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); @@ -50,30 +41,25 @@ protected void initialize(Class type, Object oldInstance, // Get the current property value in the new environment Object newVal = null; try { - newVal = new Expression(newInstance, "getElementAt", - new Object[] { i }).getValue(); + newVal = new Expression(newInstance, "getElementAt", new Object[] {i}).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* - * Make the target value and current property value equivalent - * in the new environment + * Make the target value and current property value equivalent in the new environment */ Statement setterStm = null; if (null == targetVal) { if (null != newVal) { // Set to null - setterStm = new Statement(oldInstance, "addElement", - new Object[] { null }); + setterStm = new Statement(oldInstance, "addElement", new Object[] {null}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - setterStm = new Statement(oldInstance, "addElement", - new Object[] { oldVal }); + setterStm = new Statement(oldInstance, "addElement", new Object[] {oldVal}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/SwingJFramePersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/SwingJFramePersistenceDelegate.java index 65d484d549e..9443ee298b2 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/SwingJFramePersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/SwingJFramePersistenceDelegate.java @@ -19,68 +19,54 @@ import java.awt.Container; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import javax.swing.JFrame; class SwingJFramePersistenceDelegate extends DefaultPersistenceDelegate { - @Override - @SuppressWarnings("nls") - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - // Call the initialization of the super type - super.initialize(type, oldInstance, newInstance, enc); - // Continue only if initializing the "current" type - if (type != oldInstance.getClass()) { - return; - } - - - JFrame frame = (JFrame) oldInstance; - Container container = frame.getContentPane(); - int count = container.getComponentCount(); - if(count != 0) { - Expression getterExp = new Expression(frame, - "getContentPane", null); - try { - // Calculate the old value of the property - Object oldVal = getterExp.getValue(); - // Write the getter expression to the encoder - enc.writeExpression(getterExp); - // Get the target value that exists in the new environment - Object targetVal = enc.get(oldVal); - // Get the current property value in the new environment - Object newVal = null; - JFrame newFrame = (JFrame) newInstance; - newVal = new Expression(newFrame.getContentPane(), newFrame, - "getContentPane", null).getValue(); - /* - * Make the target value and current property value equivalent - * in the new environment + @Override + @SuppressWarnings("nls") + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + // Call the initialization of the super type + super.initialize(type, oldInstance, newInstance, enc); + // Continue only if initializing the "current" type + if (type != oldInstance.getClass()) { + return; + } + + JFrame frame = (JFrame)oldInstance; + Container container = frame.getContentPane(); + int count = container.getComponentCount(); + if (count != 0) { + Expression getterExp = new Expression(frame, "getContentPane", null); + try { + // Calculate the old value of the property + Object oldVal = getterExp.getValue(); + // Write the getter expression to the encoder + enc.writeExpression(getterExp); + // Get the target value that exists in the new environment + Object targetVal = enc.get(oldVal); + // Get the current property value in the new environment + Object newVal = null; + JFrame newFrame = (JFrame)newInstance; + newVal = new Expression(newFrame.getContentPane(), newFrame, "getContentPane", null).getValue(); + /* + * Make the target value and current property value equivalent in the new environment */ - if (null == targetVal) { - if (null != newVal) { - // Set to null - Statement setterStm = new Statement(oldInstance, "setContentPane", - new Object[] { null }); - enc.writeStatement(setterStm); - } - } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); - if (!pd.mutatesTo(targetVal, newVal)) { - Statement setterStm = new Statement(oldInstance, "setContentPane", - new Object[] { oldVal }); - enc.writeStatement(setterStm); - } - } - } catch (Exception ex) { - enc.getExceptionListener().exceptionThrown(ex); - } - } + if (null == targetVal) { + if (null != newVal) { + // Set to null + Statement setterStm = new Statement(oldInstance, "setContentPane", new Object[] {null}); + enc.writeStatement(setterStm); + } + } else { + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); + if (!pd.mutatesTo(targetVal, newVal)) { + Statement setterStm = new Statement(oldInstance, "setContentPane", new Object[] {oldVal}); + enc.writeStatement(setterStm); + } + } + } catch (Exception ex) { + enc.getExceptionListener().exceptionThrown(ex); + } + } } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/SwingJTabbedPanePersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/SwingJTabbedPanePersistenceDelegate.java index ee7857f0c39..ae8a14b0f33 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/SwingJTabbedPanePersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/SwingJTabbedPanePersistenceDelegate.java @@ -17,69 +17,56 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.Statement; - import javax.swing.JTabbedPane; -class SwingJTabbedPanePersistenceDelegate extends - DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { - // Call the initialization of the super type - super.initialize(type, oldInstance, newInstance, enc); - // Continue only if initializing the "current" type - if (type != oldInstance.getClass()) { - return; - } - - - JTabbedPane pane = (JTabbedPane) oldInstance; - int count = pane.getTabCount(); - for (int i = 0; i < count; i++) { - Expression getterExp = new Expression(pane.getComponentAt(i), pane, - "getComponentAt", new Object[] { i }); +class SwingJTabbedPanePersistenceDelegate extends DefaultPersistenceDelegate { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { + // Call the initialization of the super type + super.initialize(type, oldInstance, newInstance, enc); + // Continue only if initializing the "current" type + if (type != oldInstance.getClass()) { + return; + } + + JTabbedPane pane = (JTabbedPane)oldInstance; + int count = pane.getTabCount(); + for (int i = 0; i < count; i++) { + Expression getterExp = new Expression(pane.getComponentAt(i), pane, "getComponentAt", new Object[] {i}); try { - // Calculate the old value of the property - Object oldVal = getterExp.getValue(); - // Write the getter expression to the encoder - enc.writeExpression(getterExp); - // Get the target value that exists in the new environment - Object targetVal = enc.get(oldVal); - // Get the current property value in the new environment - Object newVal = null; - try { - JTabbedPane newJTabbedPane = (JTabbedPane) newInstance; - newVal = new Expression(newJTabbedPane.getComponent(i), - newJTabbedPane, "getComponentAt", - new Object[] { i }).getValue(); + // Calculate the old value of the property + Object oldVal = getterExp.getValue(); + // Write the getter expression to the encoder + enc.writeExpression(getterExp); + // Get the target value that exists in the new environment + Object targetVal = enc.get(oldVal); + // Get the current property value in the new environment + Object newVal = null; + try { + JTabbedPane newJTabbedPane = (JTabbedPane)newInstance; + newVal = new Expression(newJTabbedPane.getComponent(i), newJTabbedPane, "getComponentAt", new Object[] {i}) + .getValue(); } catch (ArrayIndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } - /* - * Make the target value and current property value equivalent - * in the new environment + /* + * Make the target value and current property value equivalent in the new environment */ - if (null == targetVal) { - if (null != newVal) { - // Set to null - Statement setterStm = new Statement(oldInstance, "addTab", - new Object[] { pane.getTitleAt(i), oldVal }); - enc.writeStatement(setterStm); - } - } else { - Statement setterStm = new Statement(oldInstance, "addTab", - new Object[] { pane.getTitleAt(i), oldVal }); - enc.writeStatement(setterStm); - } - } catch (Exception ex) { - enc.getExceptionListener().exceptionThrown(ex); - } + if (null == targetVal) { + if (null != newVal) { + // Set to null + Statement setterStm = new Statement(oldInstance, "addTab", new Object[] {pane.getTitleAt(i), oldVal}); + enc.writeStatement(setterStm); + } + } else { + Statement setterStm = new Statement(oldInstance, "addTab", new Object[] {pane.getTitleAt(i), oldVal}); + enc.writeStatement(setterStm); + } + } catch (Exception ex) { + enc.getExceptionListener().exceptionThrown(ex); + } } } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/SwingToolTipManagerPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/SwingToolTipManagerPersistenceDelegate.java index 1500e896e43..359e747a140 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/SwingToolTipManagerPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/SwingToolTipManagerPersistenceDelegate.java @@ -17,16 +17,11 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; - class SwingToolTipManagerPersistenceDelegate extends PersistenceDelegate { @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - return new Expression(oldInstance, oldInstance.getClass(), - "sharedInstance", null); //$NON-NLS-1$ + protected Expression instantiate (Object oldInstance, Encoder enc) { + return new Expression(oldInstance, oldInstance.getClass(), "sharedInstance", null); //$NON-NLS-1$ } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/UtilCollectionPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/UtilCollectionPersistenceDelegate.java index 2f93d29bafa..18893934a95 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/UtilCollectionPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/UtilCollectionPersistenceDelegate.java @@ -17,61 +17,49 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import java.util.Collection; import java.util.Iterator; -class UtilCollectionPersistenceDelegate extends - DefaultPersistenceDelegate { - @Override - @SuppressWarnings("nls") - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { +class UtilCollectionPersistenceDelegate extends DefaultPersistenceDelegate { + @Override + @SuppressWarnings("nls") + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { - Collection oldList = (Collection) oldInstance; - Collection newList = (Collection) newInstance; - Iterator oldIterator = oldList.iterator(), newIterator = newList.iterator(); - for (; oldIterator.hasNext();) { - Expression getterExp = new Expression(oldIterator, "next", null); - try { - // Calculate the old value of the property - Object oldVal = getterExp.getValue(); + Collection oldList = (Collection)oldInstance; + Collection newList = (Collection)newInstance; + Iterator oldIterator = oldList.iterator(), newIterator = newList.iterator(); + for (; oldIterator.hasNext();) { + Expression getterExp = new Expression(oldIterator, "next", null); + try { + // Calculate the old value of the property + Object oldVal = getterExp.getValue(); - Object newVal = null; - try { - newVal = new Expression(newIterator, "next", null).getValue(); - } catch (ArrayIndexOutOfBoundsException ex) { - // The newInstance has no elements, so current property - // value remains null - } - /* - * Make the target value and current property value equivalent - * in the new environment - */ - if (null == oldVal) { - if (null != newVal) { - // Set to null - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { null }); - enc.writeStatement(setterStm); - } - } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(oldVal.getClass()); - if (!pd.mutatesTo(oldVal, newVal)) { - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { oldVal }); - enc.writeStatement(setterStm); - } - } - } catch (Exception ex) { - enc.getExceptionListener().exceptionThrown(ex); - } - } - } + Object newVal = null; + try { + newVal = new Expression(newIterator, "next", null).getValue(); + } catch (ArrayIndexOutOfBoundsException ex) { + // The newInstance has no elements, so current property + // value remains null + } + /* + * Make the target value and current property value equivalent in the new environment + */ + if (null == oldVal) { + if (null != newVal) { + // Set to null + Statement setterStm = new Statement(oldInstance, "add", new Object[] {null}); + enc.writeStatement(setterStm); + } + } else { + PersistenceDelegate pd = enc.getPersistenceDelegate(oldVal.getClass()); + if (!pd.mutatesTo(oldVal, newVal)) { + Statement setterStm = new Statement(oldInstance, "add", new Object[] {oldVal}); + enc.writeStatement(setterStm); + } + } + } catch (Exception ex) { + enc.getExceptionListener().exceptionThrown(ex); + } + } + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/UtilDatePersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/UtilDatePersistenceDelegate.java index 4475691f13b..bb30aecdfac 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/UtilDatePersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/UtilDatePersistenceDelegate.java @@ -17,19 +17,14 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; - import java.util.Date; import org.apache.harmony.beans.BeansUtils; class UtilDatePersistenceDelegate extends DefaultPersistenceDelegate { - @Override - protected Expression instantiate(Object oldInstance, Encoder enc) { - Date date = (Date) oldInstance; - return new Expression(oldInstance, oldInstance.getClass(), - BeansUtils.NEW, new Object[] { date.getTime() }); - } + @Override + protected Expression instantiate (Object oldInstance, Encoder enc) { + Date date = (Date)oldInstance; + return new Expression(oldInstance, oldInstance.getClass(), BeansUtils.NEW, new Object[] {date.getTime()}); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/UtilListPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/UtilListPersistenceDelegate.java index bae08883424..83ef6f89349 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/UtilListPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/UtilListPersistenceDelegate.java @@ -17,64 +17,51 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import java.util.List; class UtilListPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "nls", "boxing" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + @Override + @SuppressWarnings({"nls", "boxing"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { - List list = (List) oldInstance; - int size = list.size(); - for (int i = 0; i < size; i++) { - Expression getterExp = new Expression(oldInstance, "get", - new Object[] { i }); - try { - // Calculate the old value of the property - Object oldVal = getterExp.getValue(); - // Write the getter expression to the encoder - enc.writeExpression(getterExp); - // Get the target value that exists in the new environment - Object targetVal = enc.get(oldVal); - // Get the current property value in the new environment - Object newVal = null; - try { - newVal = new Expression(newInstance, "get", - new Object[] { i }).getValue(); - } catch (IndexOutOfBoundsException ex) { - // The newInstance has no elements, so current property - // value remains null - } - /* - * Make the target value and current property value equivalent - * in the new environment - */ - if (null == targetVal) { - if (null != newVal) { - // Set to null - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { null }); - enc.writeStatement(setterStm); - } - } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); - if (!pd.mutatesTo(targetVal, newVal)) { - Statement setterStm = new Statement(oldInstance, "add", - new Object[] { oldVal }); - enc.writeStatement(setterStm); - } - } - } catch (Exception ex) { - enc.getExceptionListener().exceptionThrown(ex); - } - } - } -} \ No newline at end of file + List list = (List)oldInstance; + int size = list.size(); + for (int i = 0; i < size; i++) { + Expression getterExp = new Expression(oldInstance, "get", new Object[] {i}); + try { + // Calculate the old value of the property + Object oldVal = getterExp.getValue(); + // Write the getter expression to the encoder + enc.writeExpression(getterExp); + // Get the target value that exists in the new environment + Object targetVal = enc.get(oldVal); + // Get the current property value in the new environment + Object newVal = null; + try { + newVal = new Expression(newInstance, "get", new Object[] {i}).getValue(); + } catch (IndexOutOfBoundsException ex) { + // The newInstance has no elements, so current property + // value remains null + } + /* + * Make the target value and current property value equivalent in the new environment + */ + if (null == targetVal) { + if (null != newVal) { + // Set to null + Statement setterStm = new Statement(oldInstance, "add", new Object[] {null}); + enc.writeStatement(setterStm); + } + } else { + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); + if (!pd.mutatesTo(targetVal, newVal)) { + Statement setterStm = new Statement(oldInstance, "add", new Object[] {oldVal}); + enc.writeStatement(setterStm); + } + } + } catch (Exception ex) { + enc.getExceptionListener().exceptionThrown(ex); + } + } + } +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/UtilMapPersistenceDelegate.java b/extensions/beans/src/com/badlogic/gdx/beans/UtilMapPersistenceDelegate.java index 90b7f501b42..5900e2f3b93 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/UtilMapPersistenceDelegate.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/UtilMapPersistenceDelegate.java @@ -17,30 +17,22 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.DefaultPersistenceDelegate; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.PersistenceDelegate; -import com.badlogic.gdx.beans.Statement; - import java.util.Iterator; import java.util.Map; import java.util.Set; class UtilMapPersistenceDelegate extends DefaultPersistenceDelegate { - @Override - @SuppressWarnings({ "unchecked", "nls" }) - protected void initialize(Class type, Object oldInstance, - Object newInstance, Encoder enc) { + @Override + @SuppressWarnings({"unchecked", "nls"}) + protected void initialize (Class type, Object oldInstance, Object newInstance, Encoder enc) { // Call the initialization of the super type super.initialize(type, oldInstance, newInstance, enc); - Map map = (Map) oldInstance; + Map map = (Map)oldInstance; Set keySet = map.keySet(); for (Iterator i = keySet.iterator(); i.hasNext();) { Object key = i.next(); - Expression getterExp = new Expression(oldInstance, "get", - new Object[] { key}); + Expression getterExp = new Expression(oldInstance, "get", new Object[] {key}); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); @@ -51,28 +43,24 @@ protected void initialize(Class type, Object oldInstance, // Get the current property value in the new environment Object newVal = null; try { - newVal = new Expression(newInstance, "get", new Object[] { key }).getValue(); + newVal = new Expression(newInstance, "get", new Object[] {key}).getValue(); } catch (ArrayIndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* - * Make the target value and current property value equivalent - * in the new environment + * Make the target value and current property value equivalent in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null - Statement setterStm = new Statement(oldInstance, "put", - new Object[] { key, null }); + Statement setterStm = new Statement(oldInstance, "put", new Object[] {key, null}); enc.writeStatement(setterStm); } } else { - PersistenceDelegate pd = enc - .getPersistenceDelegate(targetVal.getClass()); + PersistenceDelegate pd = enc.getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { - Statement setterStm = new Statement(oldInstance, "put", - new Object[] { key, oldVal }); + Statement setterStm = new Statement(oldInstance, "put", new Object[] {key, oldVal}); enc.writeStatement(setterStm); } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListener.java b/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListener.java index 16f3ca76654..93a1a02ac65 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListener.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListener.java @@ -17,13 +17,9 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyVetoException; - import java.util.EventListener; public interface VetoableChangeListener extends EventListener { - public void vetoableChange(PropertyChangeEvent evt) - throws PropertyVetoException; + public void vetoableChange (PropertyChangeEvent evt) throws PropertyVetoException; } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListenerProxy.java b/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListenerProxy.java index f1647d2fa7d..5d0c6e65820 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListenerProxy.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeListenerProxy.java @@ -17,30 +17,23 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyVetoException; -import com.badlogic.gdx.beans.VetoableChangeListener; - import java.util.EventListenerProxy; -public class VetoableChangeListenerProxy extends EventListenerProxy implements - VetoableChangeListener { +public class VetoableChangeListenerProxy extends EventListenerProxy implements VetoableChangeListener { - private String propertyName; + private String propertyName; - public VetoableChangeListenerProxy(String propertyName, - VetoableChangeListener listener) { - super(listener); - this.propertyName = propertyName; - } + public VetoableChangeListenerProxy (String propertyName, VetoableChangeListener listener) { + super(listener); + this.propertyName = propertyName; + } - public String getPropertyName() { - return propertyName; - } + public String getPropertyName () { + return propertyName; + } - public void vetoableChange(PropertyChangeEvent evt) - throws PropertyVetoException { - VetoableChangeListener listener = (VetoableChangeListener) getListener(); - listener.vetoableChange(evt); - } + public void vetoableChange (PropertyChangeEvent evt) throws PropertyVetoException { + VetoableChangeListener listener = (VetoableChangeListener)getListener(); + listener.vetoableChange(evt); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeSupport.java b/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeSupport.java index a2e0dab86f5..5c8b5bae841 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeSupport.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/VetoableChangeSupport.java @@ -17,12 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyVetoException; -import com.badlogic.gdx.beans.VetoableChangeListener; -import com.badlogic.gdx.beans.VetoableChangeListenerProxy; -import com.badlogic.gdx.beans.VetoableChangeSupport; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -36,224 +30,198 @@ public class VetoableChangeSupport implements Serializable { - private static final long serialVersionUID = -5090210921595982017l; - - private Hashtable children = new Hashtable(); - - private transient ArrayList globalListeners = new ArrayList(); - - private Object source; - - @SuppressWarnings("unused") - // for serialization - private int vetoableChangeSupportSerializedDataVersion = 2; - - public VetoableChangeSupport(Object sourceBean) { - if (sourceBean == null) { - throw new NullPointerException(); - } - this.source = sourceBean; - } - - public synchronized void removeVetoableChangeListener(String propertyName, - VetoableChangeListener listener) { - if ((propertyName != null) && (listener != null)) { - VetoableChangeSupport listeners = children.get(propertyName); - - if (listeners != null) { - listeners.removeVetoableChangeListener(listener); - } - } - } - - public synchronized void addVetoableChangeListener(String propertyName, - VetoableChangeListener listener) { - if (propertyName != null && listener != null) { - VetoableChangeSupport listeners = children.get(propertyName); - - if (listeners == null) { - listeners = new VetoableChangeSupport(source); - children.put(propertyName, listeners); - } - listeners.addVetoableChangeListener(listener); - } - } - - public synchronized VetoableChangeListener[] getVetoableChangeListeners( - String propertyName) { - VetoableChangeSupport listeners = null; - - if (propertyName != null) { - listeners = children.get(propertyName); - } - return (listeners == null) ? new VetoableChangeListener[] {} - : getAsVetoableChangeListenerArray(listeners); - } - - public synchronized boolean hasListeners(String propertyName) { - boolean result = globalListeners.size() > 0; - if (!result && propertyName != null) { - VetoableChangeSupport listeners = children.get(propertyName); - if (listeners != null) { - result = listeners.globalListeners.size() > 0; - } - } - return result; - } - - public synchronized void removeVetoableChangeListener( - VetoableChangeListener listener) { - if (listener != null) { - globalListeners.remove(listener); - } - } - - public synchronized void addVetoableChangeListener( - VetoableChangeListener listener) { - if (listener != null) { - if (listener instanceof VetoableChangeListenerProxy) { - VetoableChangeListenerProxy proxy = (VetoableChangeListenerProxy) listener; - addVetoableChangeListener(proxy.getPropertyName(), - (VetoableChangeListener) proxy.getListener()); - } else { - globalListeners.add(listener); - } - } - } - - public synchronized VetoableChangeListener[] getVetoableChangeListeners() { - List result = new ArrayList(); - if (globalListeners != null) { - result.addAll(globalListeners); - } - - for (Iterator iterator = children.keySet().iterator(); iterator - .hasNext();) { - String propertyName = iterator.next(); - VetoableChangeSupport namedListener = children - .get(propertyName); - VetoableChangeListener[] childListeners = namedListener - .getVetoableChangeListeners(); - for (int i = 0; i < childListeners.length; i++) { - result.add(new VetoableChangeListenerProxy(propertyName, - childListeners[i])); - } - } - return (result - .toArray(new VetoableChangeListener[result.size()])); - } - - private void writeObject(ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - VetoableChangeListener[] copy = new VetoableChangeListener[globalListeners - .size()]; - globalListeners.toArray(copy); - for (VetoableChangeListener listener : copy) { - if (listener instanceof Serializable) { - oos.writeObject(listener); - } - } - // Denotes end of list - oos.writeObject(null); - - } - - private void readObject(ObjectInputStream ois) throws IOException, - ClassNotFoundException { - ois.defaultReadObject(); - this.globalListeners = new ArrayList(); - if (null == this.children) { - this.children = new Hashtable(); - } - Object listener; - do { - // Reads a listener _or_ proxy - listener = ois.readObject(); - addVetoableChangeListener((VetoableChangeListener) listener); - } while (listener != null); - } - - @SuppressWarnings("boxing") - public void fireVetoableChange(String propertyName, boolean oldValue, - boolean newValue) throws PropertyVetoException { - PropertyChangeEvent event = createPropertyChangeEvent(propertyName, - oldValue, newValue); - doFirePropertyChange(event); - } - - @SuppressWarnings("boxing") - public void fireVetoableChange(String propertyName, int oldValue, - int newValue) throws PropertyVetoException { - PropertyChangeEvent event = createPropertyChangeEvent(propertyName, - oldValue, newValue); - doFirePropertyChange(event); - } - - public void fireVetoableChange(String propertyName, Object oldValue, - Object newValue) throws PropertyVetoException { - PropertyChangeEvent event = createPropertyChangeEvent(propertyName, - oldValue, newValue); - doFirePropertyChange(event); - } - - public void fireVetoableChange(PropertyChangeEvent event) - throws PropertyVetoException { - doFirePropertyChange(event); - } - - private PropertyChangeEvent createPropertyChangeEvent(String propertyName, - Object oldValue, Object newValue) { - return new PropertyChangeEvent(source, propertyName, oldValue, newValue); - } - - private void doFirePropertyChange(PropertyChangeEvent event) - throws PropertyVetoException { - String propName = event.getPropertyName(); - Object oldValue = event.getOldValue(); - Object newValue = event.getNewValue(); - - if (newValue != null && oldValue != null && newValue.equals(oldValue)) { - return; - } - - /* Take note of who we are going to notify (and potentially un-notify) */ - - VetoableChangeListener[] listensToAll; - VetoableChangeSupport listeners = null; - // property change - synchronized (this) { - listensToAll = globalListeners - .toArray(new VetoableChangeListener[0]); - String propertyName = event.getPropertyName(); - if (propertyName != null) { - listeners = children.get(propertyName); - } - } - - try { - for (VetoableChangeListener listener : listensToAll) { - listener.vetoableChange(event); - } - } catch (PropertyVetoException pve) { - // Tell them we have changed it back - PropertyChangeEvent revertEvent = createPropertyChangeEvent( - propName, newValue, oldValue); - for (VetoableChangeListener listener : listensToAll) { - try { - listener.vetoableChange(revertEvent); - } catch (PropertyVetoException ignored) { - // expected - } - } - throw pve; - } - if (listeners != null) { - listeners.fireVetoableChange(event); - } - } - - private static VetoableChangeListener[] getAsVetoableChangeListenerArray( - VetoableChangeSupport listeners) { - return listeners.globalListeners.toArray(new VetoableChangeListener[0]); - } + private static final long serialVersionUID = -5090210921595982017l; + + private Hashtable children = new Hashtable(); + + private transient ArrayList globalListeners = new ArrayList(); + + private Object source; + + @SuppressWarnings("unused") + // for serialization + private int vetoableChangeSupportSerializedDataVersion = 2; + + public VetoableChangeSupport (Object sourceBean) { + if (sourceBean == null) { + throw new NullPointerException(); + } + this.source = sourceBean; + } + + public synchronized void removeVetoableChangeListener (String propertyName, VetoableChangeListener listener) { + if ((propertyName != null) && (listener != null)) { + VetoableChangeSupport listeners = children.get(propertyName); + + if (listeners != null) { + listeners.removeVetoableChangeListener(listener); + } + } + } + + public synchronized void addVetoableChangeListener (String propertyName, VetoableChangeListener listener) { + if (propertyName != null && listener != null) { + VetoableChangeSupport listeners = children.get(propertyName); + + if (listeners == null) { + listeners = new VetoableChangeSupport(source); + children.put(propertyName, listeners); + } + listeners.addVetoableChangeListener(listener); + } + } + + public synchronized VetoableChangeListener[] getVetoableChangeListeners (String propertyName) { + VetoableChangeSupport listeners = null; + + if (propertyName != null) { + listeners = children.get(propertyName); + } + return (listeners == null) ? new VetoableChangeListener[] {} : getAsVetoableChangeListenerArray(listeners); + } + + public synchronized boolean hasListeners (String propertyName) { + boolean result = globalListeners.size() > 0; + if (!result && propertyName != null) { + VetoableChangeSupport listeners = children.get(propertyName); + if (listeners != null) { + result = listeners.globalListeners.size() > 0; + } + } + return result; + } + + public synchronized void removeVetoableChangeListener (VetoableChangeListener listener) { + if (listener != null) { + globalListeners.remove(listener); + } + } + + public synchronized void addVetoableChangeListener (VetoableChangeListener listener) { + if (listener != null) { + if (listener instanceof VetoableChangeListenerProxy) { + VetoableChangeListenerProxy proxy = (VetoableChangeListenerProxy)listener; + addVetoableChangeListener(proxy.getPropertyName(), (VetoableChangeListener)proxy.getListener()); + } else { + globalListeners.add(listener); + } + } + } + + public synchronized VetoableChangeListener[] getVetoableChangeListeners () { + List result = new ArrayList(); + if (globalListeners != null) { + result.addAll(globalListeners); + } + + for (Iterator iterator = children.keySet().iterator(); iterator.hasNext();) { + String propertyName = iterator.next(); + VetoableChangeSupport namedListener = children.get(propertyName); + VetoableChangeListener[] childListeners = namedListener.getVetoableChangeListeners(); + for (int i = 0; i < childListeners.length; i++) { + result.add(new VetoableChangeListenerProxy(propertyName, childListeners[i])); + } + } + return (result.toArray(new VetoableChangeListener[result.size()])); + } + + private void writeObject (ObjectOutputStream oos) throws IOException { + oos.defaultWriteObject(); + VetoableChangeListener[] copy = new VetoableChangeListener[globalListeners.size()]; + globalListeners.toArray(copy); + for (VetoableChangeListener listener : copy) { + if (listener instanceof Serializable) { + oos.writeObject(listener); + } + } + // Denotes end of list + oos.writeObject(null); + + } + + private void readObject (ObjectInputStream ois) throws IOException, ClassNotFoundException { + ois.defaultReadObject(); + this.globalListeners = new ArrayList(); + if (null == this.children) { + this.children = new Hashtable(); + } + Object listener; + do { + // Reads a listener _or_ proxy + listener = ois.readObject(); + addVetoableChangeListener((VetoableChangeListener)listener); + } while (listener != null); + } + + @SuppressWarnings("boxing") + public void fireVetoableChange (String propertyName, boolean oldValue, boolean newValue) throws PropertyVetoException { + PropertyChangeEvent event = createPropertyChangeEvent(propertyName, oldValue, newValue); + doFirePropertyChange(event); + } + + @SuppressWarnings("boxing") + public void fireVetoableChange (String propertyName, int oldValue, int newValue) throws PropertyVetoException { + PropertyChangeEvent event = createPropertyChangeEvent(propertyName, oldValue, newValue); + doFirePropertyChange(event); + } + + public void fireVetoableChange (String propertyName, Object oldValue, Object newValue) throws PropertyVetoException { + PropertyChangeEvent event = createPropertyChangeEvent(propertyName, oldValue, newValue); + doFirePropertyChange(event); + } + + public void fireVetoableChange (PropertyChangeEvent event) throws PropertyVetoException { + doFirePropertyChange(event); + } + + private PropertyChangeEvent createPropertyChangeEvent (String propertyName, Object oldValue, Object newValue) { + return new PropertyChangeEvent(source, propertyName, oldValue, newValue); + } + + private void doFirePropertyChange (PropertyChangeEvent event) throws PropertyVetoException { + String propName = event.getPropertyName(); + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + + if (newValue != null && oldValue != null && newValue.equals(oldValue)) { + return; + } + + /* Take note of who we are going to notify (and potentially un-notify) */ + + VetoableChangeListener[] listensToAll; + VetoableChangeSupport listeners = null; + // property change + synchronized (this) { + listensToAll = globalListeners.toArray(new VetoableChangeListener[0]); + String propertyName = event.getPropertyName(); + if (propertyName != null) { + listeners = children.get(propertyName); + } + } + + try { + for (VetoableChangeListener listener : listensToAll) { + listener.vetoableChange(event); + } + } catch (PropertyVetoException pve) { + // Tell them we have changed it back + PropertyChangeEvent revertEvent = createPropertyChangeEvent(propName, newValue, oldValue); + for (VetoableChangeListener listener : listensToAll) { + try { + listener.vetoableChange(revertEvent); + } catch (PropertyVetoException ignored) { + // expected + } + } + throw pve; + } + if (listeners != null) { + listeners.fireVetoableChange(event); + } + } + + private static VetoableChangeListener[] getAsVetoableChangeListenerArray (VetoableChangeSupport listeners) { + return listeners.globalListeners.toArray(new VetoableChangeListener[0]); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/Visibility.java b/extensions/beans/src/com/badlogic/gdx/beans/Visibility.java index 4f3df1e90e9..b8783bed813 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/Visibility.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/Visibility.java @@ -19,11 +19,11 @@ public interface Visibility { - public boolean needsGui(); + public boolean needsGui (); - public boolean avoidingGui(); + public boolean avoidingGui (); - public void okToUseGui(); + public void okToUseGui (); - public void dontUseGui(); + public void dontUseGui (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/XMLDecoder.java b/extensions/beans/src/com/badlogic/gdx/beans/XMLDecoder.java index 962032b242a..c38590901e2 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/XMLDecoder.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/XMLDecoder.java @@ -17,10 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.ExceptionListener; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.Statement.MethodComparator; - import java.io.InputStream; import java.lang.reflect.Array; import java.lang.reflect.Field; @@ -37,642 +33,586 @@ import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; +import com.badlogic.gdx.beans.Statement.MethodComparator; -/** - * XMLDecoder reads objects from xml created by - * XMLEncoder. +/** XMLDecoder reads objects from xml created by XMLEncoder. *

        * The API is similar to ObjectInputStream. - *

        - */ + *

        */ public class XMLDecoder { - private ClassLoader defaultClassLoader = null; - - private static class DefaultExceptionListener implements ExceptionListener { - - public void exceptionThrown(Exception e) { - System.err.println(e.getMessage()); - System.err.println("Continue..."); //$NON-NLS-1$ - } - } - - private class SAXHandler extends DefaultHandler { - - boolean inJavaElem = false; - - HashMap idObjMap = new HashMap(); - - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - if (!inJavaElem) { - return; - } - if (readObjs.size() > 0) { - Elem elem = readObjs.peek(); - if (elem.isBasicType) { - String str = new String(ch, start, length); - elem.methodName = elem.methodName == null ? str - : elem.methodName + str; - } - } - } - - @SuppressWarnings("nls") - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - if (!inJavaElem) { - if ("java".equals(qName)) { - inJavaElem = true; - } else { - listener.exceptionThrown(new Exception( - Messages.getString("beans.72", qName))); - } - return; - } - - if ("object".equals(qName)) { - startObjectElem(attributes); - } else if ("array".equals(qName)) { - startArrayElem(attributes); - } else if ("void".equals(qName)) { - startVoidElem(attributes); - } else if ("boolean".equals(qName) || "byte".equals(qName) - || "char".equals(qName) || "class".equals(qName) - || "double".equals(qName) || "float".equals(qName) - || "int".equals(qName) || "long".equals(qName) - || "short".equals(qName) || "string".equals(qName) - || "null".equals(qName)) { - startBasicElem(qName, attributes); - } - } - - @SuppressWarnings("nls") - private void startObjectElem(Attributes attributes) { - Elem elem = new Elem(); - elem.isExpression = true; - elem.id = attributes.getValue("id"); - elem.idref = attributes.getValue("idref"); - if (elem.idref == null) { - obtainTarget(elem, attributes); - obtainMethod(elem, attributes); - } - - readObjs.push(elem); - } - - private void obtainTarget(Elem elem, Attributes attributes) { - String className = attributes.getValue("class"); //$NON-NLS-1$ - if (className != null) { - try { - elem.target = classForName(className); - } catch (ClassNotFoundException e) { - listener.exceptionThrown(e); - } - } else { - Elem parent = latestUnclosedElem(); - if (parent == null) { - elem.target = owner; - return; - } - elem.target = execute(parent); - } - } - - @SuppressWarnings("nls") - private void obtainMethod(Elem elem, Attributes attributes) { - elem.methodName = attributes.getValue("method"); - if (elem.methodName != null) { - return; - } - - elem.methodName = attributes.getValue("property"); - if (elem.methodName != null) { - elem.fromProperty = true; - return; - } - - elem.methodName = attributes.getValue("index"); - if (elem.methodName != null) { - elem.fromIndex = true; - return; - } - - elem.methodName = attributes.getValue("field"); - if (elem.methodName != null) { - elem.fromField = true; - return; - } - - elem.methodName = attributes.getValue("owner"); - if (elem.methodName != null) { - elem.fromOwner = true; - return; - } - - elem.methodName = "new"; // default method name - } - - @SuppressWarnings("nls") - private Class classForName(String className) - throws ClassNotFoundException { - if ("boolean".equals(className)) { - return Boolean.TYPE; - } else if ("byte".equals(className)) { - return Byte.TYPE; - } else if ("char".equals(className)) { - return Character.TYPE; - } else if ("double".equals(className)) { - return Double.TYPE; - } else if ("float".equals(className)) { - return Float.TYPE; - } else if ("int".equals(className)) { - return Integer.TYPE; - } else if ("long".equals(className)) { - return Long.TYPE; - } else if ("short".equals(className)) { - return Short.TYPE; - } else { - return Class.forName(className, true, - defaultClassLoader == null ? Thread.currentThread() - .getContextClassLoader() : defaultClassLoader); - } - } - - private void startArrayElem(Attributes attributes) { - Elem elem = new Elem(); - elem.isExpression = true; - elem.id = attributes.getValue("id"); //$NON-NLS-1$ - try { - // find component class - Class compClass = classForName(attributes.getValue("class")); //$NON-NLS-1$ - String lengthValue = attributes.getValue("length"); //$NON-NLS-1$ - if (lengthValue != null) { - // find length - int length = Integer - .parseInt(attributes.getValue("length")); //$NON-NLS-1$ - // execute, new array instance - elem.result = Array.newInstance(compClass, length); - elem.isExecuted = true; - } else { - // create array without length attribute, - // delay the excution to the end, - // get array length from sub element - elem.target = compClass; - elem.methodName = "newArray"; //$NON-NLS-1$ - elem.isExecuted = false; - } - } catch (Exception e) { - listener.exceptionThrown(e); - } - readObjs.push(elem); - } - - @SuppressWarnings("nls") - private void startVoidElem(Attributes attributes) { - Elem elem = new Elem(); - elem.id = attributes.getValue("id"); - obtainTarget(elem, attributes); - obtainMethod(elem, attributes); - readObjs.push(elem); - } - - @SuppressWarnings("nls") - private void startBasicElem(String tagName, Attributes attributes) { - Elem elem = new Elem(); - elem.isBasicType = true; - elem.isExpression = true; - elem.id = attributes.getValue("id"); - elem.idref = attributes.getValue("idref"); - elem.target = tagName; - readObjs.push(elem); - } - - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException { - if (!inJavaElem) { - return; - } - if ("java".equals(qName)) { //$NON-NLS-1$ - inJavaElem = false; - return; - } - // find the elem to close - Elem toClose = latestUnclosedElem(); - // make sure it is executed - execute(toClose); - // set to closed - toClose.isClosed = true; - // pop it and its children - while (readObjs.pop() != toClose) { - // - } - - if (toClose.isExpression) { - // push back expression - readObjs.push(toClose); - } - } - - private Elem latestUnclosedElem() { - for (int i = readObjs.size() - 1; i >= 0; i--) { - Elem elem = readObjs.get(i); - if (!elem.isClosed) { - return elem; - } - } - return null; - } - - private Object execute(Elem elem) { - if (elem.isExecuted) { - return elem.result; - } - - // execute to obtain result - try { - if (elem.idref != null) { - elem.result = idObjMap.get(elem.idref); - } else if (elem.isBasicType) { - elem.result = executeBasic(elem); - } else { - elem.result = executeCommon(elem); - } - } catch (Exception e) { - listener.exceptionThrown(e); - } - - // track id - if (elem.id != null) { - idObjMap.put(elem.id, elem.result); - } - - elem.isExecuted = true; - return elem.result; - } - - @SuppressWarnings("nls") - private Object executeCommon(Elem elem) throws Exception { - // pop args - ArrayList args = new ArrayList(5); - while (readObjs.peek() != elem) { - Elem argElem = readObjs.pop(); - args.add(0, argElem.result); - } - // decide method name - String method = elem.methodName; - if (elem.fromProperty) { - method = (args.size() == 0 ? "get" : "set") - + capitalize(method); - } - if (elem.fromIndex) { - Integer index = Integer.valueOf(method); - args.add(0, index); - method = args.size() == 1 ? "get" : "set"; - } - if (elem.fromField) { - Field f = ((Class) elem.target).getField(method); - return (new Expression(f, "get", new Object[] { null })) - .getValue(); - } - if (elem.fromOwner) { - return owner; - } - - if (elem.target == owner) { - if ("getOwner".equals(method)) { - return owner; - } - Class[] c = new Class[args.size()]; - for (int i = 0; i < args.size(); i++) { - Object arg = args.get(i); - c[i] = (arg == null ? null: arg.getClass()); - } - - // Try actual match method - try { - Method m = owner.getClass().getMethod(method, c); - return m.invoke(owner, args.toArray()); - } catch (NoSuchMethodException e) { - // Do nothing - } - - // Find the specific method matching the parameter - Method mostSpecificMethod = findMethod( - owner instanceof Class ? (Class) owner : owner - .getClass(), method, c); - - return mostSpecificMethod.invoke(owner, args.toArray()); - } - - // execute - Expression exp = new Expression(elem.target, method, args.toArray()); - return exp.getValue(); - } - - private Method findMethod(Class clazz, String methodName, - Class[] clazzes) throws Exception { - Method[] methods = clazz.getMethods(); - ArrayList matchMethods = new ArrayList(); - - // Add all matching methods into a ArrayList - for (Method method : methods) { - if (!methodName.equals(method.getName())) { - continue; - } - Class[] parameterTypes = method.getParameterTypes(); - if (parameterTypes.length != clazzes.length) { - continue; - } - boolean match = true; - for (int i = 0; i < parameterTypes.length; i++) { - boolean isNull = (clazzes[i] == null); - boolean isPrimitive = isPrimitiveWrapper(clazzes[i], parameterTypes[i]); - boolean isAssignable = isNull? false : parameterTypes[i].isAssignableFrom(clazzes[i]); - if ( isNull || isPrimitive || isAssignable ) { - continue; - } - match = false; - } - if (match) { - matchMethods.add(method); - } - } - - int size = matchMethods.size(); - if (size == 1) { - // Only one method matches, just invoke it - return matchMethods.get(0); - } else if (size == 0) { - // Does not find any matching one, throw exception - throw new NoSuchMethodException(Messages.getString( - "beans.41", methodName)); //$NON-NLS-1$ - } - - // There are more than one method matching the signature - // Find the most specific one to invoke - MethodComparator comparator = new MethodComparator(methodName, - clazzes); - Method chosenOne = matchMethods.get(0); - matchMethods.remove(0); - int methodCounter = 1; - for (Method method : matchMethods) { - int difference = comparator.compare(chosenOne, method); - if (difference > 0) { - chosenOne = method; - methodCounter = 1; - } else if (difference == 0) { - methodCounter++; - } - } - if (methodCounter > 1) { - // if 2 methods have same relevance, throw exception - throw new NoSuchMethodException(Messages.getString( - "beans.62", methodName)); //$NON-NLS-1$ - } - return chosenOne; - } - - private boolean isPrimitiveWrapper(Class wrapper, Class base) { - return (base == boolean.class) && (wrapper == Boolean.class) - || (base == byte.class) && (wrapper == Byte.class) - || (base == char.class) && (wrapper == Character.class) - || (base == short.class) && (wrapper == Short.class) - || (base == int.class) && (wrapper == Integer.class) - || (base == long.class) && (wrapper == Long.class) - || (base == float.class) && (wrapper == Float.class) - || (base == double.class) && (wrapper == Double.class); - } - - private String capitalize(String str) { - StringBuilder buf = new StringBuilder(str); - buf.setCharAt(0, Character.toUpperCase(buf.charAt(0))); - return buf.toString(); - } - - @SuppressWarnings("nls") - private Object executeBasic(Elem elem) throws Exception { - String tag = (String) elem.target; - String value = elem.methodName; - - if ("null".equals(tag)) { - return null; - } else if ("string".equals(tag)) { - return value == null ? "" : value; - } else if ("class".equals(tag)) { - return classForName(value); - } else if ("boolean".equals(tag)) { - return Boolean.valueOf(value); - } else if ("byte".equals(tag)) { - return Byte.valueOf(value); - } else if ("char".equals(tag)) { - return Character.valueOf(value.charAt(0)); - } else if ("double".equals(tag)) { - return Double.valueOf(value); - } else if ("float".equals(tag)) { - return Float.valueOf(value); - } else if ("int".equals(tag)) { - return Integer.valueOf(value); - } else if ("long".equals(tag)) { - return Long.valueOf(value); - } else if ("short".equals(tag)) { - return Short.valueOf(value); - } else { - throw new Exception(Messages.getString("beans.71", tag)); - } - } - - @Override - public void error(SAXParseException e) throws SAXException { - listener.exceptionThrown(e); - } - - @Override - public void fatalError(SAXParseException e) throws SAXException { - listener.exceptionThrown(e); - } - - @Override - public void warning(SAXParseException e) throws SAXException { - listener.exceptionThrown(e); - } - } - - private static class Elem { - String id; - - String idref; - - boolean isExecuted; - - boolean isExpression; - - boolean isBasicType; - - boolean isClosed; - - Object target; - - String methodName; - - boolean fromProperty; - - boolean fromIndex; - - boolean fromField; - - boolean fromOwner; - - Object result; - - } - - private InputStream inputStream; - - private ExceptionListener listener; - - private Object owner; - - private Stack readObjs = new Stack(); - - private int readObjIndex = 0; - - private SAXHandler saxHandler = null; - - /** - * Create a decoder to read from specified input stream. - * - * @param inputStream - * an input stream of xml - */ - public XMLDecoder(InputStream inputStream) { - this(inputStream, null, null, null); - } - - /** - * Create a decoder to read from specified input stream. - * - * @param inputStream - * an input stream of xml - * @param owner - * the owner of this decoder - */ - public XMLDecoder(InputStream inputStream, Object owner) { - this(inputStream, owner, null, null); - } - - /** - * Create a decoder to read from specified input stream. - * - * @param inputStream - * an input stream of xml - * @param owner - * the owner of this decoder - * @param listener - * listen to the exceptions thrown by the decoder - */ - public XMLDecoder(InputStream inputStream, Object owner, - ExceptionListener listener) { - this(inputStream, owner, listener, null); - } - - public XMLDecoder(InputStream inputStream, Object owner, - ExceptionListener listener, ClassLoader cl) { - this.inputStream = inputStream; - this.owner = owner; - this.listener = (listener == null) ? new DefaultExceptionListener() - : listener; - defaultClassLoader = cl; - } - - /** - * Close the input stream of xml data. - */ - public void close() { - if (inputStream == null) { - return; - } - try { - inputStream.close(); - } catch (Exception e) { - listener.exceptionThrown(e); - } - } - - /** - * Returns the exception listener. - * - * @return the exception listener - */ - public ExceptionListener getExceptionListener() { - return listener; - } - - /** - * Returns the owner of this decoder. - * - * @return the owner of this decoder - */ - public Object getOwner() { - return owner; - } - - /** - * Reads the next object. - * - * @return the next object - * @exception ArrayIndexOutOfBoundsException - * if no more objects to read - */ - @SuppressWarnings("nls") - public Object readObject() { - if (inputStream == null) { - return null; - } - if (saxHandler == null) { - saxHandler = new SAXHandler(); - try { - SAXParserFactory.newInstance().newSAXParser().parse( - inputStream, saxHandler); - } catch (Exception e) { - this.listener.exceptionThrown(e); - } - } - - if (readObjIndex >= readObjs.size()) { - throw new ArrayIndexOutOfBoundsException(Messages.getString("beans.70")); - } - Elem elem = readObjs.get(readObjIndex); - if (!elem.isClosed) { - // bad element, error occurred while parsing - throw new ArrayIndexOutOfBoundsException(Messages.getString("beans.70")); - } - readObjIndex++; - return elem.result; - } - - /** - * Sets the exception listener. - * - * @param listener - * an exception listener - */ - public void setExceptionListener(ExceptionListener listener) { - if (listener != null) { - this.listener = listener; - } - } - - /** - * Sets the owner of this decoder. - * - * @param owner - * the owner of this decoder - */ - public void setOwner(Object owner) { - this.owner = owner; - } + private ClassLoader defaultClassLoader = null; + + private static class DefaultExceptionListener implements ExceptionListener { + + public void exceptionThrown (Exception e) { + System.err.println(e.getMessage()); + System.err.println("Continue..."); //$NON-NLS-1$ + } + } + + private class SAXHandler extends DefaultHandler { + + boolean inJavaElem = false; + + HashMap idObjMap = new HashMap(); + + @Override + public void characters (char[] ch, int start, int length) throws SAXException { + if (!inJavaElem) { + return; + } + if (readObjs.size() > 0) { + Elem elem = readObjs.peek(); + if (elem.isBasicType) { + String str = new String(ch, start, length); + elem.methodName = elem.methodName == null ? str : elem.methodName + str; + } + } + } + + @SuppressWarnings("nls") + @Override + public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { + if (!inJavaElem) { + if ("java".equals(qName)) { + inJavaElem = true; + } else { + listener.exceptionThrown(new Exception(Messages.getString("beans.72", qName))); + } + return; + } + + if ("object".equals(qName)) { + startObjectElem(attributes); + } else if ("array".equals(qName)) { + startArrayElem(attributes); + } else if ("void".equals(qName)) { + startVoidElem(attributes); + } else if ("boolean".equals(qName) || "byte".equals(qName) || "char".equals(qName) || "class".equals(qName) + || "double".equals(qName) || "float".equals(qName) || "int".equals(qName) || "long".equals(qName) + || "short".equals(qName) || "string".equals(qName) || "null".equals(qName)) { + startBasicElem(qName, attributes); + } + } + + @SuppressWarnings("nls") + private void startObjectElem (Attributes attributes) { + Elem elem = new Elem(); + elem.isExpression = true; + elem.id = attributes.getValue("id"); + elem.idref = attributes.getValue("idref"); + if (elem.idref == null) { + obtainTarget(elem, attributes); + obtainMethod(elem, attributes); + } + + readObjs.push(elem); + } + + private void obtainTarget (Elem elem, Attributes attributes) { + String className = attributes.getValue("class"); //$NON-NLS-1$ + if (className != null) { + try { + elem.target = classForName(className); + } catch (ClassNotFoundException e) { + listener.exceptionThrown(e); + } + } else { + Elem parent = latestUnclosedElem(); + if (parent == null) { + elem.target = owner; + return; + } + elem.target = execute(parent); + } + } + + @SuppressWarnings("nls") + private void obtainMethod (Elem elem, Attributes attributes) { + elem.methodName = attributes.getValue("method"); + if (elem.methodName != null) { + return; + } + + elem.methodName = attributes.getValue("property"); + if (elem.methodName != null) { + elem.fromProperty = true; + return; + } + + elem.methodName = attributes.getValue("index"); + if (elem.methodName != null) { + elem.fromIndex = true; + return; + } + + elem.methodName = attributes.getValue("field"); + if (elem.methodName != null) { + elem.fromField = true; + return; + } + + elem.methodName = attributes.getValue("owner"); + if (elem.methodName != null) { + elem.fromOwner = true; + return; + } + + elem.methodName = "new"; // default method name + } + + @SuppressWarnings("nls") + private Class classForName (String className) throws ClassNotFoundException { + if ("boolean".equals(className)) { + return Boolean.TYPE; + } else if ("byte".equals(className)) { + return Byte.TYPE; + } else if ("char".equals(className)) { + return Character.TYPE; + } else if ("double".equals(className)) { + return Double.TYPE; + } else if ("float".equals(className)) { + return Float.TYPE; + } else if ("int".equals(className)) { + return Integer.TYPE; + } else if ("long".equals(className)) { + return Long.TYPE; + } else if ("short".equals(className)) { + return Short.TYPE; + } else { + return Class.forName(className, true, defaultClassLoader == null ? Thread.currentThread().getContextClassLoader() + : defaultClassLoader); + } + } + + private void startArrayElem (Attributes attributes) { + Elem elem = new Elem(); + elem.isExpression = true; + elem.id = attributes.getValue("id"); //$NON-NLS-1$ + try { + // find component class + Class compClass = classForName(attributes.getValue("class")); //$NON-NLS-1$ + String lengthValue = attributes.getValue("length"); //$NON-NLS-1$ + if (lengthValue != null) { + // find length + int length = Integer.parseInt(attributes.getValue("length")); //$NON-NLS-1$ + // execute, new array instance + elem.result = Array.newInstance(compClass, length); + elem.isExecuted = true; + } else { + // create array without length attribute, + // delay the excution to the end, + // get array length from sub element + elem.target = compClass; + elem.methodName = "newArray"; //$NON-NLS-1$ + elem.isExecuted = false; + } + } catch (Exception e) { + listener.exceptionThrown(e); + } + readObjs.push(elem); + } + + @SuppressWarnings("nls") + private void startVoidElem (Attributes attributes) { + Elem elem = new Elem(); + elem.id = attributes.getValue("id"); + obtainTarget(elem, attributes); + obtainMethod(elem, attributes); + readObjs.push(elem); + } + + @SuppressWarnings("nls") + private void startBasicElem (String tagName, Attributes attributes) { + Elem elem = new Elem(); + elem.isBasicType = true; + elem.isExpression = true; + elem.id = attributes.getValue("id"); + elem.idref = attributes.getValue("idref"); + elem.target = tagName; + readObjs.push(elem); + } + + @Override + public void endElement (String uri, String localName, String qName) throws SAXException { + if (!inJavaElem) { + return; + } + if ("java".equals(qName)) { //$NON-NLS-1$ + inJavaElem = false; + return; + } + // find the elem to close + Elem toClose = latestUnclosedElem(); + // make sure it is executed + execute(toClose); + // set to closed + toClose.isClosed = true; + // pop it and its children + while (readObjs.pop() != toClose) { + // + } + + if (toClose.isExpression) { + // push back expression + readObjs.push(toClose); + } + } + + private Elem latestUnclosedElem () { + for (int i = readObjs.size() - 1; i >= 0; i--) { + Elem elem = readObjs.get(i); + if (!elem.isClosed) { + return elem; + } + } + return null; + } + + private Object execute (Elem elem) { + if (elem.isExecuted) { + return elem.result; + } + + // execute to obtain result + try { + if (elem.idref != null) { + elem.result = idObjMap.get(elem.idref); + } else if (elem.isBasicType) { + elem.result = executeBasic(elem); + } else { + elem.result = executeCommon(elem); + } + } catch (Exception e) { + listener.exceptionThrown(e); + } + + // track id + if (elem.id != null) { + idObjMap.put(elem.id, elem.result); + } + + elem.isExecuted = true; + return elem.result; + } + + @SuppressWarnings("nls") + private Object executeCommon (Elem elem) throws Exception { + // pop args + ArrayList args = new ArrayList(5); + while (readObjs.peek() != elem) { + Elem argElem = readObjs.pop(); + args.add(0, argElem.result); + } + // decide method name + String method = elem.methodName; + if (elem.fromProperty) { + method = (args.size() == 0 ? "get" : "set") + capitalize(method); + } + if (elem.fromIndex) { + Integer index = Integer.valueOf(method); + args.add(0, index); + method = args.size() == 1 ? "get" : "set"; + } + if (elem.fromField) { + Field f = ((Class)elem.target).getField(method); + return (new Expression(f, "get", new Object[] {null})).getValue(); + } + if (elem.fromOwner) { + return owner; + } + + if (elem.target == owner) { + if ("getOwner".equals(method)) { + return owner; + } + Class[] c = new Class[args.size()]; + for (int i = 0; i < args.size(); i++) { + Object arg = args.get(i); + c[i] = (arg == null ? null : arg.getClass()); + } + + // Try actual match method + try { + Method m = owner.getClass().getMethod(method, c); + return m.invoke(owner, args.toArray()); + } catch (NoSuchMethodException e) { + // Do nothing + } + + // Find the specific method matching the parameter + Method mostSpecificMethod = findMethod(owner instanceof Class ? (Class)owner : owner.getClass(), method, c); + + return mostSpecificMethod.invoke(owner, args.toArray()); + } + + // execute + Expression exp = new Expression(elem.target, method, args.toArray()); + return exp.getValue(); + } + + private Method findMethod (Class clazz, String methodName, Class[] clazzes) throws Exception { + Method[] methods = clazz.getMethods(); + ArrayList matchMethods = new ArrayList(); + + // Add all matching methods into a ArrayList + for (Method method : methods) { + if (!methodName.equals(method.getName())) { + continue; + } + Class[] parameterTypes = method.getParameterTypes(); + if (parameterTypes.length != clazzes.length) { + continue; + } + boolean match = true; + for (int i = 0; i < parameterTypes.length; i++) { + boolean isNull = (clazzes[i] == null); + boolean isPrimitive = isPrimitiveWrapper(clazzes[i], parameterTypes[i]); + boolean isAssignable = isNull ? false : parameterTypes[i].isAssignableFrom(clazzes[i]); + if (isNull || isPrimitive || isAssignable) { + continue; + } + match = false; + } + if (match) { + matchMethods.add(method); + } + } + + int size = matchMethods.size(); + if (size == 1) { + // Only one method matches, just invoke it + return matchMethods.get(0); + } else if (size == 0) { + // Does not find any matching one, throw exception + throw new NoSuchMethodException(Messages.getString("beans.41", methodName)); //$NON-NLS-1$ + } + + // There are more than one method matching the signature + // Find the most specific one to invoke + MethodComparator comparator = new MethodComparator(methodName, clazzes); + Method chosenOne = matchMethods.get(0); + matchMethods.remove(0); + int methodCounter = 1; + for (Method method : matchMethods) { + int difference = comparator.compare(chosenOne, method); + if (difference > 0) { + chosenOne = method; + methodCounter = 1; + } else if (difference == 0) { + methodCounter++; + } + } + if (methodCounter > 1) { + // if 2 methods have same relevance, throw exception + throw new NoSuchMethodException(Messages.getString("beans.62", methodName)); //$NON-NLS-1$ + } + return chosenOne; + } + + private boolean isPrimitiveWrapper (Class wrapper, Class base) { + return (base == boolean.class) && (wrapper == Boolean.class) || (base == byte.class) && (wrapper == Byte.class) + || (base == char.class) && (wrapper == Character.class) || (base == short.class) && (wrapper == Short.class) + || (base == int.class) && (wrapper == Integer.class) || (base == long.class) && (wrapper == Long.class) + || (base == float.class) && (wrapper == Float.class) || (base == double.class) && (wrapper == Double.class); + } + + private String capitalize (String str) { + StringBuilder buf = new StringBuilder(str); + buf.setCharAt(0, Character.toUpperCase(buf.charAt(0))); + return buf.toString(); + } + + @SuppressWarnings("nls") + private Object executeBasic (Elem elem) throws Exception { + String tag = (String)elem.target; + String value = elem.methodName; + + if ("null".equals(tag)) { + return null; + } else if ("string".equals(tag)) { + return value == null ? "" : value; + } else if ("class".equals(tag)) { + return classForName(value); + } else if ("boolean".equals(tag)) { + return Boolean.valueOf(value); + } else if ("byte".equals(tag)) { + return Byte.valueOf(value); + } else if ("char".equals(tag)) { + return Character.valueOf(value.charAt(0)); + } else if ("double".equals(tag)) { + return Double.valueOf(value); + } else if ("float".equals(tag)) { + return Float.valueOf(value); + } else if ("int".equals(tag)) { + return Integer.valueOf(value); + } else if ("long".equals(tag)) { + return Long.valueOf(value); + } else if ("short".equals(tag)) { + return Short.valueOf(value); + } else { + throw new Exception(Messages.getString("beans.71", tag)); + } + } + + @Override + public void error (SAXParseException e) throws SAXException { + listener.exceptionThrown(e); + } + + @Override + public void fatalError (SAXParseException e) throws SAXException { + listener.exceptionThrown(e); + } + + @Override + public void warning (SAXParseException e) throws SAXException { + listener.exceptionThrown(e); + } + } + + private static class Elem { + String id; + + String idref; + + boolean isExecuted; + + boolean isExpression; + + boolean isBasicType; + + boolean isClosed; + + Object target; + + String methodName; + + boolean fromProperty; + + boolean fromIndex; + + boolean fromField; + + boolean fromOwner; + + Object result; + + } + + private InputStream inputStream; + + private ExceptionListener listener; + + private Object owner; + + private Stack readObjs = new Stack(); + + private int readObjIndex = 0; + + private SAXHandler saxHandler = null; + + /** Create a decoder to read from specified input stream. + * + * @param inputStream an input stream of xml */ + public XMLDecoder (InputStream inputStream) { + this(inputStream, null, null, null); + } + + /** Create a decoder to read from specified input stream. + * + * @param inputStream an input stream of xml + * @param owner the owner of this decoder */ + public XMLDecoder (InputStream inputStream, Object owner) { + this(inputStream, owner, null, null); + } + + /** Create a decoder to read from specified input stream. + * + * @param inputStream an input stream of xml + * @param owner the owner of this decoder + * @param listener listen to the exceptions thrown by the decoder */ + public XMLDecoder (InputStream inputStream, Object owner, ExceptionListener listener) { + this(inputStream, owner, listener, null); + } + + public XMLDecoder (InputStream inputStream, Object owner, ExceptionListener listener, ClassLoader cl) { + this.inputStream = inputStream; + this.owner = owner; + this.listener = (listener == null) ? new DefaultExceptionListener() : listener; + defaultClassLoader = cl; + } + + /** Close the input stream of xml data. */ + public void close () { + if (inputStream == null) { + return; + } + try { + inputStream.close(); + } catch (Exception e) { + listener.exceptionThrown(e); + } + } + + /** Returns the exception listener. + * + * @return the exception listener */ + public ExceptionListener getExceptionListener () { + return listener; + } + + /** Returns the owner of this decoder. + * + * @return the owner of this decoder */ + public Object getOwner () { + return owner; + } + + /** Reads the next object. + * + * @return the next object + * @exception ArrayIndexOutOfBoundsException if no more objects to read */ + @SuppressWarnings("nls") + public Object readObject () { + if (inputStream == null) { + return null; + } + if (saxHandler == null) { + saxHandler = new SAXHandler(); + try { + SAXParserFactory.newInstance().newSAXParser().parse(inputStream, saxHandler); + } catch (Exception e) { + this.listener.exceptionThrown(e); + } + } + + if (readObjIndex >= readObjs.size()) { + throw new ArrayIndexOutOfBoundsException(Messages.getString("beans.70")); + } + Elem elem = readObjs.get(readObjIndex); + if (!elem.isClosed) { + // bad element, error occurred while parsing + throw new ArrayIndexOutOfBoundsException(Messages.getString("beans.70")); + } + readObjIndex++; + return elem.result; + } + + /** Sets the exception listener. + * + * @param listener an exception listener */ + public void setExceptionListener (ExceptionListener listener) { + if (listener != null) { + this.listener = listener; + } + } + + /** Sets the owner of this decoder. + * + * @param owner the owner of this decoder */ + public void setOwner (Object owner) { + this.owner = owner; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/XMLEncoder.java b/extensions/beans/src/com/badlogic/gdx/beans/XMLEncoder.java index 36211743eba..7a96ce22584 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/XMLEncoder.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/XMLEncoder.java @@ -17,10 +17,6 @@ package com.badlogic.gdx.beans; -import com.badlogic.gdx.beans.Encoder; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.Statement; - import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; @@ -38,911 +34,846 @@ import org.apache.harmony.beans.BeansUtils; import org.apache.harmony.beans.internal.nls.Messages; -/** - * XMLEncoder extends Encoder to write out the encoded - * statements and expressions in XML format. The XML can be read by - * XMLDecoder later to restore objects and their states. +/** XMLEncoder extends Encoder to write out the encoded statements and expressions in XML format. The XML + * can be read by XMLDecoder later to restore objects and their states. *

        * The API is similar to ObjectOutputStream. - *

        - * - */ + *

        */ public class XMLEncoder extends Encoder { - private static final String DEFAULT_ENCODING = "UTF-8"; //$NON-NLS-1$ - - private static int DEADLOCK_THRESHOLD = 7; - - /* - * Every object written by the encoder has a record. - */ - private static class Record { - // The expression by which the object is created or obtained. - Expression exp = null; - - // Id of the object, if it is referenced more than once. - String id = null; - - // Count of the references of the object. - int refCount = 0; - - // A list of statements that execute on the object. - ArrayList stats = new ArrayList(); - } - - private static final int INDENT_UNIT = 1; - - private static final boolean isStaticConstantsSupported = true; - - // the main record of all root objects - private ArrayList flushPending = new ArrayList(); - - // the record of root objects with a void tag - private ArrayList flushPendingStat = new ArrayList(); - - // keep the pre-required objects for each root object - private ArrayList flushPrePending = new ArrayList(); - - private boolean hasXmlHeader = false; - - /* - * if any expression or statement references owner, it is set true in method - * recordStatement() or recordExpressions(), and, at the first time - * flushObject() meets an owner object, it calls the flushOwner() method and - * then set needOwner to false, so that all succeeding flushing of owner - * will call flushExpression() or flushStatement() normally, which will get - * a reference of the owner property. - */ - private boolean needOwner = false; - - private PrintWriter out; - - private Object owner = null; - - private IdentityHashMap objRecordMap = new IdentityHashMap(); - - private IdentityHashMap, Integer> clazzCounterMap = new IdentityHashMap, Integer>(); - - private IdentityHashMap> objPrePendingCache = new IdentityHashMap>(); - - private boolean writingObject = false; - - /** - * Construct a XMLEncoder. - * - * @param out - * the output stream where XML is written to - */ - public XMLEncoder(OutputStream out) { - if (null != out) { - try { - this.out = new PrintWriter(new OutputStreamWriter(out, - DEFAULT_ENCODING), true); - } catch (UnsupportedEncodingException e) { - // should never occur - } - } - } - - /** - * Call flush() first, then write out XML footer and close the - * underlying output stream. - */ - public void close() { - flush(); - out.println(""); //$NON-NLS-1$ - out.close(); - } - - private StringBuffer decapitalize(String s) { - StringBuffer buf = new StringBuffer(s); - buf.setCharAt(0, Character.toLowerCase(buf.charAt(0))); - return buf; - } - - private String idSerialNoOfObject(Object obj) { - Class clazz = obj.getClass(); - Integer serialNo = (Integer) clazzCounterMap.get(clazz); - serialNo = serialNo == null ? 0 : serialNo; - String id = BeansUtils.idOfClass(obj.getClass()) + serialNo; - clazzCounterMap.put(clazz, ++serialNo); - return id; - } - - /** - * Writes out all objects since last flush to the output stream. - *

        - * The implementation write the XML header first if it has not been written. - * Then all pending objects since last flush are written. - *

        - */ - @SuppressWarnings("nls") - public void flush() { - synchronized (this) { - // write xml header - if (!hasXmlHeader) { - out.println(""); - out.println(""); - hasXmlHeader = true; - } - - // preprocess pending objects - for (Iterator iter = flushPending.iterator(); iter - .hasNext();) { - Object o = iter.next(); - Record rec = objRecordMap.get(o); - if (rec != null) { - preprocess(o, rec); - } - } - - // flush pending objects - for (Iterator iter = flushPending.iterator(); iter - .hasNext();) { - Object o = iter.next(); - flushObject(o, INDENT_UNIT); - // remove flushed obj - iter.remove(); - } - - // clear statement records - objRecordMap.clear(); - flushPendingStat.clear(); - objPrePendingCache.clear(); - clazzCounterMap.clear(); - - // remove all old->new mappings - super.clear(); - } - } - - @SuppressWarnings("nls") - private void flushBasicObject(Object obj, int indent) { - if (obj instanceof Proxy) { - return; - } - flushIndent(indent); - if (obj == null) { - out.println(""); - } else if (obj instanceof String) { - Record rec = objRecordMap.get(obj); - if (null != rec) { - flushExpression(obj, rec, indent - 3, - flushPendingStat.contains(obj)); - return; - } - out.print(""); - flushString((String) obj); - out.println(""); - } else if (obj instanceof Class) { - out.println("" + ((Class) obj).getName() + ""); - } else if (obj instanceof Boolean) { - out.println("" + obj + ""); - } else if (obj instanceof Byte) { - out.println("" + obj + ""); - } else if (obj instanceof Character) { - out.println("" + obj + ""); - } else if (obj instanceof Double) { - out.println("" + obj + ""); - } else if (obj instanceof Float) { - out.println("" + obj + ""); - } else if (obj instanceof Integer) { - out.println("" + obj + ""); - } else if (obj instanceof Long) { - out.println("" + obj + ""); - } else if (obj instanceof Short) { - out.println("" + obj + ""); - } else { - getExceptionListener().exceptionThrown( - new Exception(Messages.getString("beans.73", obj))); - } - } - - @SuppressWarnings("nls") - private void flushExpression(Object obj, Record rec, int indent, - boolean asStatement) { - // flush - Statement stat = asStatement ? new Statement(rec.exp.getTarget(), - rec.exp.getMethodName(), rec.exp.getArguments()) : rec.exp; - if (isStaticConstantsSupported - && "getField".equals(stat.getMethodName())) { - flushStatField(stat, indent); - return; - } - - // not first time, use idref - if (rec.id != null) { - flushIndent(indent); - out.print(""); - return; - } - - // generate id, if necessary - if (rec.refCount > 1 && rec.id == null) { - rec.id = idSerialNoOfObject(obj); - } - - // flush - flushStatement(stat, rec.id, rec.stats, indent); - } - - private void flushIndent(int indent) { - for (int i = 0; i < indent; i++) { - out.print(' '); - } - } - - private void flushObject(Object obj, int indent) { - Record rec = objRecordMap.get(obj); - if (rec == null && !isBasicType(obj)) { - return; - } - - if (obj == owner && this.needOwner) { - flushOwner(obj, rec, indent); - this.needOwner = false; - return; - } - - if (isBasicType(obj)) { - flushBasicObject(obj, indent); - } else { - flushExpression(obj, rec, indent, flushPendingStat.contains(obj)); - } - } - - @SuppressWarnings("nls") - private void flushOwner(Object obj, Record rec, int indent) { - if (rec.refCount > 1 && rec.id == null) { - rec.id = idSerialNoOfObject(obj); - } - - flushIndent(indent); - String tagName = "void"; - out.print("<"); - out.print(tagName); - - // id attribute - if (rec.id != null) { - out.print(" id=\""); - out.print(rec.id); - out.print("\""); - } - - out.print(" property=\"owner\""); - - // open tag, end - if (rec.exp.getArguments().length == 0 && rec.stats.isEmpty()) { - out.println("/>"); - return; - } - out.println(">"); - - // arguments - for (int i = 0; i < rec.exp.getArguments().length; i++) { - flushObject(rec.exp.getArguments()[i], indent + INDENT_UNIT); - } - - // sub statements - flushSubStatements(rec.stats, indent); - - // close tag - flushIndent(indent); - out.print(""); - } - - @SuppressWarnings("nls") - private void flushStatArray(Statement stat, String id, List subStats, - int indent) { - // open tag, begin - flushIndent(indent); - out.print(") stat.getArguments()[0]).getName()); - out.print("\" length=\""); - out.print(stat.getArguments()[1]); - out.print("\""); - - // open tag, end - if (subStats.isEmpty()) { - out.println("/>"); - return; - } - out.println(">"); - - // sub statements - flushSubStatements(subStats, indent); - - // close tag - flushIndent(indent); - out.println(""); - } - - @SuppressWarnings("nls") - private void flushStatCommon(Statement stat, String id, List subStats, - int indent) { - // open tag, begin - flushIndent(indent); - String tagName = stat instanceof Expression ? "object" : "void"; - out.print("<"); - out.print(tagName); - - // id attribute - if (id != null) { - out.print(" id=\""); - out.print(id); - out.print("\""); - } - - // special class attribute - if (stat.getTarget() instanceof Class) { - out.print(" class=\""); - out.print(((Class) stat.getTarget()).getName()); - out.print("\""); - } - - // method attribute - if (!"new".equals(stat.getMethodName())) { - out.print(" method=\""); - out.print(stat.getMethodName()); - out.print("\""); - } - - // open tag, end - if (stat.getArguments().length == 0 && subStats.isEmpty()) { - out.println("/>"); - return; - } - out.println(">"); - - // arguments - for (int i = 0; i < stat.getArguments().length; i++) { - flushObject(stat.getArguments()[i], indent + INDENT_UNIT); - } - - // sub statements - flushSubStatements(subStats, indent); - - // close tag - flushIndent(indent); - out.print(""); - } - - @SuppressWarnings("nls") - private void flushStatement(Statement stat, String id, List subStats, - int indent) { - Object target = stat.getTarget(); - String method = stat.getMethodName(); - Object args[] = stat.getArguments(); - - // special case for array - if (Array.class == target && BeansUtils.NEWINSTANCE.equals(method)) { - flushStatArray(stat, id, subStats, indent); - return; - } - // special case for get(int) and set(int, Object) - if (isGetArrayStat(target, method, args) - || isSetArrayStat(target, method, args)) { - flushStatIndexed(stat, id, subStats, indent); - return; - } - // special case for getProperty() and setProperty(Object) - if (isGetPropertyStat(method, args) || isSetPropertyStat(method, args)) { - flushStatGetterSetter(stat, id, subStats, indent); - return; - } - - if (isStaticConstantsSupported - && "getField".equals(stat.getMethodName())) { - flushStatField(stat, indent); - return; - } - - // common case - flushStatCommon(stat, id, subStats, indent); - } - - @SuppressWarnings("nls") - private void flushStatField(Statement stat, int indent) { - // open tag, begin - flushIndent(indent); - out.print(") { - out.print(" class=\""); - out.print(((Class) target).getName()); - out.print("\""); - } - - Field field = null; - if (target instanceof Class && stat.getArguments().length == 1 - && stat.getArguments()[0] instanceof String) { - try { - field = ((Class) target).getField((String) stat - .getArguments()[0]); - } catch (Exception e) { - // ignored - } - } - - if (field != null && Modifier.isStatic(field.getModifiers())) { - out.print(" field=\""); - out.print(stat.getArguments()[0]); - out.print("\""); - out.println("/>"); - } else { - out.print(" method=\""); - out.print(stat.getMethodName()); - out.print("\""); - out.println(">"); - flushObject(stat.getArguments()[0], indent + INDENT_UNIT); - flushIndent(indent); - out.println(""); - } - } - - @SuppressWarnings("nls") - private void flushStatGetterSetter(Statement stat, String id, - List subStats, int indent) { - // open tag, begin - flushIndent(indent); - String tagName = stat instanceof Expression ? "object" : "void"; - out.print("<"); - out.print(tagName); - - // id attribute - if (id != null) { - out.print(" id=\""); - out.print(id); - out.print("\""); - } - - // special class attribute - if (stat.getTarget() instanceof Class) { - out.print(" class=\""); - out.print(((Class) stat.getTarget()).getName()); - out.print("\""); - } - - // property attribute - out.print(" property=\""); - out.print(decapitalize(stat.getMethodName().substring(3))); - out.print("\""); - - // open tag, end - if (stat.getArguments().length == 0 && subStats.isEmpty()) { - out.println("/>"); - return; - } - out.println(">"); - - // arguments - for (int i = 0; i < stat.getArguments().length; i++) { - flushObject(stat.getArguments()[i], indent + INDENT_UNIT); - } - - // sub statements - flushSubStatements(subStats, indent); - - // close tag - flushIndent(indent); - out.print(""); - } - - @SuppressWarnings("nls") - private void flushStatIndexed(Statement stat, String id, List subStats, - int indent) { - // open tag, begin - flushIndent(indent); - String tagName = stat instanceof Expression ? "object" : "void"; - out.print("<"); - out.print(tagName); - - // id attribute - if (id != null) { - out.print(" id=\""); - out.print(id); - out.print("\""); - } - - // special class attribute - if (stat.getTarget() instanceof Class) { - out.print(" class=\""); - out.print(((Class) stat.getTarget()).getName()); - out.print("\""); - } - - // index attribute - out.print(" index=\""); - out.print(stat.getArguments()[0]); - out.print("\""); - - // open tag, end - if (stat.getArguments().length == 1 && subStats.isEmpty()) { - out.println("/>"); - return; - } - out.println(">"); - - // arguments - for (int i = 1; i < stat.getArguments().length; i++) { - flushObject(stat.getArguments()[i], indent + INDENT_UNIT); - } - - // sub statements - flushSubStatements(subStats, indent); - - // close tag - flushIndent(indent); - out.print(""); - } - - @SuppressWarnings("nls") - private void flushString(String s) { - char c; - for (int i = 0; i < s.length(); i++) { - c = s.charAt(i); - if (c == '<') { - out.print("<"); - } else if (c == '>') { - out.print(">"); - } else if (c == '&') { - out.print("&"); - } else if (c == '\'') { - out.print("'"); - } else if (c == '"') { - out.print("""); - } else { - out.print(c); - } - } - } - - private void flushSubStatements(List subStats, int indent) { - for (int i = 0; i < subStats.size(); i++) { - Statement subStat = (Statement) subStats.get(i); - try { - if (subStat.getClass() == Expression.class) { - Expression subExp = (Expression) subStat; - Object obj = subExp.getValue(); - Record rec = objRecordMap.get(obj); - flushExpression(obj, rec, indent + INDENT_UNIT, true); - } else { - flushStatement(subStat, null, Collections.EMPTY_LIST, - indent + INDENT_UNIT); - } - } catch (Exception e) { - // should not happen - getExceptionListener().exceptionThrown(e); - } - } - } - - /** - * Returns the owner of this encoder. - * - * @return the owner of this encoder - */ - public Object getOwner() { - return owner; - } - - private boolean isBasicType(Object value) { - return value == null || value instanceof Boolean - || value instanceof Byte || value instanceof Character - || value instanceof Class || value instanceof Double - || value instanceof Float || value instanceof Integer - || value instanceof Long || value instanceof Short - || value instanceof String || value instanceof Proxy; - } - - private boolean isGetArrayStat(Object target, String method, Object[] args) { - return (BeansUtils.GET.equals(method) && args.length == 1 - && args[0] instanceof Integer && target.getClass().isArray()); - } - - private boolean isGetPropertyStat(String method, Object[] args) { - return (method.startsWith(BeansUtils.GET) && method.length() > 3 && args.length == 0); - } - - private boolean isSetArrayStat(Object target, String method, Object[] args) { - return (BeansUtils.SET.equals(method) && args.length == 2 - && args[0] instanceof Integer && target.getClass().isArray()); - } - - private boolean isSetPropertyStat(String method, Object[] args) { - return (method.startsWith(BeansUtils.SET) && method.length() > 3 && args.length == 1); - } - - /* - * The preprocess removes unused statements and counts references of every - * object - */ - private void preprocess(Object obj, Record rec) { - if (writingObject && isBasicType(obj)) { - return; - } - - if (obj instanceof Class) { - return; - } - - // count reference - rec.refCount++; - - // do things only one time for each record - if (rec.refCount > 1) { - return; - } - - // do it recursively - if (null != rec.exp) { - // deal with 'field' property - Record targetRec = objRecordMap.get(rec.exp.getTarget()); - if (targetRec != null && targetRec.exp != null - && "getField".equals(targetRec.exp.getMethodName())) { - objRecordMap.remove(obj); - } - - Object args[] = rec.exp.getArguments(); - for (int i = 0; i < args.length; i++) { - Record argRec = objRecordMap.get(args[i]); - if (argRec != null) { - preprocess(args[i], argRec); - } - } - } - - for (Iterator iter = rec.stats.iterator(); iter.hasNext();) { - Statement subStat = (Statement) iter.next(); - if (subStat.getClass() == Expression.class) { - try { - Expression subExp = (Expression) subStat; - Record subRec = objRecordMap.get(subExp.getValue()); - if (subRec == null || subRec.exp == null - || subRec.exp != subExp) { - iter.remove(); - continue; - } - preprocess(subExp.getValue(), subRec); - if (subRec.stats.isEmpty()) { - if (isGetArrayStat(subExp.getTarget(), - subExp.getMethodName(), subExp.getArguments()) - || isGetPropertyStat(subExp.getMethodName(), - subExp.getArguments())) { - iter.remove(); - continue; - } - } - } catch (Exception e) { - getExceptionListener().exceptionThrown(e); - iter.remove(); - } - continue; - } - - Object subStatArgs[] = subStat.getArguments(); - for (int i = 0; i < subStatArgs.length; i++) { - Record argRec = objRecordMap.get(subStatArgs[i]); - if (argRec != null) { - preprocess(subStatArgs[i], argRec); - } - } - } - } - - private void recordExpression(Object value, Expression exp) { - // record how a new object is created or obtained - Record rec = objRecordMap.get(value); - if (rec == null) { - rec = new Record(); - objRecordMap.put(value, rec); - } - - if (rec.exp == null) { - // it is generated by its sub statements - for (Statement statement : rec.stats) { - if (statement.getClass() == Expression.class) { - flushPrePending.add(value); - } - } - } - - rec.exp = exp; - - // deal with 'owner' property - if (value == owner && owner != null) { - needOwner = true; - } - - // also record as a statement - recordStatement(exp); - } - - private void recordStatement(Statement stat) { - if (null == stat) { - return; - } - // deal with 'owner' property - if (stat.getTarget() == owner && owner != null) { - needOwner = true; - } - - // record how a statement affects the target object - Record rec = objRecordMap.get(stat.getTarget()); - if (rec == null) { - rec = new Record(); - objRecordMap.put(stat.getTarget(), rec); - } - rec.stats.add(stat); - } - - /** - * Imperfect attempt to detect a dead loop. This works with specific - * patterns that can be found in our AWT implementation. See HARMONY-5707 - * for details. - * - * @param value - * the object to check dupes for - * @return true if a dead loop detected; false otherwise FIXME - */ - private boolean checkDeadLoop(Object value) { - int n = 0; - Object obj = value; - - while (obj != null) { - Record rec = objRecordMap.get(obj); - - if (rec != null && rec.exp != null) { - obj = rec.exp.getTarget(); - } else { - break; - } - - if (obj != null - && (obj.getClass().isAssignableFrom(value.getClass())) - && obj.equals(value)) { - n++; - - if (n >= DEADLOCK_THRESHOLD) { - // System.out.println("Dead loop hit!"); - return true; - } - } - } - return false; - } - - /** - * Sets the owner of this encoder. - * - * @param owner - * the owner to set - */ - public void setOwner(Object owner) { - this.owner = owner; - } - - /** - * Records the expression so that it can be written out later, then calls - * super implementation. - */ - @Override - public void writeExpression(Expression oldExp) { - if (null == oldExp) { - throw new NullPointerException(); - } - boolean oldWritingObject = writingObject; - writingObject = true; - // get expression value - Object oldValue = expressionValue(oldExp); - // check existence - if (oldValue == null || get(oldValue) != null - && (oldWritingObject || oldValue.getClass() != String.class)) { - return; - } - - // record how the object is obtained - if (!isBasicType(oldValue) - || (!oldWritingObject && oldValue.getClass() == String.class)) { - recordExpression(oldValue, oldExp); - } - - // try to detect if we run into a dead loop - if (checkDeadLoop(oldValue)) { - return; - } - super.writeExpression(oldExp); - writingObject = oldWritingObject; - } - - /** - * Records the object so that it can be written out later, then calls super - * implementation. - */ - @Override - public void writeObject(Object o) { - synchronized (this) { - ArrayList prePending = objPrePendingCache.get(o); - if (prePending == null) { - boolean oldWritingObject = writingObject; - writingObject = true; - try { - super.writeObject(o); - } finally { - writingObject = oldWritingObject; - } - } else { - flushPrePending.clear(); - flushPrePending.addAll(prePending); - } - - // root object - if (!writingObject) { - boolean isNotCached = prePending == null; - // is not cached, add to cache - if (isNotCached && o != null) { - prePending = new ArrayList(); - prePending.addAll(flushPrePending); - objPrePendingCache.put(o, prePending); - } - - // add to pending - flushPending.addAll(flushPrePending); - flushPendingStat.addAll(flushPrePending); - flushPrePending.clear(); - - if (isNotCached && flushPending.contains(o)) { - flushPendingStat.remove(o); - } else { - flushPending.add(o); - } - if (needOwner) { - this.flushPending.remove(owner); - this.flushPending.add(0, owner); - } - } - } - } - - /** - * Records the statement so that it can be written out later, then calls - * super implementation. - */ - @Override - public void writeStatement(Statement oldStat) { - if (null == oldStat) { - System.err - .println("java.lang.Exception: XMLEncoder: discarding statement null"); - System.err.println("Continuing..."); - return; - } - - // record how the object is changed - recordStatement(oldStat); - super.writeStatement(oldStat); - } -} \ No newline at end of file + private static final String DEFAULT_ENCODING = "UTF-8"; //$NON-NLS-1$ + + private static int DEADLOCK_THRESHOLD = 7; + + /* + * Every object written by the encoder has a record. + */ + private static class Record { + // The expression by which the object is created or obtained. + Expression exp = null; + + // Id of the object, if it is referenced more than once. + String id = null; + + // Count of the references of the object. + int refCount = 0; + + // A list of statements that execute on the object. + ArrayList stats = new ArrayList(); + } + + private static final int INDENT_UNIT = 1; + + private static final boolean isStaticConstantsSupported = true; + + // the main record of all root objects + private ArrayList flushPending = new ArrayList(); + + // the record of root objects with a void tag + private ArrayList flushPendingStat = new ArrayList(); + + // keep the pre-required objects for each root object + private ArrayList flushPrePending = new ArrayList(); + + private boolean hasXmlHeader = false; + + /* + * if any expression or statement references owner, it is set true in method recordStatement() or recordExpressions(), and, at + * the first time flushObject() meets an owner object, it calls the flushOwner() method and then set needOwner to false, so + * that all succeeding flushing of owner will call flushExpression() or flushStatement() normally, which will get a reference + * of the owner property. + */ + private boolean needOwner = false; + + private PrintWriter out; + + private Object owner = null; + + private IdentityHashMap objRecordMap = new IdentityHashMap(); + + private IdentityHashMap, Integer> clazzCounterMap = new IdentityHashMap, Integer>(); + + private IdentityHashMap> objPrePendingCache = new IdentityHashMap>(); + + private boolean writingObject = false; + + /** Construct a XMLEncoder. + * + * @param out the output stream where XML is written to */ + public XMLEncoder (OutputStream out) { + if (null != out) { + try { + this.out = new PrintWriter(new OutputStreamWriter(out, DEFAULT_ENCODING), true); + } catch (UnsupportedEncodingException e) { + // should never occur + } + } + } + + /** Call flush() first, then write out XML footer and close the underlying output stream. */ + public void close () { + flush(); + out.println(""); //$NON-NLS-1$ + out.close(); + } + + private StringBuffer decapitalize (String s) { + StringBuffer buf = new StringBuffer(s); + buf.setCharAt(0, Character.toLowerCase(buf.charAt(0))); + return buf; + } + + private String idSerialNoOfObject (Object obj) { + Class clazz = obj.getClass(); + Integer serialNo = (Integer)clazzCounterMap.get(clazz); + serialNo = serialNo == null ? 0 : serialNo; + String id = BeansUtils.idOfClass(obj.getClass()) + serialNo; + clazzCounterMap.put(clazz, ++serialNo); + return id; + } + + /** Writes out all objects since last flush to the output stream. + *

        + * The implementation write the XML header first if it has not been written. Then all pending objects since last flush are + * written. + *

        */ + @SuppressWarnings("nls") + public void flush () { + synchronized (this) { + // write xml header + if (!hasXmlHeader) { + out.println(""); + out.println(""); + hasXmlHeader = true; + } + + // preprocess pending objects + for (Iterator iter = flushPending.iterator(); iter.hasNext();) { + Object o = iter.next(); + Record rec = objRecordMap.get(o); + if (rec != null) { + preprocess(o, rec); + } + } + + // flush pending objects + for (Iterator iter = flushPending.iterator(); iter.hasNext();) { + Object o = iter.next(); + flushObject(o, INDENT_UNIT); + // remove flushed obj + iter.remove(); + } + + // clear statement records + objRecordMap.clear(); + flushPendingStat.clear(); + objPrePendingCache.clear(); + clazzCounterMap.clear(); + + // remove all old->new mappings + super.clear(); + } + } + + @SuppressWarnings("nls") + private void flushBasicObject (Object obj, int indent) { + if (obj instanceof Proxy) { + return; + } + flushIndent(indent); + if (obj == null) { + out.println(""); + } else if (obj instanceof String) { + Record rec = objRecordMap.get(obj); + if (null != rec) { + flushExpression(obj, rec, indent - 3, flushPendingStat.contains(obj)); + return; + } + out.print(""); + flushString((String)obj); + out.println(""); + } else if (obj instanceof Class) { + out.println("" + ((Class)obj).getName() + ""); + } else if (obj instanceof Boolean) { + out.println("" + obj + ""); + } else if (obj instanceof Byte) { + out.println("" + obj + ""); + } else if (obj instanceof Character) { + out.println("" + obj + ""); + } else if (obj instanceof Double) { + out.println("" + obj + ""); + } else if (obj instanceof Float) { + out.println("" + obj + ""); + } else if (obj instanceof Integer) { + out.println("" + obj + ""); + } else if (obj instanceof Long) { + out.println("" + obj + ""); + } else if (obj instanceof Short) { + out.println("" + obj + ""); + } else { + getExceptionListener().exceptionThrown(new Exception(Messages.getString("beans.73", obj))); + } + } + + @SuppressWarnings("nls") + private void flushExpression (Object obj, Record rec, int indent, boolean asStatement) { + // flush + Statement stat = asStatement ? new Statement(rec.exp.getTarget(), rec.exp.getMethodName(), rec.exp.getArguments()) + : rec.exp; + if (isStaticConstantsSupported && "getField".equals(stat.getMethodName())) { + flushStatField(stat, indent); + return; + } + + // not first time, use idref + if (rec.id != null) { + flushIndent(indent); + out.print(""); + return; + } + + // generate id, if necessary + if (rec.refCount > 1 && rec.id == null) { + rec.id = idSerialNoOfObject(obj); + } + + // flush + flushStatement(stat, rec.id, rec.stats, indent); + } + + private void flushIndent (int indent) { + for (int i = 0; i < indent; i++) { + out.print(' '); + } + } + + private void flushObject (Object obj, int indent) { + Record rec = objRecordMap.get(obj); + if (rec == null && !isBasicType(obj)) { + return; + } + + if (obj == owner && this.needOwner) { + flushOwner(obj, rec, indent); + this.needOwner = false; + return; + } + + if (isBasicType(obj)) { + flushBasicObject(obj, indent); + } else { + flushExpression(obj, rec, indent, flushPendingStat.contains(obj)); + } + } + + @SuppressWarnings("nls") + private void flushOwner (Object obj, Record rec, int indent) { + if (rec.refCount > 1 && rec.id == null) { + rec.id = idSerialNoOfObject(obj); + } + + flushIndent(indent); + String tagName = "void"; + out.print("<"); + out.print(tagName); + + // id attribute + if (rec.id != null) { + out.print(" id=\""); + out.print(rec.id); + out.print("\""); + } + + out.print(" property=\"owner\""); + + // open tag, end + if (rec.exp.getArguments().length == 0 && rec.stats.isEmpty()) { + out.println("/>"); + return; + } + out.println(">"); + + // arguments + for (int i = 0; i < rec.exp.getArguments().length; i++) { + flushObject(rec.exp.getArguments()[i], indent + INDENT_UNIT); + } + + // sub statements + flushSubStatements(rec.stats, indent); + + // close tag + flushIndent(indent); + out.print(""); + } + + @SuppressWarnings("nls") + private void flushStatArray (Statement stat, String id, List subStats, int indent) { + // open tag, begin + flushIndent(indent); + out.print(")stat.getArguments()[0]).getName()); + out.print("\" length=\""); + out.print(stat.getArguments()[1]); + out.print("\""); + + // open tag, end + if (subStats.isEmpty()) { + out.println("/>"); + return; + } + out.println(">"); + + // sub statements + flushSubStatements(subStats, indent); + + // close tag + flushIndent(indent); + out.println(""); + } + + @SuppressWarnings("nls") + private void flushStatCommon (Statement stat, String id, List subStats, int indent) { + // open tag, begin + flushIndent(indent); + String tagName = stat instanceof Expression ? "object" : "void"; + out.print("<"); + out.print(tagName); + + // id attribute + if (id != null) { + out.print(" id=\""); + out.print(id); + out.print("\""); + } + + // special class attribute + if (stat.getTarget() instanceof Class) { + out.print(" class=\""); + out.print(((Class)stat.getTarget()).getName()); + out.print("\""); + } + + // method attribute + if (!"new".equals(stat.getMethodName())) { + out.print(" method=\""); + out.print(stat.getMethodName()); + out.print("\""); + } + + // open tag, end + if (stat.getArguments().length == 0 && subStats.isEmpty()) { + out.println("/>"); + return; + } + out.println(">"); + + // arguments + for (int i = 0; i < stat.getArguments().length; i++) { + flushObject(stat.getArguments()[i], indent + INDENT_UNIT); + } + + // sub statements + flushSubStatements(subStats, indent); + + // close tag + flushIndent(indent); + out.print(""); + } + + @SuppressWarnings("nls") + private void flushStatement (Statement stat, String id, List subStats, int indent) { + Object target = stat.getTarget(); + String method = stat.getMethodName(); + Object args[] = stat.getArguments(); + + // special case for array + if (Array.class == target && BeansUtils.NEWINSTANCE.equals(method)) { + flushStatArray(stat, id, subStats, indent); + return; + } + // special case for get(int) and set(int, Object) + if (isGetArrayStat(target, method, args) || isSetArrayStat(target, method, args)) { + flushStatIndexed(stat, id, subStats, indent); + return; + } + // special case for getProperty() and setProperty(Object) + if (isGetPropertyStat(method, args) || isSetPropertyStat(method, args)) { + flushStatGetterSetter(stat, id, subStats, indent); + return; + } + + if (isStaticConstantsSupported && "getField".equals(stat.getMethodName())) { + flushStatField(stat, indent); + return; + } + + // common case + flushStatCommon(stat, id, subStats, indent); + } + + @SuppressWarnings("nls") + private void flushStatField (Statement stat, int indent) { + // open tag, begin + flushIndent(indent); + out.print(") { + out.print(" class=\""); + out.print(((Class)target).getName()); + out.print("\""); + } + + Field field = null; + if (target instanceof Class && stat.getArguments().length == 1 && stat.getArguments()[0] instanceof String) { + try { + field = ((Class)target).getField((String)stat.getArguments()[0]); + } catch (Exception e) { + // ignored + } + } + + if (field != null && Modifier.isStatic(field.getModifiers())) { + out.print(" field=\""); + out.print(stat.getArguments()[0]); + out.print("\""); + out.println("/>"); + } else { + out.print(" method=\""); + out.print(stat.getMethodName()); + out.print("\""); + out.println(">"); + flushObject(stat.getArguments()[0], indent + INDENT_UNIT); + flushIndent(indent); + out.println(""); + } + } + + @SuppressWarnings("nls") + private void flushStatGetterSetter (Statement stat, String id, List subStats, int indent) { + // open tag, begin + flushIndent(indent); + String tagName = stat instanceof Expression ? "object" : "void"; + out.print("<"); + out.print(tagName); + + // id attribute + if (id != null) { + out.print(" id=\""); + out.print(id); + out.print("\""); + } + + // special class attribute + if (stat.getTarget() instanceof Class) { + out.print(" class=\""); + out.print(((Class)stat.getTarget()).getName()); + out.print("\""); + } + + // property attribute + out.print(" property=\""); + out.print(decapitalize(stat.getMethodName().substring(3))); + out.print("\""); + + // open tag, end + if (stat.getArguments().length == 0 && subStats.isEmpty()) { + out.println("/>"); + return; + } + out.println(">"); + + // arguments + for (int i = 0; i < stat.getArguments().length; i++) { + flushObject(stat.getArguments()[i], indent + INDENT_UNIT); + } + + // sub statements + flushSubStatements(subStats, indent); + + // close tag + flushIndent(indent); + out.print(""); + } + + @SuppressWarnings("nls") + private void flushStatIndexed (Statement stat, String id, List subStats, int indent) { + // open tag, begin + flushIndent(indent); + String tagName = stat instanceof Expression ? "object" : "void"; + out.print("<"); + out.print(tagName); + + // id attribute + if (id != null) { + out.print(" id=\""); + out.print(id); + out.print("\""); + } + + // special class attribute + if (stat.getTarget() instanceof Class) { + out.print(" class=\""); + out.print(((Class)stat.getTarget()).getName()); + out.print("\""); + } + + // index attribute + out.print(" index=\""); + out.print(stat.getArguments()[0]); + out.print("\""); + + // open tag, end + if (stat.getArguments().length == 1 && subStats.isEmpty()) { + out.println("/>"); + return; + } + out.println(">"); + + // arguments + for (int i = 1; i < stat.getArguments().length; i++) { + flushObject(stat.getArguments()[i], indent + INDENT_UNIT); + } + + // sub statements + flushSubStatements(subStats, indent); + + // close tag + flushIndent(indent); + out.print(""); + } + + @SuppressWarnings("nls") + private void flushString (String s) { + char c; + for (int i = 0; i < s.length(); i++) { + c = s.charAt(i); + if (c == '<') { + out.print("<"); + } else if (c == '>') { + out.print(">"); + } else if (c == '&') { + out.print("&"); + } else if (c == '\'') { + out.print("'"); + } else if (c == '"') { + out.print("""); + } else { + out.print(c); + } + } + } + + private void flushSubStatements (List subStats, int indent) { + for (int i = 0; i < subStats.size(); i++) { + Statement subStat = (Statement)subStats.get(i); + try { + if (subStat.getClass() == Expression.class) { + Expression subExp = (Expression)subStat; + Object obj = subExp.getValue(); + Record rec = objRecordMap.get(obj); + flushExpression(obj, rec, indent + INDENT_UNIT, true); + } else { + flushStatement(subStat, null, Collections.EMPTY_LIST, indent + INDENT_UNIT); + } + } catch (Exception e) { + // should not happen + getExceptionListener().exceptionThrown(e); + } + } + } + + /** Returns the owner of this encoder. + * + * @return the owner of this encoder */ + public Object getOwner () { + return owner; + } + + private boolean isBasicType (Object value) { + return value == null || value instanceof Boolean || value instanceof Byte || value instanceof Character + || value instanceof Class || value instanceof Double || value instanceof Float || value instanceof Integer + || value instanceof Long || value instanceof Short || value instanceof String || value instanceof Proxy; + } + + private boolean isGetArrayStat (Object target, String method, Object[] args) { + return (BeansUtils.GET.equals(method) && args.length == 1 && args[0] instanceof Integer && target.getClass().isArray()); + } + + private boolean isGetPropertyStat (String method, Object[] args) { + return (method.startsWith(BeansUtils.GET) && method.length() > 3 && args.length == 0); + } + + private boolean isSetArrayStat (Object target, String method, Object[] args) { + return (BeansUtils.SET.equals(method) && args.length == 2 && args[0] instanceof Integer && target.getClass().isArray()); + } + + private boolean isSetPropertyStat (String method, Object[] args) { + return (method.startsWith(BeansUtils.SET) && method.length() > 3 && args.length == 1); + } + + /* + * The preprocess removes unused statements and counts references of every object + */ + private void preprocess (Object obj, Record rec) { + if (writingObject && isBasicType(obj)) { + return; + } + + if (obj instanceof Class) { + return; + } + + // count reference + rec.refCount++; + + // do things only one time for each record + if (rec.refCount > 1) { + return; + } + + // do it recursively + if (null != rec.exp) { + // deal with 'field' property + Record targetRec = objRecordMap.get(rec.exp.getTarget()); + if (targetRec != null && targetRec.exp != null && "getField".equals(targetRec.exp.getMethodName())) { + objRecordMap.remove(obj); + } + + Object args[] = rec.exp.getArguments(); + for (int i = 0; i < args.length; i++) { + Record argRec = objRecordMap.get(args[i]); + if (argRec != null) { + preprocess(args[i], argRec); + } + } + } + + for (Iterator iter = rec.stats.iterator(); iter.hasNext();) { + Statement subStat = (Statement)iter.next(); + if (subStat.getClass() == Expression.class) { + try { + Expression subExp = (Expression)subStat; + Record subRec = objRecordMap.get(subExp.getValue()); + if (subRec == null || subRec.exp == null || subRec.exp != subExp) { + iter.remove(); + continue; + } + preprocess(subExp.getValue(), subRec); + if (subRec.stats.isEmpty()) { + if (isGetArrayStat(subExp.getTarget(), subExp.getMethodName(), subExp.getArguments()) + || isGetPropertyStat(subExp.getMethodName(), subExp.getArguments())) { + iter.remove(); + continue; + } + } + } catch (Exception e) { + getExceptionListener().exceptionThrown(e); + iter.remove(); + } + continue; + } + + Object subStatArgs[] = subStat.getArguments(); + for (int i = 0; i < subStatArgs.length; i++) { + Record argRec = objRecordMap.get(subStatArgs[i]); + if (argRec != null) { + preprocess(subStatArgs[i], argRec); + } + } + } + } + + private void recordExpression (Object value, Expression exp) { + // record how a new object is created or obtained + Record rec = objRecordMap.get(value); + if (rec == null) { + rec = new Record(); + objRecordMap.put(value, rec); + } + + if (rec.exp == null) { + // it is generated by its sub statements + for (Statement statement : rec.stats) { + if (statement.getClass() == Expression.class) { + flushPrePending.add(value); + } + } + } + + rec.exp = exp; + + // deal with 'owner' property + if (value == owner && owner != null) { + needOwner = true; + } + + // also record as a statement + recordStatement(exp); + } + + private void recordStatement (Statement stat) { + if (null == stat) { + return; + } + // deal with 'owner' property + if (stat.getTarget() == owner && owner != null) { + needOwner = true; + } + + // record how a statement affects the target object + Record rec = objRecordMap.get(stat.getTarget()); + if (rec == null) { + rec = new Record(); + objRecordMap.put(stat.getTarget(), rec); + } + rec.stats.add(stat); + } + + /** Imperfect attempt to detect a dead loop. This works with specific patterns that can be found in our AWT implementation. See + * HARMONY-5707 for details. + * + * @param value the object to check dupes for + * @return true if a dead loop detected; false otherwise FIXME */ + private boolean checkDeadLoop (Object value) { + int n = 0; + Object obj = value; + + while (obj != null) { + Record rec = objRecordMap.get(obj); + + if (rec != null && rec.exp != null) { + obj = rec.exp.getTarget(); + } else { + break; + } + + if (obj != null && (obj.getClass().isAssignableFrom(value.getClass())) && obj.equals(value)) { + n++; + + if (n >= DEADLOCK_THRESHOLD) { + // System.out.println("Dead loop hit!"); + return true; + } + } + } + return false; + } + + /** Sets the owner of this encoder. + * + * @param owner the owner to set */ + public void setOwner (Object owner) { + this.owner = owner; + } + + /** Records the expression so that it can be written out later, then calls super implementation. */ + @Override + public void writeExpression (Expression oldExp) { + if (null == oldExp) { + throw new NullPointerException(); + } + boolean oldWritingObject = writingObject; + writingObject = true; + // get expression value + Object oldValue = expressionValue(oldExp); + // check existence + if (oldValue == null || get(oldValue) != null && (oldWritingObject || oldValue.getClass() != String.class)) { + return; + } + + // record how the object is obtained + if (!isBasicType(oldValue) || (!oldWritingObject && oldValue.getClass() == String.class)) { + recordExpression(oldValue, oldExp); + } + + // try to detect if we run into a dead loop + if (checkDeadLoop(oldValue)) { + return; + } + super.writeExpression(oldExp); + writingObject = oldWritingObject; + } + + /** Records the object so that it can be written out later, then calls super implementation. */ + @Override + public void writeObject (Object o) { + synchronized (this) { + ArrayList prePending = objPrePendingCache.get(o); + if (prePending == null) { + boolean oldWritingObject = writingObject; + writingObject = true; + try { + super.writeObject(o); + } finally { + writingObject = oldWritingObject; + } + } else { + flushPrePending.clear(); + flushPrePending.addAll(prePending); + } + + // root object + if (!writingObject) { + boolean isNotCached = prePending == null; + // is not cached, add to cache + if (isNotCached && o != null) { + prePending = new ArrayList(); + prePending.addAll(flushPrePending); + objPrePendingCache.put(o, prePending); + } + + // add to pending + flushPending.addAll(flushPrePending); + flushPendingStat.addAll(flushPrePending); + flushPrePending.clear(); + + if (isNotCached && flushPending.contains(o)) { + flushPendingStat.remove(o); + } else { + flushPending.add(o); + } + if (needOwner) { + this.flushPending.remove(owner); + this.flushPending.add(0, owner); + } + } + } + } + + /** Records the statement so that it can be written out later, then calls super implementation. */ + @Override + public void writeStatement (Statement oldStat) { + if (null == oldStat) { + System.err.println("java.lang.Exception: XMLEncoder: discarding statement null"); + System.err.println("Continuing..."); + return; + } + + // record how the object is changed + recordStatement(oldStat); + super.writeStatement(oldStat); + } +} diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContext.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContext.java index 404f734eced..afacdceecd1 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContext.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContext.java @@ -17,37 +17,27 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.DesignMode; -import com.badlogic.gdx.beans.Visibility; -import com.badlogic.gdx.beans.beancontext.BeanContextChild; -import com.badlogic.gdx.beans.beancontext.BeanContextMembershipListener; - import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Collection; +import com.badlogic.gdx.beans.DesignMode; +import com.badlogic.gdx.beans.Visibility; + @SuppressWarnings("unchecked") -public interface BeanContext extends BeanContextChild, Collection, DesignMode, - Visibility { +public interface BeanContext extends BeanContextChild, Collection, DesignMode, Visibility { - /** - * TODO: find out what it should be initialized to - */ - public static final Object globalHierarchyLock = new Object(); + /** TODO: find out what it should be initialized to */ + public static final Object globalHierarchyLock = new Object(); - public void addBeanContextMembershipListener( - BeanContextMembershipListener bcml); + public void addBeanContextMembershipListener (BeanContextMembershipListener bcml); - public URL getResource(String name, BeanContextChild bcc) - throws IllegalArgumentException; + public URL getResource (String name, BeanContextChild bcc) throws IllegalArgumentException; - public InputStream getResourceAsStream(String name, BeanContextChild bcc) - throws IllegalArgumentException; + public InputStream getResourceAsStream (String name, BeanContextChild bcc) throws IllegalArgumentException; - public Object instantiateChild(String beanName) throws IOException, - ClassNotFoundException; + public Object instantiateChild (String beanName) throws IOException, ClassNotFoundException; - public void removeBeanContextMembershipListener( - BeanContextMembershipListener bcml); + public void removeBeanContextMembershipListener (BeanContextMembershipListener bcml); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChild.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChild.java index b163cae739f..2014a5fceb1 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChild.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChild.java @@ -20,23 +20,18 @@ import com.badlogic.gdx.beans.PropertyChangeListener; import com.badlogic.gdx.beans.PropertyVetoException; import com.badlogic.gdx.beans.VetoableChangeListener; -import com.badlogic.gdx.beans.beancontext.BeanContext; public interface BeanContextChild { - public void addPropertyChangeListener(String name, - PropertyChangeListener pcl); + public void addPropertyChangeListener (String name, PropertyChangeListener pcl); - public void addVetoableChangeListener(String name, - VetoableChangeListener vcl); + public void addVetoableChangeListener (String name, VetoableChangeListener vcl); - public BeanContext getBeanContext(); + public BeanContext getBeanContext (); - public void removePropertyChangeListener(String name, - PropertyChangeListener pcl); + public void removePropertyChangeListener (String name, PropertyChangeListener pcl); - public void removeVetoableChangeListener(String name, - VetoableChangeListener vcl); + public void removeVetoableChangeListener (String name, VetoableChangeListener vcl); - public void setBeanContext(BeanContext bc) throws PropertyVetoException; + public void setBeanContext (BeanContext bc) throws PropertyVetoException; } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildComponentProxy.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildComponentProxy.java index 2fe386eda1c..c780a1ef99f 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildComponentProxy.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildComponentProxy.java @@ -21,5 +21,5 @@ public interface BeanContextChildComponentProxy { - public Component getComponent(); + public Component getComponent (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildSupport.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildSupport.java index 0d9a710b868..ba38e828165 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildSupport.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextChildSupport.java @@ -17,191 +17,171 @@ package com.badlogic.gdx.beans.beancontext; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +import org.apache.harmony.beans.internal.nls.Messages; + import com.badlogic.gdx.beans.PropertyChangeEvent; import com.badlogic.gdx.beans.PropertyChangeListener; import com.badlogic.gdx.beans.PropertyChangeSupport; import com.badlogic.gdx.beans.PropertyVetoException; import com.badlogic.gdx.beans.VetoableChangeListener; import com.badlogic.gdx.beans.VetoableChangeSupport; -import com.badlogic.gdx.beans.beancontext.BeanContext; -import com.badlogic.gdx.beans.beancontext.BeanContextChild; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceAvailableEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextServicesListener; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; +public class BeanContextChildSupport implements BeanContextChild, BeanContextServicesListener, Serializable { -import org.apache.harmony.beans.internal.nls.Messages; + private static final long serialVersionUID = 6328947014421475877L; + + static final String BEAN_CONTEXT = "beanContext"; //$NON-NLS-1$ + + protected transient BeanContext beanContext; + + public BeanContextChild beanContextChildPeer; + + protected PropertyChangeSupport pcSupport; + + protected transient boolean rejectedSetBCOnce; + + protected VetoableChangeSupport vcSupport; + + private transient BeanContext lastVetoedContext; + + public BeanContextChildSupport () { + // This class implements the JavaBean component itself + this(null); + } + + public BeanContextChildSupport (BeanContextChild bcc) { + // If 'bcc' parameter is not null the JavaBean component itself + // implements BeanContextChild + this.beanContextChildPeer = (bcc == null ? this : bcc); + + // Initialize necessary fields for later use + pcSupport = new PropertyChangeSupport(this.beanContextChildPeer); + vcSupport = new VetoableChangeSupport(this.beanContextChildPeer); + this.rejectedSetBCOnce = false; + } + + public void addPropertyChangeListener (String name, PropertyChangeListener pcl) { + // Do nothing if name or listener is null + if ((name == null) || (pcl == null)) { + return; + } + + this.pcSupport.addPropertyChangeListener(name, pcl); + } + + public void addVetoableChangeListener (String name, VetoableChangeListener vcl) { + // Do nothing if name or listener is null + if ((name == null) || (vcl == null)) { + return; + } + + this.vcSupport.addVetoableChangeListener(name, vcl); + this.lastVetoedContext = null; + } + + public void firePropertyChange (String name, Object oldValue, Object newValue) { + this.pcSupport.firePropertyChange(name, oldValue, newValue); + } + + public void fireVetoableChange (String name, Object oldValue, Object newValue) throws PropertyVetoException { + + this.vcSupport.fireVetoableChange(name, oldValue, newValue); + } + + public synchronized BeanContext getBeanContext () { + return this.beanContext; + } -public class BeanContextChildSupport implements BeanContextChild, - BeanContextServicesListener, Serializable { + public BeanContextChild getBeanContextChildPeer () { + return this.beanContextChildPeer; + } - private static final long serialVersionUID = 6328947014421475877L; + protected void initializeBeanContextResources () { + } - static final String BEAN_CONTEXT = "beanContext"; //$NON-NLS-1$ + public boolean isDelegated () { + return (!this.beanContextChildPeer.equals(this)); + } - protected transient BeanContext beanContext; + private void readObject (ObjectInputStream ois) throws IOException, ClassNotFoundException { - public BeanContextChild beanContextChildPeer; + ois.defaultReadObject(); + } - protected PropertyChangeSupport pcSupport; + protected void releaseBeanContextResources () { + } - protected transient boolean rejectedSetBCOnce; + public void removePropertyChangeListener (String name, PropertyChangeListener pcl) { - protected VetoableChangeSupport vcSupport; - - private transient BeanContext lastVetoedContext; + this.pcSupport.removePropertyChangeListener(name, pcl); + } - public BeanContextChildSupport() { - // This class implements the JavaBean component itself - this(null); - } + public void removeVetoableChangeListener (String name, VetoableChangeListener vcl) { - public BeanContextChildSupport(BeanContextChild bcc) { - // If 'bcc' parameter is not null the JavaBean component itself - // implements BeanContextChild - this.beanContextChildPeer = (bcc == null ? this : bcc); + this.vcSupport.removeVetoableChangeListener(name, vcl); + this.lastVetoedContext = null; + } - // Initialize necessary fields for later use - pcSupport = new PropertyChangeSupport(this.beanContextChildPeer); - vcSupport = new VetoableChangeSupport(this.beanContextChildPeer); - this.rejectedSetBCOnce = false; - } + public void serviceAvailable (BeanContextServiceAvailableEvent bcsae) { + if (isDelegated()) { + ((BeanContextServicesListener)beanContextChildPeer).serviceAvailable(bcsae); + } + } - public void addPropertyChangeListener(String name, - PropertyChangeListener pcl) { - // Do nothing if name or listener is null - if ((name == null) || (pcl == null)) { - return; - } + public void serviceRevoked (BeanContextServiceRevokedEvent bcsre) { + if (isDelegated()) { + ((BeanContextServicesListener)beanContextChildPeer).serviceRevoked(bcsre); + } + } - this.pcSupport.addPropertyChangeListener(name, pcl); - } + public synchronized void setBeanContext (BeanContext bc) throws PropertyVetoException { - public void addVetoableChangeListener(String name, - VetoableChangeListener vcl) { - // Do nothing if name or listener is null - if ((name == null) || (vcl == null)) { - return; - } - - this.vcSupport.addVetoableChangeListener(name, vcl); - this.lastVetoedContext = null; - } - - public void firePropertyChange(String name, Object oldValue, Object newValue) { - this.pcSupport.firePropertyChange(name, oldValue, newValue); - } - - public void fireVetoableChange(String name, Object oldValue, Object newValue) - throws PropertyVetoException { - - this.vcSupport.fireVetoableChange(name, oldValue, newValue); - } - - public synchronized BeanContext getBeanContext() { - return this.beanContext; - } - - public BeanContextChild getBeanContextChildPeer() { - return this.beanContextChildPeer; - } - - protected void initializeBeanContextResources() { - } - - public boolean isDelegated() { - return (!this.beanContextChildPeer.equals(this)); - } - - private void readObject(ObjectInputStream ois) throws IOException, - ClassNotFoundException { - - ois.defaultReadObject(); - } - - protected void releaseBeanContextResources() { - } - - public void removePropertyChangeListener(String name, - PropertyChangeListener pcl) { - - this.pcSupport.removePropertyChangeListener(name, pcl); - } - - public void removeVetoableChangeListener(String name, - VetoableChangeListener vcl) { - - this.vcSupport.removeVetoableChangeListener(name, vcl); - this.lastVetoedContext = null; - } - - public void serviceAvailable(BeanContextServiceAvailableEvent bcsae) { - if (isDelegated()) { - ((BeanContextServicesListener) beanContextChildPeer) - .serviceAvailable(bcsae); - } - } - - public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) { - if (isDelegated()) { - ((BeanContextServicesListener) beanContextChildPeer) - .serviceRevoked(bcsre); - } - } - - public synchronized void setBeanContext(BeanContext bc) - throws PropertyVetoException { - - // Do nothing if the old and new values are equal - if ((this.beanContext == null) && (bc == null)) { - return; - } - - if ((this.beanContext != null) && this.beanContext.equals(bc)) { - return; - } - - - - - - // Children are not allowed to repeatedly veto this operation. - // So, we set rejectedSetBCOnce flag to true if veto occurs - // and never veto the change again - if (!(this.rejectedSetBCOnce && this.lastVetoedContext == bc)) { - this.lastVetoedContext = bc; - this.rejectedSetBCOnce = true; - // Validate the new BeanContext value and throw - // PropertyVetoException if it was not successful - if (!validatePendingSetBeanContext(bc)) { - throw new PropertyVetoException(Messages.getString("beans.0F"), //$NON-NLS-1$ - new PropertyChangeEvent(this.beanContextChildPeer, - BEAN_CONTEXT, this.beanContext, bc)); - } - fireVetoableChange(BEAN_CONTEXT, this.beanContext, bc); - } - - this.rejectedSetBCOnce = false; - - releaseBeanContextResources(); - - // We have to notify all listeners about "beanContext" - // property change - firePropertyChange(BEAN_CONTEXT, this.beanContext, bc); - this.beanContext = bc; - initializeBeanContextResources(); - //} - } - - public boolean validatePendingSetBeanContext(BeanContext newValue) { - return true; - } - - private void writeObject(ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - } + // Do nothing if the old and new values are equal + if ((this.beanContext == null) && (bc == null)) { + return; + } + + if ((this.beanContext != null) && this.beanContext.equals(bc)) { + return; + } + + // Children are not allowed to repeatedly veto this operation. + // So, we set rejectedSetBCOnce flag to true if veto occurs + // and never veto the change again + if (!(this.rejectedSetBCOnce && this.lastVetoedContext == bc)) { + this.lastVetoedContext = bc; + this.rejectedSetBCOnce = true; + // Validate the new BeanContext value and throw + // PropertyVetoException if it was not successful + if (!validatePendingSetBeanContext(bc)) { + throw new PropertyVetoException(Messages.getString("beans.0F"), //$NON-NLS-1$ + new PropertyChangeEvent(this.beanContextChildPeer, BEAN_CONTEXT, this.beanContext, bc)); + } + fireVetoableChange(BEAN_CONTEXT, this.beanContext, bc); + } + + this.rejectedSetBCOnce = false; + + releaseBeanContextResources(); + + // We have to notify all listeners about "beanContext" + // property change + firePropertyChange(BEAN_CONTEXT, this.beanContext, bc); + this.beanContext = bc; + initializeBeanContextResources(); + // } + } + + public boolean validatePendingSetBeanContext (BeanContext newValue) { + return true; + } + + private void writeObject (ObjectOutputStream oos) throws IOException { + oos.defaultWriteObject(); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextContainerProxy.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextContainerProxy.java index 52d3581261a..67d2c324b32 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextContainerProxy.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextContainerProxy.java @@ -21,5 +21,5 @@ public interface BeanContextContainerProxy { - public Container getContainer(); + public Container getContainer (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextEvent.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextEvent.java index 54cf6224758..c3fbc69dce9 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextEvent.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextEvent.java @@ -17,36 +17,32 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContext; - import java.util.EventObject; public abstract class BeanContextEvent extends EventObject { - private static final long serialVersionUID = 7267998073569045052L; - - /** - * @serial - */ - protected BeanContext propagatedFrom; + private static final long serialVersionUID = 7267998073569045052L; + + /** @serial */ + protected BeanContext propagatedFrom; - protected BeanContextEvent(BeanContext bc) { - super(bc); - } + protected BeanContextEvent (BeanContext bc) { + super(bc); + } - public BeanContext getBeanContext() { - return (BeanContext) super.getSource(); - } + public BeanContext getBeanContext () { + return (BeanContext)super.getSource(); + } - public synchronized BeanContext getPropagatedFrom() { - return this.propagatedFrom; - } + public synchronized BeanContext getPropagatedFrom () { + return this.propagatedFrom; + } - public synchronized boolean isPropagated() { - return (this.propagatedFrom != null); - } + public synchronized boolean isPropagated () { + return (this.propagatedFrom != null); + } - public synchronized void setPropagatedFrom(BeanContext bc) { - this.propagatedFrom = bc; - } + public synchronized void setPropagatedFrom (BeanContext bc) { + this.propagatedFrom = bc; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipEvent.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipEvent.java index fd9cbb353b5..6cb39e70165 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipEvent.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipEvent.java @@ -17,55 +17,53 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContext; -import com.badlogic.gdx.beans.beancontext.BeanContextEvent; - import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import org.apache.harmony.beans.internal.nls.Messages; + @SuppressWarnings("unchecked") public class BeanContextMembershipEvent extends BeanContextEvent { - private static final long serialVersionUID = 3499346510334590959L; + private static final long serialVersionUID = 3499346510334590959L; - protected Collection children; + protected Collection children; - public BeanContextMembershipEvent(BeanContext bc, Collection changes) { - super(bc); + public BeanContextMembershipEvent (BeanContext bc, Collection changes) { + super(bc); - if (changes == null) { - throw new NullPointerException(Messages.getString("beans.0E")); //$NON-NLS-1$ - } + if (changes == null) { + throw new NullPointerException(Messages.getString("beans.0E")); //$NON-NLS-1$ + } - this.children = changes; - } + this.children = changes; + } - public BeanContextMembershipEvent(BeanContext bc, Object[] changes) { - super(bc); + public BeanContextMembershipEvent (BeanContext bc, Object[] changes) { + super(bc); - if (changes == null) { - throw new NullPointerException(Messages.getString("beans.0E")); //$NON-NLS-1$ - } + if (changes == null) { + throw new NullPointerException(Messages.getString("beans.0E")); //$NON-NLS-1$ + } - // Initialize collection - this.children = Arrays.asList(changes); - } + // Initialize collection + this.children = Arrays.asList(changes); + } - public boolean contains(Object child) { - return this.children.contains(child); - } + public boolean contains (Object child) { + return this.children.contains(child); + } - public Iterator iterator() { - return this.children.iterator(); - } + public Iterator iterator () { + return this.children.iterator(); + } - public int size() { - return this.children.size(); - } + public int size () { + return this.children.size(); + } - public Object[] toArray() { - return this.children.toArray(); - } + public Object[] toArray () { + return this.children.toArray(); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipListener.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipListener.java index 26b3935f8ac..878ec1e2e2e 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipListener.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextMembershipListener.java @@ -17,13 +17,11 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContextMembershipEvent; - import java.util.EventListener; public interface BeanContextMembershipListener extends EventListener { - public void childrenAdded(BeanContextMembershipEvent bcme); + public void childrenAdded (BeanContextMembershipEvent bcme); - public void childrenRemoved(BeanContextMembershipEvent bcme); + public void childrenRemoved (BeanContextMembershipEvent bcme); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextProxy.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextProxy.java index a5e35dd1844..c154081dce1 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextProxy.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextProxy.java @@ -17,9 +17,7 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContextChild; - public interface BeanContextProxy { - public BeanContextChild getBeanContextProxy(); + public BeanContextChild getBeanContextProxy (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceAvailableEvent.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceAvailableEvent.java index 18c7825c980..a24c5ae4606 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceAvailableEvent.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceAvailableEvent.java @@ -17,35 +17,30 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContextEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextServices; - import java.util.Iterator; + @SuppressWarnings("unchecked") public class BeanContextServiceAvailableEvent extends BeanContextEvent { - private static final long serialVersionUID = -5333985775656400778L; + private static final long serialVersionUID = -5333985775656400778L; - /** - * @serial - */ - protected Class serviceClass; + /** @serial */ + protected Class serviceClass; - public BeanContextServiceAvailableEvent(BeanContextServices bcs, Class sc) { - super(bcs); - this.serviceClass = sc; - } + public BeanContextServiceAvailableEvent (BeanContextServices bcs, Class sc) { + super(bcs); + this.serviceClass = sc; + } - public Iterator getCurrentServiceSelectors() { - return ((BeanContextServices) super.source) - .getCurrentServiceSelectors(serviceClass); - } + public Iterator getCurrentServiceSelectors () { + return ((BeanContextServices)super.source).getCurrentServiceSelectors(serviceClass); + } - public Class getServiceClass() { - return this.serviceClass; - } + public Class getServiceClass () { + return this.serviceClass; + } - public BeanContextServices getSourceAsBeanContextServices() { - return (BeanContextServices) super.source; - } + public BeanContextServices getSourceAsBeanContextServices () { + return (BeanContextServices)super.source; + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProvider.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProvider.java index 1e34eab5a4a..3cb3c49aba8 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProvider.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProvider.java @@ -17,16 +17,13 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContextServices; - import java.util.Iterator; @SuppressWarnings("unchecked") public interface BeanContextServiceProvider { - Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass); + Iterator getCurrentServiceSelectors (BeanContextServices bcs, Class serviceClass); - Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, - Object serviceSelector); + Object getService (BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector); - void releaseService(BeanContextServices bcs, Object requestor, Object service); + void releaseService (BeanContextServices bcs, Object requestor, Object service); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProviderBeanInfo.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProviderBeanInfo.java index 6d7643c03dd..65979f5572d 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProviderBeanInfo.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceProviderBeanInfo.java @@ -21,5 +21,5 @@ public interface BeanContextServiceProviderBeanInfo extends BeanInfo { - public BeanInfo[] getServicesBeanInfo(); + public BeanInfo[] getServicesBeanInfo (); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedEvent.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedEvent.java index 8dc542a7540..77d869f6c99 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedEvent.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedEvent.java @@ -17,45 +17,37 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContextEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextServices; - @SuppressWarnings("unchecked") public class BeanContextServiceRevokedEvent extends BeanContextEvent { - private static final long serialVersionUID = -1295543154724961754L; + private static final long serialVersionUID = -1295543154724961754L; - /** - * @serial - */ - protected Class serviceClass; + /** @serial */ + protected Class serviceClass; - /** - * @serial - */ - private boolean invalidateRefs; + /** @serial */ + private boolean invalidateRefs; - public BeanContextServiceRevokedEvent(BeanContextServices bcs, Class sc, - boolean invalidate) { + public BeanContextServiceRevokedEvent (BeanContextServices bcs, Class sc, boolean invalidate) { - super(bcs); - this.serviceClass = sc; - this.invalidateRefs = invalidate; - } + super(bcs); + this.serviceClass = sc; + this.invalidateRefs = invalidate; + } - public Class getServiceClass() { - return this.serviceClass; - } + public Class getServiceClass () { + return this.serviceClass; + } - public BeanContextServices getSourceAsBeanContextServices() { - return (BeanContextServices) super.getBeanContext(); - } + public BeanContextServices getSourceAsBeanContextServices () { + return (BeanContextServices)super.getBeanContext(); + } - public boolean isCurrentServiceInvalidNow() { - return this.invalidateRefs; - } + public boolean isCurrentServiceInvalidNow () { + return this.invalidateRefs; + } - public boolean isServiceClass(Class service) { - return serviceClass.equals(service); - } + public boolean isServiceClass (Class service) { + return serviceClass.equals(service); + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedListener.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedListener.java index 15b86b3fb1d..d4723458e10 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedListener.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServiceRevokedListener.java @@ -17,11 +17,9 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedEvent; - import java.util.EventListener; public interface BeanContextServiceRevokedListener extends EventListener { - public void serviceRevoked(BeanContextServiceRevokedEvent bcsre); + public void serviceRevoked (BeanContextServiceRevokedEvent bcsre); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServices.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServices.java index 519dd9a91ac..c62d492b362 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServices.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServices.java @@ -17,41 +17,28 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContext; -import com.badlogic.gdx.beans.beancontext.BeanContextChild; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceProvider; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedListener; -import com.badlogic.gdx.beans.beancontext.BeanContextServicesListener; - import java.util.Iterator; import java.util.TooManyListenersException; + @SuppressWarnings("unchecked") -public interface BeanContextServices extends BeanContext, - BeanContextServicesListener { +public interface BeanContextServices extends BeanContext, BeanContextServicesListener { - public void addBeanContextServicesListener(BeanContextServicesListener bcsl); + public void addBeanContextServicesListener (BeanContextServicesListener bcsl); - public boolean addService(Class serviceClass, - BeanContextServiceProvider serviceProvider); + public boolean addService (Class serviceClass, BeanContextServiceProvider serviceProvider); - public Iterator getCurrentServiceClasses(); + public Iterator getCurrentServiceClasses (); - public Iterator getCurrentServiceSelectors(Class serviceClass); + public Iterator getCurrentServiceSelectors (Class serviceClass); - public Object getService(BeanContextChild child, Object requestor, - Class serviceClass, Object serviceSelector, - BeanContextServiceRevokedListener bcsrl) - throws TooManyListenersException; + public Object getService (BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, + BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException; - public boolean hasService(Class serviceClass); + public boolean hasService (Class serviceClass); - public void releaseService(BeanContextChild child, Object requestor, - Object service); + public void releaseService (BeanContextChild child, Object requestor, Object service); - public void removeBeanContextServicesListener( - BeanContextServicesListener bcsl); + public void removeBeanContextServicesListener (BeanContextServicesListener bcsl); - public void revokeService(Class serviceClass, - BeanContextServiceProvider serviceProvider, - boolean revokeCurrentServicesNow); + public void revokeService (Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesListener.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesListener.java index bd2870d4126..d7f9c497ea7 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesListener.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesListener.java @@ -17,11 +17,7 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceAvailableEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedListener; +public interface BeanContextServicesListener extends BeanContextServiceRevokedListener { -public interface BeanContextServicesListener extends - BeanContextServiceRevokedListener { - - public void serviceAvailable(BeanContextServiceAvailableEvent bcsae); + public void serviceAvailable (BeanContextServiceAvailableEvent bcsae); } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesSupport.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesSupport.java index bd626a195ed..d3c23ef0f74 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesSupport.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextServicesSupport.java @@ -17,17 +17,6 @@ package com.badlogic.gdx.beans.beancontext; -import com.badlogic.gdx.beans.beancontext.BeanContext; -import com.badlogic.gdx.beans.beancontext.BeanContextChild; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceAvailableEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceProvider; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedListener; -import com.badlogic.gdx.beans.beancontext.BeanContextServices; -import com.badlogic.gdx.beans.beancontext.BeanContextServicesListener; -import com.badlogic.gdx.beans.beancontext.BeanContextServicesSupport; -import com.badlogic.gdx.beans.beancontext.BeanContextSupport; - import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -36,1054 +25,802 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Locale; -import java.util.TooManyListenersException; import java.util.Map.Entry; +import java.util.TooManyListenersException; import org.apache.harmony.beans.internal.nls.Messages; -/** - * This support class implements BeanContextServices interface. - * This class can be used directly, or be a super class of your class, or be a - * delegate of your implementation that needs to support - * BeanContextServices interface. - * - */ -public class BeanContextServicesSupport extends BeanContextSupport implements - BeanContextServices, Serializable { - - private static class ServiceRecord { - - BeanContextServiceProvider provider; - - BeanContextChild child; - - Object requestor; - - Class serviceClass; - - BeanContextServiceRevokedListener revokedListener; - - Object service; - - boolean isDelegate; - - ServiceRecord(BeanContextServiceProvider provider, - BeanContextChild child, Object requestor, Class serviceClass, - BeanContextServiceRevokedListener revokedListener, - Object service, boolean isDelegate) { - this.provider = provider; - this.child = child; - this.requestor = requestor; - this.serviceClass = serviceClass; - this.revokedListener = revokedListener; - this.service = service; - this.isDelegate = isDelegate; - } - } - - /** - * Every child of context is companied with a BCSSChild - * instance. It can hold implementation specific information about each - * child. - *

        - * This class keeps records of all services requests submitted by this - * child. - *

        - * - */ - protected class BCSSChild extends BeanContextSupport.BCSChild { - - private static final long serialVersionUID = -3263851306889194873L; - - transient ArrayList serviceRecords; - - BCSSChild(Object child, Object proxyPeer) { - super(child, proxyPeer); - } - - } - - /** - * This class implements the BeanContextServiceProvider - * interface by wrapping a BeanContextServices. All services - * registered in the BeanContextServices are accessible via - * this wrapper service provider. - *

        - * This class is used by BeanContextServicesSupport to access - * services provided by its parent context (if there is one). - *

        - * - */ - protected class BCSSProxyServiceProvider implements - BeanContextServiceProvider, BeanContextServiceRevokedListener { - - private BeanContextServices backBCS; - - BCSSProxyServiceProvider(BeanContextServices backBCS) { - this.backBCS = backBCS; - } - - /** - * Throws UnsupportedOperationException. - */ - public Iterator getCurrentServiceSelectors(BeanContextServices bcs, - Class serviceClass) { - throw new UnsupportedOperationException(); - } - - /** - * Throws UnsupportedOperationException. - */ - public Object getService(BeanContextServices bcs, Object requestor, - Class serviceClass, Object serviceSelector) { - throw new UnsupportedOperationException(); - } - - /** - * Delegate to the wrapped BeanContextServices. - */ - Object getService(BeanContextServices bcs, Object requestor, - Class serviceClass, Object serviceSelector, - BeanContextServiceRevokedListener listener) - throws TooManyListenersException { - return backBCS.getService(BeanContextServicesSupport.this - .getBeanContextServicesPeer(), requestor, serviceClass, - serviceSelector, new ServiceRevokedListenerDelegator( - listener)); - } - - /** - * Delegate to the wrapped BeanContextServices. - */ - public void releaseService(BeanContextServices bcs, Object requestor, - Object service) { - backBCS.releaseService(BeanContextServicesSupport.this - .getBeanContextServicesPeer(), requestor, service); - } - - /** - * Throws UnsupportedOperationException. - */ - public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) { - throw new UnsupportedOperationException(); - } - - } - - private class ServiceRevokedListenerDelegator implements - BeanContextServiceRevokedListener { - - private BeanContextServiceRevokedListener backListener; - - public ServiceRevokedListenerDelegator( - BeanContextServiceRevokedListener backListener) { - this.backListener = backListener; - } - - public void serviceRevoked(BeanContextServiceRevokedEvent event) { - backListener.serviceRevoked(new BeanContextServiceRevokedEvent( - BeanContextServicesSupport.this - .getBeanContextServicesPeer(), event - .getServiceClass(), event - .isCurrentServiceInvalidNow())); - } - - } - - /** - * Every servie registered in this context is companied with a - * BCSSServiceProvider instance. It can hold implementation - * specific information about each registered service. - *

        - * This class holds a reference to the service provider of the service. - *

        - * - */ - protected static class BCSSServiceProvider implements Serializable { - - private static final long serialVersionUID = 861278251667444782L; - - /** - * The service provider of the related service. - */ - protected BeanContextServiceProvider serviceProvider; - - BCSSServiceProvider(BeanContextServiceProvider provider) { - this.serviceProvider = provider; - } - - /** - * Returns the service provider of the related service. - * - * @return the service provider of the related service - */ - protected BeanContextServiceProvider getServiceProvider() { - return serviceProvider; - } - - } - - private static final long serialVersionUID = -8494482757288719206L; - - /** - * A map of all registered services - key is service class, value is - * BCSSServiceProvider object. All access to this object - * should be synchronized on itself. - */ - @SuppressWarnings("unchecked") - protected transient HashMap services; - - /** - * The number of serializable service providers currently registered. - */ - protected transient int serializable; - - /** - * A proxy service provider that delegates service requests to the parent - * context. - */ - protected transient BCSSProxyServiceProvider proxy; - - /** - * A list of registered BeanContextServicesListeners. All - * access to this object should be synchronized on itself. - */ - @SuppressWarnings("unchecked") - protected transient ArrayList bcsListeners; - - /** - * Constructs a standard BeanContextServicesSupport. - */ - public BeanContextServicesSupport() { - super(); - } - - /** - * Constructs a BeanContextServicesSupport which is a - * delegate of the given peer. - * - * @param peer - * the peer of this context - */ - public BeanContextServicesSupport(BeanContextServices peer) { - super(peer); - } - - /** - * Constructs a BeanContextServicesSupport which is a - * delegate of the given peer. - * - * @param peer - * the peer of this context - * @param locale - * the locale of this context - */ - public BeanContextServicesSupport(BeanContextServices peer, Locale locale) { - super(peer, locale); - } - - /** - * Constructs a BeanContextServicesSupport which is a - * delegate of the given peer. - * - * @param peer - * the peer of this context - * @param locale - * the locale of this context - * @param designTime - * whether in design mode or not - */ - public BeanContextServicesSupport(BeanContextServices peer, Locale locale, - boolean designTime) { - super(peer, locale, designTime); - } - - /** - * Constructs a BeanContextServicesSupport which is a - * delegate of the given peer. - * - * @param peer - * the peer of this context - * @param locale - * the locale of this context - * @param designTime - * whether in design mode or not - * @param okToUseGui - * whether GUI is usable or not - */ - public BeanContextServicesSupport(BeanContextServices peer, Locale locale, - boolean designTime, boolean okToUseGui) { - super(peer, locale, designTime, okToUseGui); - } - - /* - * (non-Javadoc) - * - * @see com.esotericsoftware.android.beans.beancontext.BeanContextServices#addBeanContextServicesListener(com.esotericsoftware.android.beans.beancontext.BeanContextServicesListener) - */ - public void addBeanContextServicesListener( - BeanContextServicesListener listener) { - if (listener == null) { - throw new NullPointerException(); - } - synchronized (bcsListeners) { - bcsListeners.add(listener); - } - } - - /** - * Add a service to this context. - *

        - * Delegate to addService(serviceClass, provider, true). - *

        - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#addService(java.lang.Class, - * com.badlogic.gdx.beans.beancontext.BeanContextServiceProvider) - */ - public boolean addService(Class serviceClass, - BeanContextServiceProvider provider) { - return addService(serviceClass, provider, true); - } - - /** - * Add a service to this context. - *

        - * If the service already exists in the context, simply return false. - * Otherwise, the service is added and event is fired if required. - *

        - * - * @param serviceClass - * the service class - * @param provider - * the provider of the service - * @param fireEvent - * the flag indicating to fire event or not - * @return true if the service is added; or false if the context already has - * this service - */ - protected boolean addService(Class serviceClass, - BeanContextServiceProvider provider, boolean fireEvent) { - if (serviceClass == null || provider == null) { - throw new NullPointerException(); - } - - synchronized (globalHierarchyLock) { - synchronized (services) { - if (services.containsKey(serviceClass)) { - return false; - } - // add to services - services.put(serviceClass, createBCSSServiceProvider( - serviceClass, provider)); - // count Serializable - if (provider instanceof Serializable) { - serializable++; - } - } - } - - if (fireEvent) { - // notify all listeners and BeanContextServices children - notifyServiceAvailable(new BeanContextServiceAvailableEvent(this, - serviceClass)); - } - return true; - } - - private void notifyServiceAvailable(BeanContextServiceAvailableEvent event) { - fireServiceAdded(event); - Object childs[] = copyChildren(); - for (int i = 0; i < childs.length; i++) { - if (childs[i] instanceof BeanContextServices) { - ((BeanContextServices) childs[i]).serviceAvailable(event); - } - } - } - - /** - * Deserializes all serializable services and their providers before the - * children of this context is deserialized. - *

        - * First a int is read, indicating the number of services to - * read. Then pairs of service class and service provider are read one by - * one. - *

        - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#bcsPreDeserializationHook(java.io.ObjectInputStream) - */ - protected void bcsPreDeserializationHook(ObjectInputStream ois) - throws IOException, ClassNotFoundException { - super.bcsPreDeserializationHook(ois); - - // deserialize services - synchronized (services) { - serializable = ois.readInt(); - for (int i = 0; i < serializable; i++) { - Object serviceClass = ois.readObject(); - Object bcssProvider = ois.readObject(); - services.put((Class) serviceClass, - (BCSSServiceProvider) bcssProvider); - } - } - } - - /** - * Serializes all serializable services and their providers before the - * children of this context is serialized. - *

        - * First a int is writtern, indicating the number of - * serializable services. Then pairs of service class and service provider - * are writtern one by one. - *

        - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#bcsPreSerializationHook(java.io.ObjectOutputStream) - */ - protected void bcsPreSerializationHook(ObjectOutputStream oos) - throws IOException { - super.bcsPreSerializationHook(oos); - - // serialize services - synchronized (services) { - oos.writeInt(serializable); - for (Iterator iter = services.entrySet().iterator(); iter.hasNext();) { - Entry entry = (Entry) iter.next(); - if (((BCSSServiceProvider) entry.getValue()) - .getServiceProvider() instanceof Serializable) { - oos.writeObject(entry.getKey()); - oos.writeObject(entry.getValue()); - } - } - } - } - - /** - * This method is called everytime a child is removed from this context. - *

        - * The implementation releases all services requested by the child. - *

        - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#childJustRemovedHook(java.lang.Object, - * com.badlogic.gdx.beans.beancontext.BeanContextSupport.BCSChild) - */ - protected void childJustRemovedHook(Object child, BCSChild bcsChild) { - if (bcsChild instanceof BCSSChild) { - releaseServicesForChild((BCSSChild) bcsChild, false); - } - } - - /** - * Release all services requested by the given child. - * - * @param bcssChild - * a child - * @param delegatedServices - * only release services that are delegated to parent context - */ - private void releaseServicesForChild(BCSSChild bcssChild, - boolean delegatedServices) { - if (bcssChild.serviceRecords == null - || bcssChild.serviceRecords.isEmpty()) { - return; - } - synchronized (bcssChild.child) { - Object records[] = bcssChild.serviceRecords.toArray(); - for (int i = 0; i < records.length; i++) { - ServiceRecord rec = (ServiceRecord) records[i]; - if (delegatedServices) { - if (rec.isDelegate) { - releaseServiceWithoutCheck(rec.child, bcssChild, - rec.requestor, rec.service, true); - } - } else { - releaseServiceWithoutCheck(rec.child, bcssChild, - rec.requestor, rec.service, false); - } - } - } - } - - /** - * Creates a BCSSChild object to company the given child. - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#createBCSChild(java.lang.Object, - * java.lang.Object) - */ - protected BCSChild createBCSChild(Object child, Object proxyPeer) { - return new BCSSChild(child, proxyPeer); - } - - /** - * Creates a BCSSServiceProvider to company the given - * service. - * - * @param serviceClass - * the service class - * @param provider - * the service provider - * @return a BCSSServiceProvider to company the given service - */ - protected BCSSServiceProvider createBCSSServiceProvider(Class serviceClass, - BeanContextServiceProvider provider) { - return new BCSSServiceProvider(provider); - } - - /** - * Fires a BeanContextServiceAvailableEvent to registered - * BeanContextServicesListeners. - * - * @param serviceClass - * the service that has been added - */ - protected final void fireServiceAdded(Class serviceClass) { - fireServiceAdded(new BeanContextServiceAvailableEvent(this, - serviceClass)); - } - - /** - * Fires a BeanContextServiceAvailableEvent to registered - * BeanContextServicesListeners. - * - * @param event - * the event - */ - protected final void fireServiceAdded(BeanContextServiceAvailableEvent event) { - Object listeners[]; - synchronized (bcsListeners) { - listeners = bcsListeners.toArray(); - } - for (int i = 0; i < listeners.length; i++) { - BeanContextServicesListener l = (BeanContextServicesListener) listeners[i]; - l.serviceAvailable(event); - } - } - - /** - * Fires a BeanContextServiceRevokedEvent to registered - * BeanContextServicesListeners. - * - * @param serviceClass - * the service that has been revoked - * @param revokeNow - * whether to terminate service immediately - */ - protected final void fireServiceRevoked(Class serviceClass, - boolean revokeNow) { - fireServiceRevoked(new BeanContextServiceRevokedEvent(this, - serviceClass, revokeNow)); - } - - /** - * Fires a BeanContextServiceRevokedEvent to registered - * BeanContextServicesListeners. - * - * @param event - * the event - */ - protected final void fireServiceRevoked(BeanContextServiceRevokedEvent event) { - Object listeners[]; - synchronized (bcsListeners) { - listeners = bcsListeners.toArray(); - } - for (int i = 0; i < listeners.length; i++) { - BeanContextServicesListener l = (BeanContextServicesListener) listeners[i]; - l.serviceRevoked(event); - } - } - - /** - * Returns the peer of this context casted as - * BeanContextServices. - * - * @return the peer of this context casted as - * BeanContextServices - */ - public BeanContextServices getBeanContextServicesPeer() { - return (BeanContextServices) beanContextChildPeer; - } - - /** - * Returns the given child casted to - * BeanContextServicesListener, or null if it does not - * implements the interface. - * - * @param child - * a child - * @return the given child casted to - * BeanContextServicesListener, or null if it does - * not implements the interface - */ - protected static final BeanContextServicesListener getChildBeanContextServicesListener( - Object child) { - if (child instanceof BeanContextServicesListener) { - return (BeanContextServicesListener) child; - } - return null; - } - - /** - * Returns an iterator of all registered service classes, with - * removed() disabled. - * - * @return an iterator of all registered service classes - * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#getCurrentServiceClasses() - */ - public Iterator getCurrentServiceClasses() { - synchronized (services) { - return new BCSIterator(services.keySet().iterator()); - } - } - - /** - * Returns the service selectors of the specified service. The iterator's - * remove() operation is disabled. - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#getCurrentServiceSelectors(java.lang.Class) - */ - public Iterator getCurrentServiceSelectors(Class serviceClass) { - BeanContextServiceProvider provider = getLocalServiceProvider(serviceClass); - return provider == null ? null : new BCSIterator(provider - .getCurrentServiceSelectors(getBeanContextServicesPeer(), - serviceClass)); - } - - private BeanContextServiceProvider getLocalServiceProvider( - Class serviceClass) { - synchronized (services) { - BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services - .get(serviceClass); - if (bcssProvider != null) { - return bcssProvider.getServiceProvider(); - } - return null; - } - } - - /** - * Get a service instance on behalf of the specified child of this context, - * by calling the registered service provider, or by delegating to the - * parent context. - * - * @param child - * the child that request service - * @param requestor - * the requestor object - * @param serviceClass - * the service class - * @param serviceSelector - * the service selectors - * @param bcsrl - * the BeanContextServiceRevokedListener - * @return a service instance on behalf of the specified child of this - * context - * @throws IllegalArgumentException - * if child is not a child of this context - * @throws TooManyListenersException - * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#getService(com.badlogic.gdx.beans.beancontext.BeanContextChild, - * java.lang.Object, java.lang.Class, java.lang.Object, - * com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedListener) - */ - public Object getService(BeanContextChild child, Object requestor, - Class serviceClass, Object serviceSelector, - BeanContextServiceRevokedListener bcsrl) - throws TooManyListenersException { - if (child == null || requestor == null || serviceClass == null - || bcsrl == null) { - throw new NullPointerException(); - } - - BCSSChild bcssChild = null; - BeanContextServiceProvider provider = null; - Object service = null; - boolean isDelegate = false; - - synchronized (globalHierarchyLock) { - // check child - synchronized (children) { - bcssChild = (BCSSChild) children.get(child); - } - if (bcssChild == null) { - throw new IllegalArgumentException( - Messages.getString("beans.65")); - } - - // try local service - provider = getLocalServiceProvider(serviceClass); - if (provider != null) { - service = provider.getService(getBeanContextServicesPeer(), - requestor, serviceClass, serviceSelector); - } - - // no local service, try delegate - if (service == null && proxy != null) { - provider = proxy; - service = proxy.getService(getBeanContextServicesPeer(), - requestor, serviceClass, serviceSelector, bcsrl); - isDelegate = true; - } - } - - if (service != null) { - // save record - synchronized (child) { - if (bcssChild.serviceRecords == null) { - bcssChild.serviceRecords = new ArrayList(); - } - bcssChild.serviceRecords.add(new ServiceRecord(provider, child, - requestor, serviceClass, bcsrl, service, isDelegate)); - } - } - - return service; - } - - /** - * Checks whether a service is registed in this context or the parent - * context. - * - * @param serviceClass - * the service class - * @return true if the service is registered - * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#hasService(java.lang.Class) - */ - public boolean hasService(Class serviceClass) { - if (serviceClass == null) { - throw new NullPointerException(); - } - - boolean has; - synchronized (services) { - has = services.containsKey(serviceClass); - } - if (!has && getBeanContext() instanceof BeanContextServices) { - has = ((BeanContextServices) getBeanContext()) - .hasService(serviceClass); - } - return has; - } - - /* - * (non-Javadoc) - * - * @see com.esotericsoftware.android.beans.beancontext.BeanContextSupport#initialize() - */ - public void initialize() { - super.initialize(); - services = new HashMap(); - serializable = 0; - proxy = null; - bcsListeners = new ArrayList(); - } - - /** - * Called after the parent context is updated. The implementation checks if - * the parent context is a BeanContextServices. If it is, - * then a BCSSProxyServiceProvider is created to delegate - * service requests to the parent context. - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextChildSupport#initializeBeanContextResources() - */ - protected void initializeBeanContextResources() { - super.initializeBeanContextResources(); - - BeanContext context = getBeanContext(); - if (context instanceof BeanContextServices) { - proxy = new BCSSProxyServiceProvider((BeanContextServices) context); - } else { - proxy = null; - } - } - - /** - * Called before the parent context is updated. The implementation releases - * any service that is currently provided by the parent context. - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextChildSupport#releaseBeanContextResources() - */ - protected void releaseBeanContextResources() { - super.releaseBeanContextResources(); - - releaseAllDelegatedServices(); - proxy = null; - } - - private void releaseAllDelegatedServices() { - synchronized (children) { - for (Iterator iter = bcsChildren(); iter.hasNext();) { - releaseServicesForChild((BCSSChild) iter.next(), true); - } - } - } - - /** - * Release a service which has been requested previously. - * - * @param child - * the child that request the service - * @param requestor - * the requestor object - * @param service - * the service instance - * @throws IllegalArgumentException - * if child is not a child of this context - */ - public void releaseService(BeanContextChild child, Object requestor, - Object service) { - if (child == null || requestor == null || service == null) { - throw new NullPointerException(); - } - - synchronized (globalHierarchyLock) { - BCSSChild bcssChild; - synchronized (children) { - bcssChild = (BCSSChild) children.get(child); - } - if (bcssChild == null) { - throw new IllegalArgumentException( - Messages.getString("beans.65")); - } - - releaseServiceWithoutCheck(child, bcssChild, requestor, service, - false); - } - } - - /** - * Releases a service without checking the membership of the child. - */ - private void releaseServiceWithoutCheck(BeanContextChild child, - BCSSChild bcssChild, Object requestor, Object service, - boolean callRevokedListener) { - - if (bcssChild.serviceRecords == null - || bcssChild.serviceRecords.isEmpty()) { - return; - } - - synchronized (child) { - // scan record - for (Iterator iter = bcssChild.serviceRecords.iterator(); iter - .hasNext();) { - ServiceRecord rec = (ServiceRecord) iter.next(); - if (rec.requestor == requestor && rec.service == service) { - // release service - rec.provider.releaseService(getBeanContextServicesPeer(), - requestor, service); - // call service revoked listener - if (callRevokedListener && rec.revokedListener != null) { - rec.revokedListener - .serviceRevoked(new BeanContextServiceRevokedEvent( - getBeanContextServicesPeer(), - rec.serviceClass, true)); - } - // remove record - iter.remove(); - break; - } - } - } - } - - /* - * (non-Javadoc) - * - * @see com.esotericsoftware.android.beans.beancontext.BeanContextServices#removeBeanContextServicesListener(com.esotericsoftware.android.beans.beancontext.BeanContextServicesListener) - */ - public void removeBeanContextServicesListener( - BeanContextServicesListener listener) { - if (listener == null) { - throw new NullPointerException(); - } - synchronized (bcsListeners) { - bcsListeners.remove(listener); - } - } - - /** - * Revokes a service in this bean context. - *

        - * The given service provider is unregistered and a - * BeanContextServiceRevokedEvent is fired. All registered - * service listeners and current service users get notified. - *

        - * - * @param serviceClass - * the service class - * @param serviceProvider - * the service provider - * @param revokeCurrentServicesNow - * true if service should be terminated immediantly - * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#revokeService(java.lang.Class, - * com.badlogic.gdx.beans.beancontext.BeanContextServiceProvider, boolean) - */ - public void revokeService(Class serviceClass, - BeanContextServiceProvider serviceProvider, - boolean revokeCurrentServicesNow) { - if (serviceClass == null || serviceProvider == null) { - throw new NullPointerException(); - } - - synchronized (globalHierarchyLock) { - synchronized (services) { - BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services - .get(serviceClass); - if (bcssProvider == null) { // non-exist service - return; - } - if (bcssProvider.getServiceProvider() != serviceProvider) { - throw new IllegalArgumentException( - Messages.getString("beans.66")); - } - - services.remove(serviceClass); - - if (serviceProvider instanceof Serializable) { - serializable--; - } - } - } - - // notify listeners - fireServiceRevoked(serviceClass, revokeCurrentServicesNow); - - // notify service users - notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider, - revokeCurrentServicesNow); - } - - /** - * Notify all children that a service has been revoked. - */ - private void notifyServiceRevokedToServiceUsers(Class serviceClass, - BeanContextServiceProvider serviceProvider, - boolean revokeCurrentServicesNow) { - synchronized (children) { - for (Iterator iter = bcsChildren(); iter.hasNext();) { - BCSSChild bcssChild = (BCSSChild) iter.next(); - notifyServiceRevokedToServiceUsers(serviceClass, - serviceProvider, revokeCurrentServicesNow, bcssChild); - } - } - } - - /** - * Notify the given child that a service has been revoked. - */ - private void notifyServiceRevokedToServiceUsers(Class serviceClass, - BeanContextServiceProvider serviceProvider, - boolean revokeCurrentServicesNow, BCSSChild bcssChild) { - if (bcssChild.serviceRecords == null - || bcssChild.serviceRecords.isEmpty()) { - return; - } - synchronized (bcssChild.child) { - for (Iterator it = bcssChild.serviceRecords.iterator(); it - .hasNext();) { - ServiceRecord rec = (ServiceRecord) it.next(); - if (rec.serviceClass == serviceClass - && rec.provider == serviceProvider - && rec.revokedListener != null && !rec.isDelegate) { - rec.revokedListener - .serviceRevoked(new BeanContextServiceRevokedEvent( - getBeanContextServicesPeer(), serviceClass, - revokeCurrentServicesNow)); - // prevent duplicate notification - rec.revokedListener = null; - } - } - } - } - - /** - * Notify all listeners and children that implements - * BeanContextServices of the event. - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextServicesListener#serviceAvailable(com.badlogic.gdx.beans.beancontext.BeanContextServiceAvailableEvent) - */ - public void serviceAvailable(BeanContextServiceAvailableEvent event) { - if (null == event) { - throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$ - } - if (services.containsKey(event.serviceClass)) { - return; - } - fireServiceAdded(event); - Object childs[] = copyChildren(); - for (int i = 0; i < childs.length; i++) { - if (childs[i] instanceof BeanContextServices) { - ((BeanContextServices) childs[i]).serviceAvailable(event); - } - } - } - - /** - * Notify all listeners and children that implements - * BeanContextServices of the event. - * - * @see com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedListener#serviceRevoked(com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedEvent) - */ - public void serviceRevoked(BeanContextServiceRevokedEvent event) { - if (null == event) { - throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$ - } - if (services.containsKey(event.serviceClass)) { - return; - } - fireServiceRevoked(event); - Object childs[] = copyChildren(); - for (int i = 0; i < childs.length; i++) { - if (childs[i] instanceof BeanContextServices) { - ((BeanContextServices) childs[i]).serviceRevoked(event); - } - } - } - - /** - * The implementation goes through following steps: - *

        - *

          - *
        1. Calls defaultWriteObject().
        2. - *
        3. Writes out serializable service listeners.
        4. - *
        - *

        - * - * @param oos - * the object output stream - * @throws IOException - * if I/O exception occurs - */ - private void writeObject(ObjectOutputStream oos) throws IOException { - - oos.defaultWriteObject(); - - synchronized (bcsListeners) { - serialize(oos, bcsListeners); - } - } - - /** - * The implementation goes through following steps: - *

        - *

          - *
        1. Calls defaultReadObject().
        2. - *
        3. Reads serializable service listeners.
        4. - *
        - *

        - * - * @param ois - * the object input stream - * @throws IOException - * if I/O error occurs - * @throws ClassNotFoundException - * if class of read object is not found - */ - private void readObject(ObjectInputStream ois) throws IOException, - ClassNotFoundException { - - ois.defaultReadObject(); - - synchronized (bcsListeners) { - deserialize(ois, bcsListeners); - } - } +/** This support class implements BeanContextServices interface. This class can be used directly, or be a super class + * of your class, or be a delegate of your implementation that needs to support BeanContextServices interface. */ +public class BeanContextServicesSupport extends BeanContextSupport implements BeanContextServices, Serializable { + + private static class ServiceRecord { + + BeanContextServiceProvider provider; + + BeanContextChild child; + + Object requestor; + + Class serviceClass; + + BeanContextServiceRevokedListener revokedListener; + + Object service; + + boolean isDelegate; + + ServiceRecord (BeanContextServiceProvider provider, BeanContextChild child, Object requestor, Class serviceClass, + BeanContextServiceRevokedListener revokedListener, Object service, boolean isDelegate) { + this.provider = provider; + this.child = child; + this.requestor = requestor; + this.serviceClass = serviceClass; + this.revokedListener = revokedListener; + this.service = service; + this.isDelegate = isDelegate; + } + } + + /** Every child of context is companied with a BCSSChild instance. It can hold implementation specific information + * about each child. + *

        + * This class keeps records of all services requests submitted by this child. + *

        */ + protected class BCSSChild extends BeanContextSupport.BCSChild { + + private static final long serialVersionUID = -3263851306889194873L; + + transient ArrayList serviceRecords; + + BCSSChild (Object child, Object proxyPeer) { + super(child, proxyPeer); + } + + } + + /** This class implements the BeanContextServiceProvider interface by wrapping a BeanContextServices. + * All services registered in the BeanContextServices are accessible via this wrapper service provider. + *

        + * This class is used by BeanContextServicesSupport to access services provided by its parent context (if there is + * one). + *

        */ + protected class BCSSProxyServiceProvider implements BeanContextServiceProvider, BeanContextServiceRevokedListener { + + private BeanContextServices backBCS; + + BCSSProxyServiceProvider (BeanContextServices backBCS) { + this.backBCS = backBCS; + } + + /** Throws UnsupportedOperationException. */ + public Iterator getCurrentServiceSelectors (BeanContextServices bcs, Class serviceClass) { + throw new UnsupportedOperationException(); + } + + /** Throws UnsupportedOperationException. */ + public Object getService (BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) { + throw new UnsupportedOperationException(); + } + + /** Delegate to the wrapped BeanContextServices. */ + Object getService (BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector, + BeanContextServiceRevokedListener listener) throws TooManyListenersException { + return backBCS.getService(BeanContextServicesSupport.this.getBeanContextServicesPeer(), requestor, serviceClass, + serviceSelector, new ServiceRevokedListenerDelegator(listener)); + } + + /** Delegate to the wrapped BeanContextServices. */ + public void releaseService (BeanContextServices bcs, Object requestor, Object service) { + backBCS.releaseService(BeanContextServicesSupport.this.getBeanContextServicesPeer(), requestor, service); + } + + /** Throws UnsupportedOperationException. */ + public void serviceRevoked (BeanContextServiceRevokedEvent bcsre) { + throw new UnsupportedOperationException(); + } + + } + + private class ServiceRevokedListenerDelegator implements BeanContextServiceRevokedListener { + + private BeanContextServiceRevokedListener backListener; + + public ServiceRevokedListenerDelegator (BeanContextServiceRevokedListener backListener) { + this.backListener = backListener; + } + + public void serviceRevoked (BeanContextServiceRevokedEvent event) { + backListener.serviceRevoked(new BeanContextServiceRevokedEvent(BeanContextServicesSupport.this + .getBeanContextServicesPeer(), event.getServiceClass(), event.isCurrentServiceInvalidNow())); + } + + } + + /** Every servie registered in this context is companied with a BCSSServiceProvider instance. It can hold + * implementation specific information about each registered service. + *

        + * This class holds a reference to the service provider of the service. + *

        */ + protected static class BCSSServiceProvider implements Serializable { + + private static final long serialVersionUID = 861278251667444782L; + + /** The service provider of the related service. */ + protected BeanContextServiceProvider serviceProvider; + + BCSSServiceProvider (BeanContextServiceProvider provider) { + this.serviceProvider = provider; + } + + /** Returns the service provider of the related service. + * + * @return the service provider of the related service */ + protected BeanContextServiceProvider getServiceProvider () { + return serviceProvider; + } + + } + + private static final long serialVersionUID = -8494482757288719206L; + + /** A map of all registered services - key is service class, value is BCSSServiceProvider object. All access to + * this object should be synchronized on itself. */ + @SuppressWarnings("unchecked") + protected transient HashMap services; + + /** The number of serializable service providers currently registered. */ + protected transient int serializable; + + /** A proxy service provider that delegates service requests to the parent context. */ + protected transient BCSSProxyServiceProvider proxy; + + /** A list of registered BeanContextServicesListeners. All access to this object should be synchronized on itself. */ + @SuppressWarnings("unchecked") + protected transient ArrayList bcsListeners; + + /** Constructs a standard BeanContextServicesSupport. */ + public BeanContextServicesSupport () { + super(); + } + + /** Constructs a BeanContextServicesSupport which is a delegate of the given peer. + * + * @param peer the peer of this context */ + public BeanContextServicesSupport (BeanContextServices peer) { + super(peer); + } + + /** Constructs a BeanContextServicesSupport which is a delegate of the given peer. + * + * @param peer the peer of this context + * @param locale the locale of this context */ + public BeanContextServicesSupport (BeanContextServices peer, Locale locale) { + super(peer, locale); + } + + /** Constructs a BeanContextServicesSupport which is a delegate of the given peer. + * + * @param peer the peer of this context + * @param locale the locale of this context + * @param designTime whether in design mode or not */ + public BeanContextServicesSupport (BeanContextServices peer, Locale locale, boolean designTime) { + super(peer, locale, designTime); + } + + /** Constructs a BeanContextServicesSupport which is a delegate of the given peer. + * + * @param peer the peer of this context + * @param locale the locale of this context + * @param designTime whether in design mode or not + * @param okToUseGui whether GUI is usable or not */ + public BeanContextServicesSupport (BeanContextServices peer, Locale locale, boolean designTime, boolean okToUseGui) { + super(peer, locale, designTime, okToUseGui); + } + + /* + * (non-Javadoc) + * + * @see + * com.esotericsoftware.android.beans.beancontext.BeanContextServices#addBeanContextServicesListener(com.esotericsoftware.android + * .beans.beancontext.BeanContextServicesListener) + */ + public void addBeanContextServicesListener (BeanContextServicesListener listener) { + if (listener == null) { + throw new NullPointerException(); + } + synchronized (bcsListeners) { + bcsListeners.add(listener); + } + } + + /** Add a service to this context. + *

        + * Delegate to addService(serviceClass, provider, true). + *

        + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#addService(java.lang.Class, + * com.badlogic.gdx.beans.beancontext.BeanContextServiceProvider) */ + public boolean addService (Class serviceClass, BeanContextServiceProvider provider) { + return addService(serviceClass, provider, true); + } + + /** Add a service to this context. + *

        + * If the service already exists in the context, simply return false. Otherwise, the service is added and event is fired if + * required. + *

        + * + * @param serviceClass the service class + * @param provider the provider of the service + * @param fireEvent the flag indicating to fire event or not + * @return true if the service is added; or false if the context already has this service */ + protected boolean addService (Class serviceClass, BeanContextServiceProvider provider, boolean fireEvent) { + if (serviceClass == null || provider == null) { + throw new NullPointerException(); + } + + synchronized (globalHierarchyLock) { + synchronized (services) { + if (services.containsKey(serviceClass)) { + return false; + } + // add to services + services.put(serviceClass, createBCSSServiceProvider(serviceClass, provider)); + // count Serializable + if (provider instanceof Serializable) { + serializable++; + } + } + } + + if (fireEvent) { + // notify all listeners and BeanContextServices children + notifyServiceAvailable(new BeanContextServiceAvailableEvent(this, serviceClass)); + } + return true; + } + + private void notifyServiceAvailable (BeanContextServiceAvailableEvent event) { + fireServiceAdded(event); + Object childs[] = copyChildren(); + for (int i = 0; i < childs.length; i++) { + if (childs[i] instanceof BeanContextServices) { + ((BeanContextServices)childs[i]).serviceAvailable(event); + } + } + } + + /** Deserializes all serializable services and their providers before the children of this context is deserialized. + *

        + * First a int is read, indicating the number of services to read. Then pairs of service class and service + * provider are read one by one. + *

        + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#bcsPreDeserializationHook(java.io.ObjectInputStream) */ + protected void bcsPreDeserializationHook (ObjectInputStream ois) throws IOException, ClassNotFoundException { + super.bcsPreDeserializationHook(ois); + + // deserialize services + synchronized (services) { + serializable = ois.readInt(); + for (int i = 0; i < serializable; i++) { + Object serviceClass = ois.readObject(); + Object bcssProvider = ois.readObject(); + services.put((Class)serviceClass, (BCSSServiceProvider)bcssProvider); + } + } + } + + /** Serializes all serializable services and their providers before the children of this context is serialized. + *

        + * First a int is writtern, indicating the number of serializable services. Then pairs of service class and + * service provider are writtern one by one. + *

        + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#bcsPreSerializationHook(java.io.ObjectOutputStream) */ + protected void bcsPreSerializationHook (ObjectOutputStream oos) throws IOException { + super.bcsPreSerializationHook(oos); + + // serialize services + synchronized (services) { + oos.writeInt(serializable); + for (Iterator iter = services.entrySet().iterator(); iter.hasNext();) { + Entry entry = (Entry)iter.next(); + if (((BCSSServiceProvider)entry.getValue()).getServiceProvider() instanceof Serializable) { + oos.writeObject(entry.getKey()); + oos.writeObject(entry.getValue()); + } + } + } + } + + /** This method is called everytime a child is removed from this context. + *

        + * The implementation releases all services requested by the child. + *

        + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#childJustRemovedHook(java.lang.Object, + * com.badlogic.gdx.beans.beancontext.BeanContextSupport.BCSChild) */ + protected void childJustRemovedHook (Object child, BCSChild bcsChild) { + if (bcsChild instanceof BCSSChild) { + releaseServicesForChild((BCSSChild)bcsChild, false); + } + } + + /** Release all services requested by the given child. + * + * @param bcssChild a child + * @param delegatedServices only release services that are delegated to parent context */ + private void releaseServicesForChild (BCSSChild bcssChild, boolean delegatedServices) { + if (bcssChild.serviceRecords == null || bcssChild.serviceRecords.isEmpty()) { + return; + } + synchronized (bcssChild.child) { + Object records[] = bcssChild.serviceRecords.toArray(); + for (int i = 0; i < records.length; i++) { + ServiceRecord rec = (ServiceRecord)records[i]; + if (delegatedServices) { + if (rec.isDelegate) { + releaseServiceWithoutCheck(rec.child, bcssChild, rec.requestor, rec.service, true); + } + } else { + releaseServiceWithoutCheck(rec.child, bcssChild, rec.requestor, rec.service, false); + } + } + } + } + + /** Creates a BCSSChild object to company the given child. + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextSupport#createBCSChild(java.lang.Object, java.lang.Object) */ + protected BCSChild createBCSChild (Object child, Object proxyPeer) { + return new BCSSChild(child, proxyPeer); + } + + /** Creates a BCSSServiceProvider to company the given service. + * + * @param serviceClass the service class + * @param provider the service provider + * @return a BCSSServiceProvider to company the given service */ + protected BCSSServiceProvider createBCSSServiceProvider (Class serviceClass, BeanContextServiceProvider provider) { + return new BCSSServiceProvider(provider); + } + + /** Fires a BeanContextServiceAvailableEvent to registered BeanContextServicesListeners. + * + * @param serviceClass the service that has been added */ + protected final void fireServiceAdded (Class serviceClass) { + fireServiceAdded(new BeanContextServiceAvailableEvent(this, serviceClass)); + } + + /** Fires a BeanContextServiceAvailableEvent to registered BeanContextServicesListeners. + * + * @param event the event */ + protected final void fireServiceAdded (BeanContextServiceAvailableEvent event) { + Object listeners[]; + synchronized (bcsListeners) { + listeners = bcsListeners.toArray(); + } + for (int i = 0; i < listeners.length; i++) { + BeanContextServicesListener l = (BeanContextServicesListener)listeners[i]; + l.serviceAvailable(event); + } + } + + /** Fires a BeanContextServiceRevokedEvent to registered BeanContextServicesListeners. + * + * @param serviceClass the service that has been revoked + * @param revokeNow whether to terminate service immediately */ + protected final void fireServiceRevoked (Class serviceClass, boolean revokeNow) { + fireServiceRevoked(new BeanContextServiceRevokedEvent(this, serviceClass, revokeNow)); + } + + /** Fires a BeanContextServiceRevokedEvent to registered BeanContextServicesListeners. + * + * @param event the event */ + protected final void fireServiceRevoked (BeanContextServiceRevokedEvent event) { + Object listeners[]; + synchronized (bcsListeners) { + listeners = bcsListeners.toArray(); + } + for (int i = 0; i < listeners.length; i++) { + BeanContextServicesListener l = (BeanContextServicesListener)listeners[i]; + l.serviceRevoked(event); + } + } + + /** Returns the peer of this context casted as BeanContextServices. + * + * @return the peer of this context casted as BeanContextServices */ + public BeanContextServices getBeanContextServicesPeer () { + return (BeanContextServices)beanContextChildPeer; + } + + /** Returns the given child casted to BeanContextServicesListener, or null if it does not implements the interface. + * + * @param child a child + * @return the given child casted to BeanContextServicesListener, or null if it does not implements the interface */ + protected static final BeanContextServicesListener getChildBeanContextServicesListener (Object child) { + if (child instanceof BeanContextServicesListener) { + return (BeanContextServicesListener)child; + } + return null; + } + + /** Returns an iterator of all registered service classes, with removed() disabled. + * + * @return an iterator of all registered service classes + * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#getCurrentServiceClasses() */ + public Iterator getCurrentServiceClasses () { + synchronized (services) { + return new BCSIterator(services.keySet().iterator()); + } + } + + /** Returns the service selectors of the specified service. The iterator's remove() operation is disabled. + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#getCurrentServiceSelectors(java.lang.Class) */ + public Iterator getCurrentServiceSelectors (Class serviceClass) { + BeanContextServiceProvider provider = getLocalServiceProvider(serviceClass); + return provider == null ? null : new BCSIterator(provider.getCurrentServiceSelectors(getBeanContextServicesPeer(), + serviceClass)); + } + + private BeanContextServiceProvider getLocalServiceProvider (Class serviceClass) { + synchronized (services) { + BCSSServiceProvider bcssProvider = (BCSSServiceProvider)services.get(serviceClass); + if (bcssProvider != null) { + return bcssProvider.getServiceProvider(); + } + return null; + } + } + + /** Get a service instance on behalf of the specified child of this context, by calling the registered service provider, or by + * delegating to the parent context. + * + * @param child the child that request service + * @param requestor the requestor object + * @param serviceClass the service class + * @param serviceSelector the service selectors + * @param bcsrl the BeanContextServiceRevokedListener + * @return a service instance on behalf of the specified child of this context + * @throws IllegalArgumentException if child is not a child of this context + * @throws TooManyListenersException + * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#getService(com.badlogic.gdx.beans.beancontext.BeanContextChild, + * java.lang.Object, java.lang.Class, java.lang.Object, + * com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedListener) */ + public Object getService (BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, + BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { + if (child == null || requestor == null || serviceClass == null || bcsrl == null) { + throw new NullPointerException(); + } + + BCSSChild bcssChild = null; + BeanContextServiceProvider provider = null; + Object service = null; + boolean isDelegate = false; + + synchronized (globalHierarchyLock) { + // check child + synchronized (children) { + bcssChild = (BCSSChild)children.get(child); + } + if (bcssChild == null) { + throw new IllegalArgumentException(Messages.getString("beans.65")); + } + + // try local service + provider = getLocalServiceProvider(serviceClass); + if (provider != null) { + service = provider.getService(getBeanContextServicesPeer(), requestor, serviceClass, serviceSelector); + } + + // no local service, try delegate + if (service == null && proxy != null) { + provider = proxy; + service = proxy.getService(getBeanContextServicesPeer(), requestor, serviceClass, serviceSelector, bcsrl); + isDelegate = true; + } + } + + if (service != null) { + // save record + synchronized (child) { + if (bcssChild.serviceRecords == null) { + bcssChild.serviceRecords = new ArrayList(); + } + bcssChild.serviceRecords.add(new ServiceRecord(provider, child, requestor, serviceClass, bcsrl, service, isDelegate)); + } + } + + return service; + } + + /** Checks whether a service is registed in this context or the parent context. + * + * @param serviceClass the service class + * @return true if the service is registered + * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#hasService(java.lang.Class) */ + public boolean hasService (Class serviceClass) { + if (serviceClass == null) { + throw new NullPointerException(); + } + + boolean has; + synchronized (services) { + has = services.containsKey(serviceClass); + } + if (!has && getBeanContext() instanceof BeanContextServices) { + has = ((BeanContextServices)getBeanContext()).hasService(serviceClass); + } + return has; + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.beancontext.BeanContextSupport#initialize() + */ + public void initialize () { + super.initialize(); + services = new HashMap(); + serializable = 0; + proxy = null; + bcsListeners = new ArrayList(); + } + + /** Called after the parent context is updated. The implementation checks if the parent context is a + * BeanContextServices. If it is, then a BCSSProxyServiceProvider is created to delegate service + * requests to the parent context. + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextChildSupport#initializeBeanContextResources() */ + protected void initializeBeanContextResources () { + super.initializeBeanContextResources(); + + BeanContext context = getBeanContext(); + if (context instanceof BeanContextServices) { + proxy = new BCSSProxyServiceProvider((BeanContextServices)context); + } else { + proxy = null; + } + } + + /** Called before the parent context is updated. The implementation releases any service that is currently provided by the + * parent context. + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextChildSupport#releaseBeanContextResources() */ + protected void releaseBeanContextResources () { + super.releaseBeanContextResources(); + + releaseAllDelegatedServices(); + proxy = null; + } + + private void releaseAllDelegatedServices () { + synchronized (children) { + for (Iterator iter = bcsChildren(); iter.hasNext();) { + releaseServicesForChild((BCSSChild)iter.next(), true); + } + } + } + + /** Release a service which has been requested previously. + * + * @param child the child that request the service + * @param requestor the requestor object + * @param service the service instance + * @throws IllegalArgumentException if child is not a child of this context */ + public void releaseService (BeanContextChild child, Object requestor, Object service) { + if (child == null || requestor == null || service == null) { + throw new NullPointerException(); + } + + synchronized (globalHierarchyLock) { + BCSSChild bcssChild; + synchronized (children) { + bcssChild = (BCSSChild)children.get(child); + } + if (bcssChild == null) { + throw new IllegalArgumentException(Messages.getString("beans.65")); + } + + releaseServiceWithoutCheck(child, bcssChild, requestor, service, false); + } + } + + /** Releases a service without checking the membership of the child. */ + private void releaseServiceWithoutCheck (BeanContextChild child, BCSSChild bcssChild, Object requestor, Object service, + boolean callRevokedListener) { + + if (bcssChild.serviceRecords == null || bcssChild.serviceRecords.isEmpty()) { + return; + } + + synchronized (child) { + // scan record + for (Iterator iter = bcssChild.serviceRecords.iterator(); iter.hasNext();) { + ServiceRecord rec = (ServiceRecord)iter.next(); + if (rec.requestor == requestor && rec.service == service) { + // release service + rec.provider.releaseService(getBeanContextServicesPeer(), requestor, service); + // call service revoked listener + if (callRevokedListener && rec.revokedListener != null) { + rec.revokedListener.serviceRevoked(new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), + rec.serviceClass, true)); + } + // remove record + iter.remove(); + break; + } + } + } + } + + /* + * (non-Javadoc) + * + * @see + * com.esotericsoftware.android.beans.beancontext.BeanContextServices#removeBeanContextServicesListener(com.esotericsoftware + * .android.beans.beancontext.BeanContextServicesListener) + */ + public void removeBeanContextServicesListener (BeanContextServicesListener listener) { + if (listener == null) { + throw new NullPointerException(); + } + synchronized (bcsListeners) { + bcsListeners.remove(listener); + } + } + + /** Revokes a service in this bean context. + *

        + * The given service provider is unregistered and a BeanContextServiceRevokedEvent is fired. All registered + * service listeners and current service users get notified. + *

        + * + * @param serviceClass the service class + * @param serviceProvider the service provider + * @param revokeCurrentServicesNow true if service should be terminated immediantly + * @see com.badlogic.gdx.beans.beancontext.BeanContextServices#revokeService(java.lang.Class, + * com.badlogic.gdx.beans.beancontext.BeanContextServiceProvider, boolean) */ + public void revokeService (Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow) { + if (serviceClass == null || serviceProvider == null) { + throw new NullPointerException(); + } + + synchronized (globalHierarchyLock) { + synchronized (services) { + BCSSServiceProvider bcssProvider = (BCSSServiceProvider)services.get(serviceClass); + if (bcssProvider == null) { // non-exist service + return; + } + if (bcssProvider.getServiceProvider() != serviceProvider) { + throw new IllegalArgumentException(Messages.getString("beans.66")); + } + + services.remove(serviceClass); + + if (serviceProvider instanceof Serializable) { + serializable--; + } + } + } + + // notify listeners + fireServiceRevoked(serviceClass, revokeCurrentServicesNow); + + // notify service users + notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider, revokeCurrentServicesNow); + } + + /** Notify all children that a service has been revoked. */ + private void notifyServiceRevokedToServiceUsers (Class serviceClass, BeanContextServiceProvider serviceProvider, + boolean revokeCurrentServicesNow) { + synchronized (children) { + for (Iterator iter = bcsChildren(); iter.hasNext();) { + BCSSChild bcssChild = (BCSSChild)iter.next(); + notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider, revokeCurrentServicesNow, bcssChild); + } + } + } + + /** Notify the given child that a service has been revoked. */ + private void notifyServiceRevokedToServiceUsers (Class serviceClass, BeanContextServiceProvider serviceProvider, + boolean revokeCurrentServicesNow, BCSSChild bcssChild) { + if (bcssChild.serviceRecords == null || bcssChild.serviceRecords.isEmpty()) { + return; + } + synchronized (bcssChild.child) { + for (Iterator it = bcssChild.serviceRecords.iterator(); it.hasNext();) { + ServiceRecord rec = (ServiceRecord)it.next(); + if (rec.serviceClass == serviceClass && rec.provider == serviceProvider && rec.revokedListener != null + && !rec.isDelegate) { + rec.revokedListener.serviceRevoked(new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), serviceClass, + revokeCurrentServicesNow)); + // prevent duplicate notification + rec.revokedListener = null; + } + } + } + } + + /** Notify all listeners and children that implements BeanContextServices of the event. + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextServicesListener#serviceAvailable(com.badlogic.gdx.beans.beancontext.BeanContextServiceAvailableEvent) */ + public void serviceAvailable (BeanContextServiceAvailableEvent event) { + if (null == event) { + throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$ + } + if (services.containsKey(event.serviceClass)) { + return; + } + fireServiceAdded(event); + Object childs[] = copyChildren(); + for (int i = 0; i < childs.length; i++) { + if (childs[i] instanceof BeanContextServices) { + ((BeanContextServices)childs[i]).serviceAvailable(event); + } + } + } + + /** Notify all listeners and children that implements BeanContextServices of the event. + * + * @see com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedListener#serviceRevoked(com.badlogic.gdx.beans.beancontext.BeanContextServiceRevokedEvent) */ + public void serviceRevoked (BeanContextServiceRevokedEvent event) { + if (null == event) { + throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$ + } + if (services.containsKey(event.serviceClass)) { + return; + } + fireServiceRevoked(event); + Object childs[] = copyChildren(); + for (int i = 0; i < childs.length; i++) { + if (childs[i] instanceof BeanContextServices) { + ((BeanContextServices)childs[i]).serviceRevoked(event); + } + } + } + + /** The implementation goes through following steps: + *

        + *

          + *
        1. Calls defaultWriteObject().
        2. + *
        3. Writes out serializable service listeners.
        4. + *
        + *

        + * + * @param oos the object output stream + * @throws IOException if I/O exception occurs */ + private void writeObject (ObjectOutputStream oos) throws IOException { + + oos.defaultWriteObject(); + + synchronized (bcsListeners) { + serialize(oos, bcsListeners); + } + } + + /** The implementation goes through following steps: + *

        + *

          + *
        1. Calls defaultReadObject().
        2. + *
        3. Reads serializable service listeners.
        4. + *
        + *

        + * + * @param ois the object input stream + * @throws IOException if I/O error occurs + * @throws ClassNotFoundException if class of read object is not found */ + private void readObject (ObjectInputStream ois) throws IOException, ClassNotFoundException { + + ois.defaultReadObject(); + + synchronized (bcsListeners) { + deserialize(ois, bcsListeners); + } + } } diff --git a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextSupport.java b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextSupport.java index 2e214615621..32b08d468c6 100644 --- a/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextSupport.java +++ b/extensions/beans/src/com/badlogic/gdx/beans/beancontext/BeanContextSupport.java @@ -18,21 +18,6 @@ package com.badlogic.gdx.beans.beancontext; import java.awt.Component; - -import com.badlogic.gdx.beans.Beans; -import com.badlogic.gdx.beans.PropertyChangeEvent; -import com.badlogic.gdx.beans.PropertyChangeListener; -import com.badlogic.gdx.beans.PropertyVetoException; -import com.badlogic.gdx.beans.VetoableChangeListener; -import com.badlogic.gdx.beans.Visibility; -import com.badlogic.gdx.beans.beancontext.BeanContext; -import com.badlogic.gdx.beans.beancontext.BeanContextChild; -import com.badlogic.gdx.beans.beancontext.BeanContextChildSupport; -import com.badlogic.gdx.beans.beancontext.BeanContextMembershipEvent; -import com.badlogic.gdx.beans.beancontext.BeanContextMembershipListener; -import com.badlogic.gdx.beans.beancontext.BeanContextProxy; -import com.badlogic.gdx.beans.beancontext.BeanContextSupport; - import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; @@ -47,1292 +32,1125 @@ import org.apache.harmony.beans.internal.nls.Messages; +import com.badlogic.gdx.beans.Beans; +import com.badlogic.gdx.beans.PropertyChangeEvent; +import com.badlogic.gdx.beans.PropertyChangeListener; +import com.badlogic.gdx.beans.PropertyVetoException; +import com.badlogic.gdx.beans.VetoableChangeListener; +import com.badlogic.gdx.beans.Visibility; -/** - * This support class implements BeanContext interface. - * This class can be used directly, or be a super class of your class, - * or be a delegate of your implementation that needs to support - * BeanContext interface. - * - */ -public class BeanContextSupport extends BeanContextChildSupport implements - BeanContext, PropertyChangeListener, VetoableChangeListener, - Serializable { - - /** - * Every child of context is companied with a BCSChild - * instance. It can hold implementation specific information about - * each child. - *

        - * This class holds references of the child and its peer if there is one.

        - * - */ - protected class BCSChild implements Serializable { - - private static final long serialVersionUID = -5815286101609939109L; - - Object child; - - Object proxyPeer; - - BCSChild(Object child, Object proxyPeer) { - this.child = child; - this.proxyPeer = proxyPeer; - } - } - - /** - * This implementation wraps an iterator and override - * remove() with a noop method. - * - */ - protected static final class BCSIterator implements Iterator { - - private Iterator backIter; - - BCSIterator(Iterator backIter) { - this.backIter = backIter; - } - - public boolean hasNext() { - return backIter.hasNext(); - } - - public Object next() { - return backIter.next(); - } - - public void remove() { - // no-op - } - } - - private static final long serialVersionUID = -4879613978649577204L; //J2SE 1.4.2 - - /** - * A list of registered membership listeners. - * All access to this object should be synchronized on itself. - */ - @SuppressWarnings("unchecked") - transient protected ArrayList bcmListeners; - - /** - * A map of children - key is child instance, value is BCSChild instance. - * All access to this object should be synchronized on itself. - */ - @SuppressWarnings("unchecked") - transient protected HashMap children; - - transient private boolean serializing; - - transient private boolean inNeedsGui; - - transient private PropertyChangeListener nonSerPCL; - - private int serializable; - - /** - * The locale of this context. - */ - protected Locale locale; - - /** - * A flag indicating whether this context is allowed to use GUI. - */ - protected boolean okToUseGui; - - /** - * A flag indicating whether this context is in design mode. - */ - protected boolean designTime; - - /** - * Constructs a standload BeanContextSupport. - */ - public BeanContextSupport() { - this(null, Locale.getDefault(), false, true); - } - - /** - * Constructs a BeanContextSupport which is a delegate - * of the given peer. - * - * @param peer the peer of this context - */ - public BeanContextSupport(BeanContext peer) { - this(peer, Locale.getDefault(), false, true); - } - - /** - * Constructs a BeanContextSupport which is a delegate - * of the given peer. - * - * @param peer the peer of this context - * @param locale the locale of this context - */ - public BeanContextSupport(BeanContext peer, Locale locale) { - this(peer, locale, false, true); - } - - /** - * Constructs a BeanContextSupport which is a delegate - * of the given peer. - * - * @param peer the peer of this context - * @param locale the locale of this context - * @param designTime whether in design mode or not - */ - public BeanContextSupport(BeanContext peer, Locale locale, - boolean designTime) { - this(peer, locale, designTime, true); - } - - /** - * Constructs a BeanContextSupport which is a delegate - * of the given peer. - * - * @param peer the peer of this context - * @param locale the locale of this context - * @param designTime whether in design mode or not - * @param okToUseGui whether GUI is usable or not - */ - public BeanContextSupport(BeanContext peer, Locale locale, - boolean designTime, boolean okToUseGui) { - super(peer); - if (locale == null) { - locale = Locale.getDefault(); - } - this.locale = locale; - this.designTime = designTime; - this.okToUseGui = okToUseGui; - - initialize(); - } - - /** - * Add a child to this context. - *

        - * If the child already exists in this context, simply returns false. - * Otherwise, it is validated by calling validatePendingAdd(). - * If the add is valid, the child and its proxy (if the child implements - * BeanContextProxy) is then added, and setBeanContext() - * is called on it (if the child implements BeanContextChild - * or it has a proxy). Last, the childJustAddedHook() is - * called and all registered BeanContextMembershipListeners - * are notified.

        - * - * @param child the child to add - * @return true if the child is added to this context; otherwise false - * @throws IllegalStateException if the child is not valid to add - * @see java.util.Collection#add(java.lang.Object) - */ - @SuppressWarnings("unchecked") - public boolean add(Object child) { - if (child == null) { - throw new IllegalArgumentException(Messages.getString("beans.67")); - } - - BeanContextChild proxy = null; - - synchronized (globalHierarchyLock) { - // check existence - if (contains(child)) { - return false; - } - - // check serializing state - if (serializing) { - throw new IllegalStateException( - Messages.getString("beans.68")); - } - - // validate - boolean valid = validatePendingAdd(child); - if (!valid) { - throw new IllegalStateException( - Messages.getString("beans.69")); - } - - // find the proxy, if there's one - if (child instanceof BeanContextProxy) { - proxy = ((BeanContextProxy) child).getBeanContextProxy(); - if (proxy == null) { - throw new NullPointerException( - Messages.getString("beans.6A")); - } - } - BeanContextChild beanContextChild = getChildBeanContextChild(child); - - // add to children - BCSChild childBCSC = null, proxyBCSC = null; - synchronized (children) { - childBCSC = createBCSChild(child, proxy); - children.put(child, childBCSC); - if (proxy != null) { - proxyBCSC = createBCSChild(proxy, child); - children.put(proxy, proxyBCSC); - } - } - - // set child's beanContext property - if (beanContextChild != null) { - try { - beanContextChild.setBeanContext(getBeanContextPeer()); - } catch (PropertyVetoException e) { - synchronized (children) { - children.remove(child); - if (proxy != null) { - children.remove(proxy); - } - } - throw new IllegalStateException( - Messages.getString("beans.6B")); - } - // ensure no duplicate listener - beanContextChild.removePropertyChangeListener("beanContext", - nonSerPCL); - // listen to child's beanContext change - beanContextChild.addPropertyChangeListener("beanContext", - nonSerPCL); - } - - // trigger hook - synchronized (child) { - addSerializable(childBCSC); - childJustAddedHook(child, childBCSC); - } - if (proxy != null) { - synchronized (proxy) { - addSerializable(proxyBCSC); - childJustAddedHook(proxy, proxyBCSC); - } - } - } - - // notify listeners - fireChildrenAdded(new BeanContextMembershipEvent(getBeanContextPeer(), - proxy == null ? new Object[] { child } : new Object[] { child, - proxy })); - return true; - } - - /** - * This method is unsupported, throws UnsupportedOperationException. - * - * @see java.util.Collection#addAll(java.util.Collection) - */ - public boolean addAll(Collection collection) { - throw new UnsupportedOperationException(); - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.beancontext.BeanContext#addBeanContextMembershipListener(com.esotericsoftware.android.beans.beancontext.BeanContextMembershipListener) - */ - public void addBeanContextMembershipListener( - BeanContextMembershipListener listener) { - if (listener == null) { - throw new NullPointerException(); - } - synchronized (bcmListeners) { - if (!bcmListeners.contains(listener)) { - bcmListeners.add(listener); - } - } - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.Visibility#avoidingGui() - */ - public boolean avoidingGui() { - // Avoiding GUI means that - // GUI is needed but not allowed to use at this time - return (needsGui() && !this.okToUseGui); - } - - /** - * Returns an iterator of all BCSChild instances, - * with remove() disabled. - * - * @return an iterator of all BCSChild instances - */ - protected Iterator bcsChildren() { - synchronized (children) { - return new BCSIterator(children.values().iterator()); - } - } - - /** - * This method is called by readObject() after - * defaultReadObject() and before deserializing any - * children or listeners. Subclass can insert its specific - * deserialization behavior by overrideing this method. - *

        - * The default implementation does nothing.

        - * - * @param ois the object input stream - * @throws IOException - * @throws ClassNotFoundException - */ - protected void bcsPreDeserializationHook(ObjectInputStream ois) - throws IOException, ClassNotFoundException { - // to be overridden - } - - /** - * This method is called by writeObject() after - * defaultWriteObject() and before serializing any - * children or listeners. Subclass can insert its specific - * serialization behavior by overrideing this method. - *

        - * The default implementation does nothing.

        - * - * @param oos the object output stream - * @throws IOException - */ - protected void bcsPreSerializationHook(ObjectOutputStream oos) - throws IOException { - // to be overridden - } - - /** - * This method is called during deserialization everytime a child is read. - *

        - * The default implementation does nothing.

        - * - * @param child the child just deserialized - * @param bcsChild the BCSChild just deserialized - */ - protected void childDeserializedHook(Object child, BCSChild bcsChild) { - // to be overridden - } - - /** - * This method is called everytime a child is added to this context. - * This method is called with child synchronized. - *

        - * The default implementation does nothing.

        - * - * @param child the child just added - * @param bcsChild the BCSChild just added - */ - protected void childJustAddedHook(Object child, BCSChild bcsChild) { - // to be overridden - } - - /** - * This method is called everytime a child is removed from this context. - * This method is called with child synchronized. - *

        - * The default implementation does nothing.

        - * - * @param child the child just removed - * @param bcsChild the BCSChild just removed - */ - protected void childJustRemovedHook(Object child, BCSChild bcsChild) { - // to be overridden - } - - /** - * Compares if two classes are equal or their class names are equal. - * - * @param clz1 a class - * @param clz2 another class - * @return true if two class objects are equal or their class names are equal. - */ - protected static final boolean classEquals(Class clz1, Class clz2) { - if (clz1 == null || clz2 == null) { - throw new NullPointerException(); - } - return clz1 == clz2 || clz1.getName().equals(clz2.getName()); - } - - /** - * This method is unsupported, throws UnsupportedOperationException. - * - * @see java.util.Collection#clear() - */ - public void clear() { - throw new UnsupportedOperationException(); - } - - /** - * Returns true if the given object is a child of this context. - * - * @param child the object to test - * @return true if the given object is a child of this context - * @see java.util.Collection#contains(java.lang.Object) - */ - public boolean contains(Object child) { - synchronized (children) { - return children.containsKey(child); - } - } - - /** - * Returns true if given objects are children of this context. - * - * @param collection a collection of objects - * @return true if given objects are children of this context - * @see java.util.Collection#containsAll(java.util.Collection) - */ - @SuppressWarnings("unchecked") - public boolean containsAll(Collection collection) { - synchronized (children) { - return children.keySet().containsAll(collection); - } - } - - /** - * Returns true if the given object is a child of this context. - * - * @param child the object to test - * @return true if the given object is a child of this context - */ - public boolean containsKey(Object child) { - synchronized (children) { - return children.containsKey(child); - } - } - - /** - * Returns an array containing all children of this context. - * - * @return an array containing all children of this context - */ - protected final Object[] copyChildren() { - synchronized (children) { - return children.keySet().toArray(); - } - } - - /** - * Creates a BCSChild object to company the given child. - * - * @param child the child - * @param proxyPeer the proxy peer of the child if there is one - * @return a BCSChild object to company the given child - */ - protected BCSChild createBCSChild(Object child, Object proxyPeer) { - return new BCSChild(child, proxyPeer); - } - - /** - * Deserialize a collection. - *

        - * First read a int indicating of number of rest objects, - * then read the objects one by one.

        - * - * @param ois the stream where the collection is read from - * @param collection the collection to hold read objects - * @throws IOException if I/O exception occurs - * @throws ClassNotFoundException if class of any read object is not found - */ - @SuppressWarnings("unchecked") - protected final void deserialize(ObjectInputStream ois, - Collection collection) throws IOException, ClassNotFoundException { - int size = ois.readInt(); - for (int i = 0; i < size; i++) { - collection.add(ois.readObject()); - } - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.Visibility#dontUseGui() - */ - public void dontUseGui() { - okToUseGui = false; - } - - /** - * Notifies registered BeanContextMembershipListeners that - * a new child has been added. - * - * @param event the BeanContextMembershipEvent - */ - protected final void fireChildrenAdded(BeanContextMembershipEvent event) { - Object listeners[]; - synchronized (bcmListeners) { - listeners = bcmListeners.toArray(); - } - for (int i = 0; i < listeners.length; i++) { - BeanContextMembershipListener l = (BeanContextMembershipListener) listeners[i]; - l.childrenAdded(event); - } - } - - /** - * Notifies registered BeanContextMembershipListeners that - * a child has been removed. - * - * @param event the BeanContextMembershipEvent - */ - protected final void fireChildrenRemoved(BeanContextMembershipEvent event) { - Object listeners[]; - synchronized (bcmListeners) { - listeners = bcmListeners.toArray(); - } - for (int i = 0; i < listeners.length; i++) { - BeanContextMembershipListener l = (BeanContextMembershipListener) listeners[i]; - l.childrenRemoved(event); - } - } - - /** - * Returns the peer of this context casted as BeanContext. - * - * @return the peer of this context casted as BeanContext - */ - public BeanContext getBeanContextPeer() { - return (BeanContext) beanContextChildPeer; - } - - /** - * Returns the BeanContextChild related with the given child. - *

        - * If the child implements BeanContextChild, it is returned. - * If the child implements BeanContextProxy, the proxy is returned. - * Otherwise, null is returned.

        - * - * @param child a child - * @return the BeanContextChild related with the given child - * @throws IllegalStateException if the child implements both BeanContextChild and BeanContextProxy - */ - protected static final BeanContextChild getChildBeanContextChild( - Object child) { - if (child instanceof BeanContextChild) { - if (child instanceof BeanContextProxy) { - throw new IllegalArgumentException( - Messages.getString("beans.6C")); - } - return (BeanContextChild) child; - } - if (child instanceof BeanContextProxy) { - if (child instanceof BeanContextChild) { - throw new IllegalArgumentException( - Messages.getString("beans.6C")); - } - return ((BeanContextProxy) child).getBeanContextProxy(); - } - return null; - } - - /** - * Returns the given child casted to BeanContextMembershipListener, - * or null if it does not implements the interface. - * - * @param child a child - * @return the given child casted to BeanContextMembershipListener, - * or null if it does not implements the interface - */ - protected static final BeanContextMembershipListener getChildBeanContextMembershipListener( - Object child) { - if (child instanceof BeanContextMembershipListener) { - return (BeanContextMembershipListener) child; - } else { - return null; - } - } - - /** - * Returns the given child casted to PropertyChangeListener, - * or null if it does not implements the interface. - * - * @param child a child - * @return the given child casted to PropertyChangeListener, - * or null if it does not implements the interface - */ - protected static final PropertyChangeListener getChildPropertyChangeListener( - Object child) { - if (child instanceof PropertyChangeListener) { - return (PropertyChangeListener) child; - } else { - return null; - } - } - - /** - * Returns the given child casted to Serializable, - * or null if it does not implements the interface. - * - * @param child a child - * @return the given child casted to Serializable, - * or null if it does not implements the interface - */ - protected static final Serializable getChildSerializable(Object child) { - if (child instanceof Serializable) { - return (Serializable) child; - } else { - return null; - } - } - - /** - * Returns the given child casted to VetoableChangeListener, - * or null if it does not implements the interface. - * - * @param child a child - * @return the given child casted to VetoableChangeListener, - * or null if it does not implements the interface - */ - protected static final VetoableChangeListener getChildVetoableChangeListener( - Object child) { - if (child instanceof VetoableChangeListener) { - return (VetoableChangeListener) child; - } else { - return null; - } - } - - /** - * Returns the given child casted to Visibility, - * or null if it does not implements the interface. - * - * @param child a child - * @return the given child casted to Visibility, - * or null if it does not implements the interface - */ - protected static final Visibility getChildVisibility(Object child) { - if (child instanceof Visibility) { - return (Visibility) child; - } else { - return null; - } - } - - /** - * Returns the locale of this context. - * - * @return the locale of this context - */ - public Locale getLocale() { - return locale; - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.beancontext.BeanContext#getResource(java.lang.String, com.esotericsoftware.android.beans.beancontext.BeanContextChild) - */ - public URL getResource(String resourceName, BeanContextChild child) { - if (resourceName == null || child == null) { - throw new NullPointerException(); - } - if (!contains(child)) { - throw new IllegalArgumentException(Messages.getString("beans.6D")); - } - - return ClassLoader.getSystemResource(resourceName); - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.beancontext.BeanContext#getResourceAsStream(java.lang.String, com.esotericsoftware.android.beans.beancontext.BeanContextChild) - */ - public InputStream getResourceAsStream(String resourceName, - BeanContextChild child) throws IllegalArgumentException { - if (resourceName == null || child == null) { - throw new NullPointerException(); - } - if (!contains(child)) { - throw new IllegalArgumentException(Messages.getString("beans.6D")); - } - - return ClassLoader.getSystemResourceAsStream(resourceName); - } - - /** - * Initializes all transient fields of this instance, called by - * constructors and readObject(). - */ - protected void initialize() { - // init transient fields - bcmListeners = new ArrayList(); - children = new HashMap(); - serializing = false; - inNeedsGui = false; - nonSerPCL = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - BeanContextSupport.this.propertyChange(event); - } - }; - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.beancontext.BeanContext#instantiateChild(java.lang.String) - */ - public Object instantiateChild(String beanName) throws IOException, - ClassNotFoundException { - return Beans.instantiate(getClass().getClassLoader(), beanName, - getBeanContextPeer()); - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.DesignMode#isDesignTime() - */ - public boolean isDesignTime() { - return designTime; - } - - /* (non-Javadoc) - * @see java.util.Collection#isEmpty() - */ - public boolean isEmpty() { - synchronized (children) { - return children.isEmpty(); - } - } - - /** - * Returns true if this context is currently being serialized - * (by another thread). - * - * @return true if this context is currently being serialized - * (by another thread) - */ - public boolean isSerializing() { - return serializing; - } - - /** - * Returns an iterator of children of this context, - * with remove() disabled. - * - * @see java.util.Collection#iterator() - */ - public Iterator iterator() { - synchronized (children) { - return new BCSIterator(children.keySet().iterator()); - } - } - - /** - * Returns true if this context or its children needs GUI to work properly. - *

        - * The implementation checks the peer and all the children that implement - * Visibility to see if any of their needsGui() - * returns true, and if any of the children extends - * java.awt.Component.

        - * - * @see com.badlogic.gdx.beans.Visibility#needsGui() - */ - public boolean needsGui() { - if (inNeedsGui) { - return false; - } - inNeedsGui = true; - - try { - if (getBeanContextPeer() != this) { - if (getBeanContextPeer().needsGui()) { - return true; - } - } - Object childs[] = copyChildren(); - for (int i = 0; i < childs.length; i++) { - if (childs[i] instanceof Component) { - return true; - } - Visibility v = getChildVisibility(childs[i]); - if (v != null && v.needsGui()) { - return true; - } - } - return false; - } finally { - inNeedsGui = false; - } - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.Visibility#okToUseGui() - */ - public void okToUseGui() { - okToUseGui = true; - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.PropertyChangeListener#propertyChange(com.esotericsoftware.android.beans.PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - if (contains(event.getSource()) - && "beanContext".equals(event.getPropertyName()) - && event.getOldValue() == getBeanContextPeer()) { - remove(event.getSource(), false); - } - } - - /** - * Deserializes children from the given object input stream. +/** This support class implements BeanContext interface. This class can be used directly, or be a super class of your + * class, or be a delegate of your implementation that needs to support BeanContext interface. */ +public class BeanContextSupport extends BeanContextChildSupport implements BeanContext, PropertyChangeListener, + VetoableChangeListener, Serializable { + + /** Every child of context is companied with a BCSChild instance. It can hold implementation specific information + * about each child. + *

        + * This class holds references of the child and its peer if there is one. + *

        */ + protected class BCSChild implements Serializable { + + private static final long serialVersionUID = -5815286101609939109L; + + Object child; + + Object proxyPeer; + + BCSChild (Object child, Object proxyPeer) { + this.child = child; + this.proxyPeer = proxyPeer; + } + } + + /** This implementation wraps an iterator and override remove() with a noop method. */ + protected static final class BCSIterator implements Iterator { + + private Iterator backIter; + + BCSIterator (Iterator backIter) { + this.backIter = backIter; + } + + public boolean hasNext () { + return backIter.hasNext(); + } + + public Object next () { + return backIter.next(); + } + + public void remove () { + // no-op + } + } + + private static final long serialVersionUID = -4879613978649577204L; // J2SE 1.4.2 + + /** A list of registered membership listeners. All access to this object should be synchronized on itself. */ + @SuppressWarnings("unchecked") + transient protected ArrayList bcmListeners; + + /** A map of children - key is child instance, value is BCSChild instance. All access to this object should be + * synchronized on itself. */ + @SuppressWarnings("unchecked") + transient protected HashMap children; + + transient private boolean serializing; + + transient private boolean inNeedsGui; + + transient private PropertyChangeListener nonSerPCL; + + private int serializable; + + /** The locale of this context. */ + protected Locale locale; + + /** A flag indicating whether this context is allowed to use GUI. */ + protected boolean okToUseGui; + + /** A flag indicating whether this context is in design mode. */ + protected boolean designTime; + + /** Constructs a standload BeanContextSupport. */ + public BeanContextSupport () { + this(null, Locale.getDefault(), false, true); + } + + /** Constructs a BeanContextSupport which is a delegate of the given peer. + * + * @param peer the peer of this context */ + public BeanContextSupport (BeanContext peer) { + this(peer, Locale.getDefault(), false, true); + } + + /** Constructs a BeanContextSupport which is a delegate of the given peer. + * + * @param peer the peer of this context + * @param locale the locale of this context */ + public BeanContextSupport (BeanContext peer, Locale locale) { + this(peer, locale, false, true); + } + + /** Constructs a BeanContextSupport which is a delegate of the given peer. + * + * @param peer the peer of this context + * @param locale the locale of this context + * @param designTime whether in design mode or not */ + public BeanContextSupport (BeanContext peer, Locale locale, boolean designTime) { + this(peer, locale, designTime, true); + } + + /** Constructs a BeanContextSupport which is a delegate of the given peer. + * + * @param peer the peer of this context + * @param locale the locale of this context + * @param designTime whether in design mode or not + * @param okToUseGui whether GUI is usable or not */ + public BeanContextSupport (BeanContext peer, Locale locale, boolean designTime, boolean okToUseGui) { + super(peer); + if (locale == null) { + locale = Locale.getDefault(); + } + this.locale = locale; + this.designTime = designTime; + this.okToUseGui = okToUseGui; + + initialize(); + } + + /** Add a child to this context. *

        - * The implementation reads pairs of child object and BCSChild - * object according to serializable property. For each pair, - * it is added to the children map and the - * childDeserializedHook() is called. If the child implements - * BeanContextChild, its setBeanContext() is - * also called. + * If the child already exists in this context, simply returns false. Otherwise, it is validated by calling + * validatePendingAdd(). If the add is valid, the child and its proxy (if the child implements + * BeanContextProxy) is then added, and setBeanContext() is called on it (if the child implements + * BeanContextChild or it has a proxy). Last, the childJustAddedHook() is called and all registered + * BeanContextMembershipListeners are notified. *

        + * + * @param child the child to add + * @return true if the child is added to this context; otherwise false + * @throws IllegalStateException if the child is not valid to add + * @see java.util.Collection#add(java.lang.Object) */ + @SuppressWarnings("unchecked") + public boolean add (Object child) { + if (child == null) { + throw new IllegalArgumentException(Messages.getString("beans.67")); + } + + BeanContextChild proxy = null; + + synchronized (globalHierarchyLock) { + // check existence + if (contains(child)) { + return false; + } + + // check serializing state + if (serializing) { + throw new IllegalStateException(Messages.getString("beans.68")); + } + + // validate + boolean valid = validatePendingAdd(child); + if (!valid) { + throw new IllegalStateException(Messages.getString("beans.69")); + } + + // find the proxy, if there's one + if (child instanceof BeanContextProxy) { + proxy = ((BeanContextProxy)child).getBeanContextProxy(); + if (proxy == null) { + throw new NullPointerException(Messages.getString("beans.6A")); + } + } + BeanContextChild beanContextChild = getChildBeanContextChild(child); + + // add to children + BCSChild childBCSC = null, proxyBCSC = null; + synchronized (children) { + childBCSC = createBCSChild(child, proxy); + children.put(child, childBCSC); + if (proxy != null) { + proxyBCSC = createBCSChild(proxy, child); + children.put(proxy, proxyBCSC); + } + } + + // set child's beanContext property + if (beanContextChild != null) { + try { + beanContextChild.setBeanContext(getBeanContextPeer()); + } catch (PropertyVetoException e) { + synchronized (children) { + children.remove(child); + if (proxy != null) { + children.remove(proxy); + } + } + throw new IllegalStateException(Messages.getString("beans.6B")); + } + // ensure no duplicate listener + beanContextChild.removePropertyChangeListener("beanContext", nonSerPCL); + // listen to child's beanContext change + beanContextChild.addPropertyChangeListener("beanContext", nonSerPCL); + } + + // trigger hook + synchronized (child) { + addSerializable(childBCSC); + childJustAddedHook(child, childBCSC); + } + if (proxy != null) { + synchronized (proxy) { + addSerializable(proxyBCSC); + childJustAddedHook(proxy, proxyBCSC); + } + } + } + + // notify listeners + fireChildrenAdded(new BeanContextMembershipEvent(getBeanContextPeer(), proxy == null ? new Object[] {child} : new Object[] { + child, proxy})); + return true; + } + + /** This method is unsupported, throws UnsupportedOperationException. + * + * @see java.util.Collection#addAll(java.util.Collection) */ + public boolean addAll (Collection collection) { + throw new UnsupportedOperationException(); + } + + /* + * (non-Javadoc) + * + * @see + * com.esotericsoftware.android.beans.beancontext.BeanContext#addBeanContextMembershipListener(com.esotericsoftware.android + * .beans.beancontext.BeanContextMembershipListener) + */ + public void addBeanContextMembershipListener (BeanContextMembershipListener listener) { + if (listener == null) { + throw new NullPointerException(); + } + synchronized (bcmListeners) { + if (!bcmListeners.contains(listener)) { + bcmListeners.add(listener); + } + } + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.Visibility#avoidingGui() + */ + public boolean avoidingGui () { + // Avoiding GUI means that + // GUI is needed but not allowed to use at this time + return (needsGui() && !this.okToUseGui); + } + + /** Returns an iterator of all BCSChild instances, with remove() disabled. + * + * @return an iterator of all BCSChild instances */ + protected Iterator bcsChildren () { + synchronized (children) { + return new BCSIterator(children.values().iterator()); + } + } + + /** This method is called by readObject() after defaultReadObject() and before deserializing any + * children or listeners. Subclass can insert its specific deserialization behavior by overrideing this method. *

        - * This method is called by readObject() if the context works - * standalone. Or if this support object is a delegate of another - * BeanContext implementation, then this method should be - * called by the peer. Doing this means that derialization can proceed - * without any circular dependency problems. + * The default implementation does nothing. + *

        * - * @param ois - * the object input stream + * @param ois the object input stream * @throws IOException - * if I/O exception occurs - * @throws ClassNotFoundException - * if class of read object is not found + * @throws ClassNotFoundException */ + protected void bcsPreDeserializationHook (ObjectInputStream ois) throws IOException, ClassNotFoundException { + // to be overridden + } + + /** This method is called by writeObject() after defaultWriteObject() and before serializing any + * children or listeners. Subclass can insert its specific serialization behavior by overrideing this method. + *

        + * The default implementation does nothing. + *

        + * + * @param oos the object output stream + * @throws IOException */ + protected void bcsPreSerializationHook (ObjectOutputStream oos) throws IOException { + // to be overridden + } + + /** This method is called during deserialization everytime a child is read. + *

        + * The default implementation does nothing. + *

        + * + * @param child the child just deserialized + * @param bcsChild the BCSChild just deserialized */ + protected void childDeserializedHook (Object child, BCSChild bcsChild) { + // to be overridden + } + + /** This method is called everytime a child is added to this context. This method is called with child synchronized. + *

        + * The default implementation does nothing. + *

        + * + * @param child the child just added + * @param bcsChild the BCSChild just added */ + protected void childJustAddedHook (Object child, BCSChild bcsChild) { + // to be overridden + } + + /** This method is called everytime a child is removed from this context. This method is called with child synchronized. + *

        + * The default implementation does nothing. + *

        + * + * @param child the child just removed + * @param bcsChild the BCSChild just removed */ + protected void childJustRemovedHook (Object child, BCSChild bcsChild) { + // to be overridden + } + + /** Compares if two classes are equal or their class names are equal. + * + * @param clz1 a class + * @param clz2 another class + * @return true if two class objects are equal or their class names are equal. */ + protected static final boolean classEquals (Class clz1, Class clz2) { + if (clz1 == null || clz2 == null) { + throw new NullPointerException(); + } + return clz1 == clz2 || clz1.getName().equals(clz2.getName()); + } + + /** This method is unsupported, throws UnsupportedOperationException. + * + * @see java.util.Collection#clear() */ + public void clear () { + throw new UnsupportedOperationException(); + } + + /** Returns true if the given object is a child of this context. + * + * @param child the object to test + * @return true if the given object is a child of this context + * @see java.util.Collection#contains(java.lang.Object) */ + public boolean contains (Object child) { + synchronized (children) { + return children.containsKey(child); + } + } + + /** Returns true if given objects are children of this context. + * + * @param collection a collection of objects + * @return true if given objects are children of this context + * @see java.util.Collection#containsAll(java.util.Collection) */ + @SuppressWarnings("unchecked") + public boolean containsAll (Collection collection) { + synchronized (children) { + return children.keySet().containsAll(collection); + } + } + + /** Returns true if the given object is a child of this context. + * + * @param child the object to test + * @return true if the given object is a child of this context */ + public boolean containsKey (Object child) { + synchronized (children) { + return children.containsKey(child); + } + } + + /** Returns an array containing all children of this context. + * + * @return an array containing all children of this context */ + protected final Object[] copyChildren () { + synchronized (children) { + return children.keySet().toArray(); + } + } + + /** Creates a BCSChild object to company the given child. + * + * @param child the child + * @param proxyPeer the proxy peer of the child if there is one + * @return a BCSChild object to company the given child */ + protected BCSChild createBCSChild (Object child, Object proxyPeer) { + return new BCSChild(child, proxyPeer); + } + + /** Deserialize a collection. + *

        + * First read a int indicating of number of rest objects, then read the objects one by one. + *

        + * + * @param ois the stream where the collection is read from + * @param collection the collection to hold read objects + * @throws IOException if I/O exception occurs + * @throws ClassNotFoundException if class of any read object is not found */ + @SuppressWarnings("unchecked") + protected final void deserialize (ObjectInputStream ois, Collection collection) throws IOException, ClassNotFoundException { + int size = ois.readInt(); + for (int i = 0; i < size; i++) { + collection.add(ois.readObject()); + } + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.Visibility#dontUseGui() */ - @SuppressWarnings("unchecked") - public final void readChildren(ObjectInputStream ois) throws IOException, - ClassNotFoundException { - synchronized (children) { - for (int i = 0; i < serializable; i++) { - Object child = ois.readObject(); - BCSChild childBCSC = (BCSChild) ois.readObject(); - children.put(child, childBCSC); - - childDeserializedHook(child, childBCSC); - - // set child's beanContext property - BeanContextChild beanContextChild = getChildBeanContextChild(child); - if (beanContextChild != null) { - try { - beanContextChild.setBeanContext(getBeanContextPeer()); - } catch (PropertyVetoException e) { - throw new IOException( - Messages.getString("beans.6B")); - } - // ensure no duplicate listener - beanContextChild.removePropertyChangeListener( - "beanContext", nonSerPCL); - // listen to child's beanContext change - beanContextChild.addPropertyChangeListener("beanContext", - nonSerPCL); - } - } - } - } - - /** - * Removes the given child from this context. - *

        - * Delegates to remove(child, true).

        - * - * @param child a child of this context - * @return true if the child is removed; or false if it is not a child of this context - * @throws IllegalArgumentException if the child is null - * @throws IllegalStateException if the child is not valid to remove - * @see java.util.Collection#remove(java.lang.Object) - */ - public boolean remove(Object child) { - return remove(child, true); - } - - /** - * Removes the given child from this context. - *

        - * If the given child is not a child of this context, simply returns false. - * Otherwise, validatePendingRemove() is called. If the - * removal is valid, the child's beanContext property is - * updated (if required) and the child and its proxy peer (if there is one) - * is removed. Last, childJustRemovedHook() is called and - * listeners are notified.

        - * - * @param child a child of this context - * @param setChildBC whether to call setBeanContext() on the child or not - * @return true if the child is removed; or false if it is not a child of this context - * @throws IllegalArgumentException if the child is null - * @throws IllegalStateException if the child is not valid to remove - */ - protected boolean remove(Object child, boolean setChildBC) { - if (child == null) { - throw new IllegalArgumentException(Messages.getString("beans.67")); - } - - Object peer = null; - - synchronized (globalHierarchyLock) { - // check existence - if (!contains(child)) { - return false; - } - - // check serializing state - if (serializing) { - throw new IllegalStateException( - Messages.getString("beans.68")); - } - - // validate - boolean valid = validatePendingRemove(child); - if (!valid) { - throw new IllegalStateException( - Messages.getString("beans.6E")); - } - - // set child's beanContext property - BeanContextChild beanContextChild = getChildBeanContextChild(child); - if (beanContextChild != null && setChildBC) { - // remove listener, first - beanContextChild.removePropertyChangeListener("beanContext", - nonSerPCL); - try { - beanContextChild.setBeanContext(null); - } catch (PropertyVetoException e) { - // rollback the listener change - beanContextChild.addPropertyChangeListener("beanContext", - nonSerPCL); - throw new IllegalStateException( - Messages.getString("beans.6B")); - } - } - - // remove from children - BCSChild childBCSC = null, peerBCSC = null; - synchronized (children) { - childBCSC = (BCSChild) children.remove(child); - peer = childBCSC.proxyPeer; - if (peer != null) { - peerBCSC = (BCSChild) children.remove(peer); - } - } - - // trigger hook - synchronized (child) { - removeSerializable(childBCSC); - childJustRemovedHook(child, childBCSC); - } - if (peer != null) { - synchronized (peer) { - removeSerializable(peerBCSC); - childJustRemovedHook(peer, peerBCSC); - } - } - } - - // notify listeners - fireChildrenRemoved(new BeanContextMembershipEvent( - getBeanContextPeer(), peer == null ? new Object[] { child } - : new Object[] { child, peer })); - return true; - } - - /** - * This method is unsupported, throws UnsupportedOperationException. - * - * @see java.util.Collection#removeAll(java.util.Collection) - */ - public boolean removeAll(Collection collection) { - throw new UnsupportedOperationException(); - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.beancontext.BeanContext#removeBeanContextMembershipListener(com.esotericsoftware.android.beans.beancontext.BeanContextMembershipListener) - */ - public void removeBeanContextMembershipListener( - BeanContextMembershipListener listener) { - if (listener == null) { - throw new NullPointerException(); - } - synchronized (bcmListeners) { - bcmListeners.remove(listener); - } - } - - /** - * This method is unsupported, throws UnsupportedOperationException. - * - * @see java.util.Collection#retainAll(java.util.Collection) - */ - public boolean retainAll(Collection collection) { - throw new UnsupportedOperationException(); - } - - /** - * Serializes the given collection. - *

        - * First writes a int indicating the number of all - * serializable elements (implements Serializable, then - * objects are writtern one by one.

        - * - * @param oos the stream where the collection is writtern to - * @param collection the collection to serialize - * @throws IOException if I/O exception occurs - */ - protected final void serialize(ObjectOutputStream oos, Collection collection) - throws IOException { - Object array[] = collection.toArray(); - int serCount = 0; - for (int i = 0; i < array.length; i++) { - if (array[i] instanceof Serializable) { - serCount++; - } - } - - oos.writeInt(serCount); - for (int i = 0; i < array.length; i++) { - if (array[i] instanceof Serializable) { - oos.writeObject(array[i]); - } - } - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.DesignMode#setDesignTime(boolean) - */ - public void setDesignTime(boolean designTime) { - this.designTime = designTime; - } - - /** - * Sets the locale of this context. VetoableChangeListeners - * and PropertyChangeListeners are notified. - * - * @param newLocale the new locale to set - * @throws PropertyVetoException if any VetoableChangeListener vetos this change - */ - public void setLocale(Locale newLocale) throws PropertyVetoException { - if (newLocale == null || newLocale == locale) { - return; // ignore null locale - } - - PropertyChangeEvent event = new PropertyChangeEvent( - beanContextChildPeer, "locale", locale, newLocale); - - // apply change - Locale oldLocale = locale; - locale = newLocale; - - try { - // notify vetoable listeners - vcSupport.fireVetoableChange(event); - } catch (PropertyVetoException e) { - // rollback change - locale = oldLocale; - throw e; - } - // Notify BeanContext about this change - this.pcSupport.firePropertyChange(event); - } - - /** - * Returns the number children of this context. - * - * @return the number children of this context - * @see java.util.Collection#size() - */ - public int size() { - synchronized (children) { - return children.size(); - } - } - - /** - * Returns an array of children of this context. - * - * @return an array of children of this context - * @see java.util.Collection#toArray() - */ - public Object[] toArray() { - synchronized (children) { - return children.keySet().toArray(); - } - } - - /** - * Returns an array of children of this context. - * - * @return an array of children of this context - * @see java.util.Collection#toArray(java.lang.Object[]) - */ - @SuppressWarnings("unchecked") - public Object[] toArray(Object[] array) { - synchronized (children) { - return children.keySet().toArray(array); - } - } - - /** - * Validates the pending add of child. - *

        - * Default implementation always returns true.

        - * - * @param child the child to be added - * @return true if it is valid to add the child - */ - protected boolean validatePendingAdd(Object child) { - // to be overridden - return true; - } - - /** - * Validates the pending removal of child. - *

        - * Default implementation always returns true.

        - * - * @param child the child to be removed - * @return true if it is valid to remove the child - */ - protected boolean validatePendingRemove(Object child) { - // to be overridden - return true; - } - - /* (non-Javadoc) - * @see com.esotericsoftware.android.beans.VetoableChangeListener#vetoableChange(com.esotericsoftware.android.beans.PropertyChangeEvent) - */ - public void vetoableChange(PropertyChangeEvent pce) - throws PropertyVetoException { - if (pce == null) { - throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$ - } - } - - /** - * Serializes children to the given object input stream. - *

        - * The implementation iterates through all children and writes out pairs - * of child object and BCSChild object if the child is - * serializable (implements Serialization.

        - *

        - * This method is called by writeObject() if the context - * works standalone. Or if this support object is a delegate of another - * BeanContext implementation, then this method should be - * called by the peer to avoid the 'chicken and egg' problem during - * deserialization.

        - * - * @param oos the stream to write - * @throws IOException if I/O exception occurs - */ - public final void writeChildren(ObjectOutputStream oos) throws IOException { - boolean origSer = serializing; - serializing = true; - - try { - int count = 0; - synchronized (children) { - for (Iterator iter = children.values().iterator(); iter - .hasNext();) { - BCSChild bcsc = (BCSChild) iter.next(); - if (bcsc.child instanceof Serializable - && (bcsc.proxyPeer == null || bcsc.proxyPeer instanceof Serializable)) { - oos.writeObject(bcsc.child); - oos.writeObject(bcsc); - count++; - } - } - } - - // what if count not equals to serializable? - if (count != serializable) { - throw new IOException(Messages.getString("beans.6F")); - } - } finally { - serializing = origSer; - } - } - - /** - * The implementation goes through following steps: - *

        - *

          - *
        1. Writes out non-transient properties by calling - * defaultWriteObject(), especially the - * serializable indicating the number of serializable - * children.
        2. - *
        3. Calls bcsPreSerializationHook().
        4. - *
        5. Writes out children by calling writeChildren() if - * this context works standalone. Otherwise it is the peer's - * responsibility to call writeChildren() after this object - * is serialized.
        6. - *
        7. Writes out serializable membership listeners.
        8. - *
        - *

        - * - * @param oos the object output stream - * @throws IOException if I/O exception occurs - */ - private void writeObject(ObjectOutputStream oos) throws IOException { - boolean origSer = serializing; - serializing = true; - - try { - oos.defaultWriteObject(); - - bcsPreSerializationHook(oos); - - if (this == getBeanContextPeer()) { - writeChildren(oos); - } - - synchronized (bcmListeners) { - serialize(oos, bcmListeners); - } - } finally { - serializing = origSer; - } - } - - /** - * The implementation goes through following steps: - *

        - *

          - *
        1. Reads non-transient properties by calling - * defaultReadObject().
        2. - *
        3. Calls bcsPreDeserializationHook().
        4. - *
        5. Reads children by calling readChildren() if - * this context works standalone. Otherwise it is the peer's - * responsibility to call readChildren() after this object - * is deserialized.
        6. - *
        7. Reads serializable membership listeners.
        8. - *
        - *

        - * - * @param ois the object input stream - * @throws IOException if I/O error occurs - * @throws ClassNotFoundException if class of read object is not found - */ - private void readObject(ObjectInputStream ois) throws IOException, - ClassNotFoundException { - - ois.defaultReadObject(); - - initialize(); // init transient fields - - bcsPreDeserializationHook(ois); - - if (this == getBeanContextPeer()) { - readChildren(ois); - } - - synchronized (bcmListeners) { - deserialize(ois, bcmListeners); - } - } - - /* - * Increase variable serializable if child and proxyPeer fields of the given - * BCSChild object are serializable - */ - private void addSerializable(BCSChild bcsc) { - if (bcsc.child instanceof Serializable - && (bcsc.proxyPeer == null || bcsc.proxyPeer instanceof Serializable)) { - serializable++; - } - } - - /* - * Decrease variable serializable if child and proxyPeer fields of the given - * BCSChild object are serializable - */ - private void removeSerializable(BCSChild bcsc) { - if (serializable > 0 - && bcsc.child instanceof Serializable - && (bcsc.proxyPeer == null || bcsc.proxyPeer instanceof Serializable)) { - serializable--; - } - } + public void dontUseGui () { + okToUseGui = false; + } -} + /** Notifies registered BeanContextMembershipListeners that a new child has been added. + * + * @param event the BeanContextMembershipEvent */ + protected final void fireChildrenAdded (BeanContextMembershipEvent event) { + Object listeners[]; + synchronized (bcmListeners) { + listeners = bcmListeners.toArray(); + } + for (int i = 0; i < listeners.length; i++) { + BeanContextMembershipListener l = (BeanContextMembershipListener)listeners[i]; + l.childrenAdded(event); + } + } + + /** Notifies registered BeanContextMembershipListeners that a child has been removed. + * + * @param event the BeanContextMembershipEvent */ + protected final void fireChildrenRemoved (BeanContextMembershipEvent event) { + Object listeners[]; + synchronized (bcmListeners) { + listeners = bcmListeners.toArray(); + } + for (int i = 0; i < listeners.length; i++) { + BeanContextMembershipListener l = (BeanContextMembershipListener)listeners[i]; + l.childrenRemoved(event); + } + } + + /** Returns the peer of this context casted as BeanContext. + * + * @return the peer of this context casted as BeanContext */ + public BeanContext getBeanContextPeer () { + return (BeanContext)beanContextChildPeer; + } + /** Returns the BeanContextChild related with the given child. + *

        + * If the child implements BeanContextChild, it is returned. If the child implements BeanContextProxy + * , the proxy is returned. Otherwise, null is returned. + *

        + * + * @param child a child + * @return the BeanContextChild related with the given child + * @throws IllegalStateException if the child implements both BeanContextChild and BeanContextProxy */ + protected static final BeanContextChild getChildBeanContextChild (Object child) { + if (child instanceof BeanContextChild) { + if (child instanceof BeanContextProxy) { + throw new IllegalArgumentException(Messages.getString("beans.6C")); + } + return (BeanContextChild)child; + } + if (child instanceof BeanContextProxy) { + if (child instanceof BeanContextChild) { + throw new IllegalArgumentException(Messages.getString("beans.6C")); + } + return ((BeanContextProxy)child).getBeanContextProxy(); + } + return null; + } + + /** Returns the given child casted to BeanContextMembershipListener, or null if it does not implements the + * interface. + * + * @param child a child + * @return the given child casted to BeanContextMembershipListener, or null if it does not implements the + * interface */ + protected static final BeanContextMembershipListener getChildBeanContextMembershipListener (Object child) { + if (child instanceof BeanContextMembershipListener) { + return (BeanContextMembershipListener)child; + } else { + return null; + } + } + + /** Returns the given child casted to PropertyChangeListener, or null if it does not implements the interface. + * + * @param child a child + * @return the given child casted to PropertyChangeListener, or null if it does not implements the interface */ + protected static final PropertyChangeListener getChildPropertyChangeListener (Object child) { + if (child instanceof PropertyChangeListener) { + return (PropertyChangeListener)child; + } else { + return null; + } + } + + /** Returns the given child casted to Serializable, or null if it does not implements the interface. + * + * @param child a child + * @return the given child casted to Serializable, or null if it does not implements the interface */ + protected static final Serializable getChildSerializable (Object child) { + if (child instanceof Serializable) { + return (Serializable)child; + } else { + return null; + } + } + + /** Returns the given child casted to VetoableChangeListener, or null if it does not implements the interface. + * + * @param child a child + * @return the given child casted to VetoableChangeListener, or null if it does not implements the interface */ + protected static final VetoableChangeListener getChildVetoableChangeListener (Object child) { + if (child instanceof VetoableChangeListener) { + return (VetoableChangeListener)child; + } else { + return null; + } + } + + /** Returns the given child casted to Visibility, or null if it does not implements the interface. + * + * @param child a child + * @return the given child casted to Visibility, or null if it does not implements the interface */ + protected static final Visibility getChildVisibility (Object child) { + if (child instanceof Visibility) { + return (Visibility)child; + } else { + return null; + } + } + + /** Returns the locale of this context. + * + * @return the locale of this context */ + public Locale getLocale () { + return locale; + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.beancontext.BeanContext#getResource(java.lang.String, + * com.esotericsoftware.android.beans.beancontext.BeanContextChild) + */ + public URL getResource (String resourceName, BeanContextChild child) { + if (resourceName == null || child == null) { + throw new NullPointerException(); + } + if (!contains(child)) { + throw new IllegalArgumentException(Messages.getString("beans.6D")); + } + + return ClassLoader.getSystemResource(resourceName); + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.beancontext.BeanContext#getResourceAsStream(java.lang.String, + * com.esotericsoftware.android.beans.beancontext.BeanContextChild) + */ + public InputStream getResourceAsStream (String resourceName, BeanContextChild child) throws IllegalArgumentException { + if (resourceName == null || child == null) { + throw new NullPointerException(); + } + if (!contains(child)) { + throw new IllegalArgumentException(Messages.getString("beans.6D")); + } + + return ClassLoader.getSystemResourceAsStream(resourceName); + } + + /** Initializes all transient fields of this instance, called by constructors and readObject(). */ + protected void initialize () { + // init transient fields + bcmListeners = new ArrayList(); + children = new HashMap(); + serializing = false; + inNeedsGui = false; + nonSerPCL = new PropertyChangeListener() { + public void propertyChange (PropertyChangeEvent event) { + BeanContextSupport.this.propertyChange(event); + } + }; + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.beancontext.BeanContext#instantiateChild(java.lang.String) + */ + public Object instantiateChild (String beanName) throws IOException, ClassNotFoundException { + return Beans.instantiate(getClass().getClassLoader(), beanName, getBeanContextPeer()); + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.DesignMode#isDesignTime() + */ + public boolean isDesignTime () { + return designTime; + } + + /* + * (non-Javadoc) + * + * @see java.util.Collection#isEmpty() + */ + public boolean isEmpty () { + synchronized (children) { + return children.isEmpty(); + } + } + + /** Returns true if this context is currently being serialized (by another thread). + * + * @return true if this context is currently being serialized (by another thread) */ + public boolean isSerializing () { + return serializing; + } + + /** Returns an iterator of children of this context, with remove() disabled. + * + * @see java.util.Collection#iterator() */ + public Iterator iterator () { + synchronized (children) { + return new BCSIterator(children.keySet().iterator()); + } + } + + /** Returns true if this context or its children needs GUI to work properly. + *

        + * The implementation checks the peer and all the children that implement Visibility to see if any of their + * needsGui() returns true, and if any of the children extends java.awt.Component. + *

        + * + * @see com.badlogic.gdx.beans.Visibility#needsGui() */ + public boolean needsGui () { + if (inNeedsGui) { + return false; + } + inNeedsGui = true; + + try { + if (getBeanContextPeer() != this) { + if (getBeanContextPeer().needsGui()) { + return true; + } + } + Object childs[] = copyChildren(); + for (int i = 0; i < childs.length; i++) { + if (childs[i] instanceof Component) { + return true; + } + Visibility v = getChildVisibility(childs[i]); + if (v != null && v.needsGui()) { + return true; + } + } + return false; + } finally { + inNeedsGui = false; + } + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.Visibility#okToUseGui() + */ + public void okToUseGui () { + okToUseGui = true; + } + + /* + * (non-Javadoc) + * + * @see + * com.esotericsoftware.android.beans.PropertyChangeListener#propertyChange(com.esotericsoftware.android.beans.PropertyChangeEvent + * ) + */ + public void propertyChange (PropertyChangeEvent event) { + if (contains(event.getSource()) && "beanContext".equals(event.getPropertyName()) + && event.getOldValue() == getBeanContextPeer()) { + remove(event.getSource(), false); + } + } + + /** Deserializes children from the given object input stream. + *

        + * The implementation reads pairs of child object and BCSChild object according to serializable + * property. For each pair, it is added to the children map and the childDeserializedHook() is + * called. If the child implements BeanContextChild, its setBeanContext() is also called. + *

        + *

        + * This method is called by readObject() if the context works standalone. Or if this support object is a delegate + * of another BeanContext implementation, then this method should be called by the peer. Doing this means that + * derialization can proceed without any circular dependency problems. + * + * @param ois the object input stream + * @throws IOException if I/O exception occurs + * @throws ClassNotFoundException if class of read object is not found */ + @SuppressWarnings("unchecked") + public final void readChildren (ObjectInputStream ois) throws IOException, ClassNotFoundException { + synchronized (children) { + for (int i = 0; i < serializable; i++) { + Object child = ois.readObject(); + BCSChild childBCSC = (BCSChild)ois.readObject(); + children.put(child, childBCSC); + + childDeserializedHook(child, childBCSC); + + // set child's beanContext property + BeanContextChild beanContextChild = getChildBeanContextChild(child); + if (beanContextChild != null) { + try { + beanContextChild.setBeanContext(getBeanContextPeer()); + } catch (PropertyVetoException e) { + throw new IOException(Messages.getString("beans.6B")); + } + // ensure no duplicate listener + beanContextChild.removePropertyChangeListener("beanContext", nonSerPCL); + // listen to child's beanContext change + beanContextChild.addPropertyChangeListener("beanContext", nonSerPCL); + } + } + } + } + + /** Removes the given child from this context. + *

        + * Delegates to remove(child, true). + *

        + * + * @param child a child of this context + * @return true if the child is removed; or false if it is not a child of this context + * @throws IllegalArgumentException if the child is null + * @throws IllegalStateException if the child is not valid to remove + * @see java.util.Collection#remove(java.lang.Object) */ + public boolean remove (Object child) { + return remove(child, true); + } + + /** Removes the given child from this context. + *

        + * If the given child is not a child of this context, simply returns false. Otherwise, validatePendingRemove() is + * called. If the removal is valid, the child's beanContext property is updated (if required) and the child and + * its proxy peer (if there is one) is removed. Last, childJustRemovedHook() is called and listeners are notified. + *

        + * + * @param child a child of this context + * @param setChildBC whether to call setBeanContext() on the child or not + * @return true if the child is removed; or false if it is not a child of this context + * @throws IllegalArgumentException if the child is null + * @throws IllegalStateException if the child is not valid to remove */ + protected boolean remove (Object child, boolean setChildBC) { + if (child == null) { + throw new IllegalArgumentException(Messages.getString("beans.67")); + } + + Object peer = null; + + synchronized (globalHierarchyLock) { + // check existence + if (!contains(child)) { + return false; + } + + // check serializing state + if (serializing) { + throw new IllegalStateException(Messages.getString("beans.68")); + } + + // validate + boolean valid = validatePendingRemove(child); + if (!valid) { + throw new IllegalStateException(Messages.getString("beans.6E")); + } + + // set child's beanContext property + BeanContextChild beanContextChild = getChildBeanContextChild(child); + if (beanContextChild != null && setChildBC) { + // remove listener, first + beanContextChild.removePropertyChangeListener("beanContext", nonSerPCL); + try { + beanContextChild.setBeanContext(null); + } catch (PropertyVetoException e) { + // rollback the listener change + beanContextChild.addPropertyChangeListener("beanContext", nonSerPCL); + throw new IllegalStateException(Messages.getString("beans.6B")); + } + } + + // remove from children + BCSChild childBCSC = null, peerBCSC = null; + synchronized (children) { + childBCSC = (BCSChild)children.remove(child); + peer = childBCSC.proxyPeer; + if (peer != null) { + peerBCSC = (BCSChild)children.remove(peer); + } + } + + // trigger hook + synchronized (child) { + removeSerializable(childBCSC); + childJustRemovedHook(child, childBCSC); + } + if (peer != null) { + synchronized (peer) { + removeSerializable(peerBCSC); + childJustRemovedHook(peer, peerBCSC); + } + } + } + + // notify listeners + fireChildrenRemoved(new BeanContextMembershipEvent(getBeanContextPeer(), peer == null ? new Object[] {child} + : new Object[] {child, peer})); + return true; + } + + /** This method is unsupported, throws UnsupportedOperationException. + * + * @see java.util.Collection#removeAll(java.util.Collection) */ + public boolean removeAll (Collection collection) { + throw new UnsupportedOperationException(); + } + /* + * (non-Javadoc) + * + * @see + * com.esotericsoftware.android.beans.beancontext.BeanContext#removeBeanContextMembershipListener(com.esotericsoftware.android + * .beans.beancontext.BeanContextMembershipListener) + */ + public void removeBeanContextMembershipListener (BeanContextMembershipListener listener) { + if (listener == null) { + throw new NullPointerException(); + } + synchronized (bcmListeners) { + bcmListeners.remove(listener); + } + } + + /** This method is unsupported, throws UnsupportedOperationException. + * + * @see java.util.Collection#retainAll(java.util.Collection) */ + public boolean retainAll (Collection collection) { + throw new UnsupportedOperationException(); + } + + /** Serializes the given collection. + *

        + * First writes a int indicating the number of all serializable elements (implements Serializable, + * then objects are writtern one by one. + *

        + * + * @param oos the stream where the collection is writtern to + * @param collection the collection to serialize + * @throws IOException if I/O exception occurs */ + protected final void serialize (ObjectOutputStream oos, Collection collection) throws IOException { + Object array[] = collection.toArray(); + int serCount = 0; + for (int i = 0; i < array.length; i++) { + if (array[i] instanceof Serializable) { + serCount++; + } + } + + oos.writeInt(serCount); + for (int i = 0; i < array.length; i++) { + if (array[i] instanceof Serializable) { + oos.writeObject(array[i]); + } + } + } + + /* + * (non-Javadoc) + * + * @see com.esotericsoftware.android.beans.DesignMode#setDesignTime(boolean) + */ + public void setDesignTime (boolean designTime) { + this.designTime = designTime; + } + + /** Sets the locale of this context. VetoableChangeListeners and PropertyChangeListeners are notified. + * + * @param newLocale the new locale to set + * @throws PropertyVetoException if any VetoableChangeListener vetos this change */ + public void setLocale (Locale newLocale) throws PropertyVetoException { + if (newLocale == null || newLocale == locale) { + return; // ignore null locale + } + + PropertyChangeEvent event = new PropertyChangeEvent(beanContextChildPeer, "locale", locale, newLocale); + + // apply change + Locale oldLocale = locale; + locale = newLocale; + + try { + // notify vetoable listeners + vcSupport.fireVetoableChange(event); + } catch (PropertyVetoException e) { + // rollback change + locale = oldLocale; + throw e; + } + // Notify BeanContext about this change + this.pcSupport.firePropertyChange(event); + } + + /** Returns the number children of this context. + * + * @return the number children of this context + * @see java.util.Collection#size() */ + public int size () { + synchronized (children) { + return children.size(); + } + } + + /** Returns an array of children of this context. + * + * @return an array of children of this context + * @see java.util.Collection#toArray() */ + public Object[] toArray () { + synchronized (children) { + return children.keySet().toArray(); + } + } + + /** Returns an array of children of this context. + * + * @return an array of children of this context + * @see java.util.Collection#toArray(java.lang.Object[]) */ + @SuppressWarnings("unchecked") + public Object[] toArray (Object[] array) { + synchronized (children) { + return children.keySet().toArray(array); + } + } + + /** Validates the pending add of child. + *

        + * Default implementation always returns true. + *

        + * + * @param child the child to be added + * @return true if it is valid to add the child */ + protected boolean validatePendingAdd (Object child) { + // to be overridden + return true; + } + + /** Validates the pending removal of child. + *

        + * Default implementation always returns true. + *

        + * + * @param child the child to be removed + * @return true if it is valid to remove the child */ + protected boolean validatePendingRemove (Object child) { + // to be overridden + return true; + } + + /* + * (non-Javadoc) + * + * @see + * com.esotericsoftware.android.beans.VetoableChangeListener#vetoableChange(com.esotericsoftware.android.beans.PropertyChangeEvent + * ) + */ + public void vetoableChange (PropertyChangeEvent pce) throws PropertyVetoException { + if (pce == null) { + throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$ + } + } + + /** Serializes children to the given object input stream. + *

        + * The implementation iterates through all children and writes out pairs of child object and BCSChild object if + * the child is serializable (implements Serialization. + *

        + *

        + * This method is called by writeObject() if the context works standalone. Or if this support object is a delegate + * of another BeanContext implementation, then this method should be called by the peer to avoid the 'chicken and + * egg' problem during deserialization. + *

        + * + * @param oos the stream to write + * @throws IOException if I/O exception occurs */ + public final void writeChildren (ObjectOutputStream oos) throws IOException { + boolean origSer = serializing; + serializing = true; + + try { + int count = 0; + synchronized (children) { + for (Iterator iter = children.values().iterator(); iter.hasNext();) { + BCSChild bcsc = (BCSChild)iter.next(); + if (bcsc.child instanceof Serializable && (bcsc.proxyPeer == null || bcsc.proxyPeer instanceof Serializable)) { + oos.writeObject(bcsc.child); + oos.writeObject(bcsc); + count++; + } + } + } + + // what if count not equals to serializable? + if (count != serializable) { + throw new IOException(Messages.getString("beans.6F")); + } + } finally { + serializing = origSer; + } + } + + /** The implementation goes through following steps: + *

        + *

          + *
        1. Writes out non-transient properties by calling defaultWriteObject(), especially the + * serializable indicating the number of serializable children.
        2. + *
        3. Calls bcsPreSerializationHook().
        4. + *
        5. Writes out children by calling writeChildren() if this context works standalone. Otherwise it is the peer's + * responsibility to call writeChildren() after this object is serialized.
        6. + *
        7. Writes out serializable membership listeners.
        8. + *
        + *

        + * + * @param oos the object output stream + * @throws IOException if I/O exception occurs */ + private void writeObject (ObjectOutputStream oos) throws IOException { + boolean origSer = serializing; + serializing = true; + + try { + oos.defaultWriteObject(); + + bcsPreSerializationHook(oos); + + if (this == getBeanContextPeer()) { + writeChildren(oos); + } + + synchronized (bcmListeners) { + serialize(oos, bcmListeners); + } + } finally { + serializing = origSer; + } + } + + /** The implementation goes through following steps: + *

        + *

          + *
        1. Reads non-transient properties by calling defaultReadObject().
        2. + *
        3. Calls bcsPreDeserializationHook().
        4. + *
        5. Reads children by calling readChildren() if this context works standalone. Otherwise it is the peer's + * responsibility to call readChildren() after this object is deserialized.
        6. + *
        7. Reads serializable membership listeners.
        8. + *
        + *

        + * + * @param ois the object input stream + * @throws IOException if I/O error occurs + * @throws ClassNotFoundException if class of read object is not found */ + private void readObject (ObjectInputStream ois) throws IOException, ClassNotFoundException { + + ois.defaultReadObject(); + + initialize(); // init transient fields + + bcsPreDeserializationHook(ois); + + if (this == getBeanContextPeer()) { + readChildren(ois); + } + + synchronized (bcmListeners) { + deserialize(ois, bcmListeners); + } + } + + /* + * Increase variable serializable if child and proxyPeer fields of the given BCSChild object are serializable + */ + private void addSerializable (BCSChild bcsc) { + if (bcsc.child instanceof Serializable && (bcsc.proxyPeer == null || bcsc.proxyPeer instanceof Serializable)) { + serializable++; + } + } + + /* + * Decrease variable serializable if child and proxyPeer fields of the given BCSChild object are serializable + */ + private void removeSerializable (BCSChild bcsc) { + if (serializable > 0 && bcsc.child instanceof Serializable + && (bcsc.proxyPeer == null || bcsc.proxyPeer instanceof Serializable)) { + serializable--; + } + } + +} diff --git a/extensions/beans/src/org/apache/harmony/beans/Argument.java b/extensions/beans/src/org/apache/harmony/beans/Argument.java index 8afba2621a3..404e46e77e6 100644 --- a/extensions/beans/src/org/apache/harmony/beans/Argument.java +++ b/extensions/beans/src/org/apache/harmony/beans/Argument.java @@ -19,44 +19,44 @@ public class Argument { - private Class type; - - private Object value; - - private Class[] interfaces; - - public Argument(Object value) { - this.value = value; - if (this.value != null) { - this.type = value.getClass(); - this.interfaces = this.type.getInterfaces(); - } - } - - public Argument(Class type, Object value) { - this.type = type; - this.value = value; - this.interfaces = type.getInterfaces(); - } - - public Class getType() { - return type; - } - - public Object getValue() { - return value; - } - - public Class[] getInterfaces() { - return interfaces; - } - - public void setType(Class type) { - this.type = type; - this.interfaces = type.getInterfaces(); - } - - public void setInterfaces(Class[] interfaces) { - this.interfaces = interfaces; - } + private Class type; + + private Object value; + + private Class[] interfaces; + + public Argument (Object value) { + this.value = value; + if (this.value != null) { + this.type = value.getClass(); + this.interfaces = this.type.getInterfaces(); + } + } + + public Argument (Class type, Object value) { + this.type = type; + this.value = value; + this.interfaces = type.getInterfaces(); + } + + public Class getType () { + return type; + } + + public Object getValue () { + return value; + } + + public Class[] getInterfaces () { + return interfaces; + } + + public void setType (Class type) { + this.type = type; + this.interfaces = type.getInterfaces(); + } + + public void setInterfaces (Class[] interfaces) { + this.interfaces = interfaces; + } } diff --git a/extensions/beans/src/org/apache/harmony/beans/BeansUtils.java b/extensions/beans/src/org/apache/harmony/beans/BeansUtils.java index b498afa2f7a..7b3e81e497b 100644 --- a/extensions/beans/src/org/apache/harmony/beans/BeansUtils.java +++ b/extensions/beans/src/org/apache/harmony/beans/BeansUtils.java @@ -22,101 +22,96 @@ public class BeansUtils { - public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; - - public static final String NEW = "new"; //$NON-NLS-1$ - - public static final String NEWINSTANCE = "newInstance"; //$NON-NLS-1$ - - public static final String NEWARRAY = "newArray"; //$NON-NLS-1$ - - public static final String FORNAME = "forName"; //$NON-NLS-1$ - - public static final String GET = "get"; //$NON-NLS-1$ - - public static final String IS = "is"; //$NON-NLS-1$ - - public static final String SET = "set"; //$NON-NLS-1$ - - public static final String ADD = "add"; //$NON-NLS-1$ - - public static final String PUT = "put"; //$NON-NLS-1$ - - public static final String NULL = "null"; //$NON-NLS-1$ - - public static final String QUOTE = "\"\""; //$NON-NLS-1$ - - public static final int getHashCode(Object obj) { - return obj != null ? obj.hashCode() : 0; - } - - public static final int getHashCode(boolean bool) { - return bool ? 1 : 0; - } - - public static String toASCIILowerCase(String string) { - char[] charArray = string.toCharArray(); - StringBuilder sb = new StringBuilder(charArray.length); - for (int index = 0; index < charArray.length; index++) { - if ('A' <= charArray[index] && charArray[index] <= 'Z') { - sb.append((char) (charArray[index] + ('a' - 'A'))); - } else { - sb.append(charArray[index]); - } - } - return sb.toString(); - } - - public static String toASCIIUpperCase(String string) { - char[] charArray = string.toCharArray(); - StringBuilder sb = new StringBuilder(charArray.length); - for (int index = 0; index < charArray.length; index++) { - if ('a' <= charArray[index] && charArray[index] <= 'z') { - sb.append((char) (charArray[index] - ('a' - 'A'))); - } else { - sb.append(charArray[index]); - } - } - return sb.toString(); - } - - public static boolean isPrimitiveWrapper(Class wrapper, Class base) { - return (base == boolean.class) && (wrapper == Boolean.class) - || (base == byte.class) && (wrapper == Byte.class) - || (base == char.class) && (wrapper == Character.class) - || (base == short.class) && (wrapper == Short.class) - || (base == int.class) && (wrapper == Integer.class) - || (base == long.class) && (wrapper == Long.class) - || (base == float.class) && (wrapper == Float.class) - || (base == double.class) && (wrapper == Double.class); - } - - private static final String EQUALS_METHOD = "equals"; - - private static final Class[] EQUALS_PARAMETERS = new Class[] { Object.class }; - - public static boolean declaredEquals(Class clazz) { - for (Method declaredMethod : clazz.getDeclaredMethods()) { - if (EQUALS_METHOD.equals(declaredMethod.getName()) - && Arrays.equals(declaredMethod.getParameterTypes(), - EQUALS_PARAMETERS)) { - return true; - } - } - return false; - } - - public static String idOfClass(Class clazz) { - Class theClass = clazz; - StringBuilder sb = new StringBuilder(); - if (theClass.isArray()) { - do { - sb.append("Array"); //$NON-NLS-1$ - theClass = theClass.getComponentType(); - } while (theClass.isArray()); - } - String clazzName = theClass.getName(); - clazzName = clazzName.substring(clazzName.lastIndexOf('.') + 1); - return clazzName + sb.toString(); - } + public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; + + public static final String NEW = "new"; //$NON-NLS-1$ + + public static final String NEWINSTANCE = "newInstance"; //$NON-NLS-1$ + + public static final String NEWARRAY = "newArray"; //$NON-NLS-1$ + + public static final String FORNAME = "forName"; //$NON-NLS-1$ + + public static final String GET = "get"; //$NON-NLS-1$ + + public static final String IS = "is"; //$NON-NLS-1$ + + public static final String SET = "set"; //$NON-NLS-1$ + + public static final String ADD = "add"; //$NON-NLS-1$ + + public static final String PUT = "put"; //$NON-NLS-1$ + + public static final String NULL = "null"; //$NON-NLS-1$ + + public static final String QUOTE = "\"\""; //$NON-NLS-1$ + + public static final int getHashCode (Object obj) { + return obj != null ? obj.hashCode() : 0; + } + + public static final int getHashCode (boolean bool) { + return bool ? 1 : 0; + } + + public static String toASCIILowerCase (String string) { + char[] charArray = string.toCharArray(); + StringBuilder sb = new StringBuilder(charArray.length); + for (int index = 0; index < charArray.length; index++) { + if ('A' <= charArray[index] && charArray[index] <= 'Z') { + sb.append((char)(charArray[index] + ('a' - 'A'))); + } else { + sb.append(charArray[index]); + } + } + return sb.toString(); + } + + public static String toASCIIUpperCase (String string) { + char[] charArray = string.toCharArray(); + StringBuilder sb = new StringBuilder(charArray.length); + for (int index = 0; index < charArray.length; index++) { + if ('a' <= charArray[index] && charArray[index] <= 'z') { + sb.append((char)(charArray[index] - ('a' - 'A'))); + } else { + sb.append(charArray[index]); + } + } + return sb.toString(); + } + + public static boolean isPrimitiveWrapper (Class wrapper, Class base) { + return (base == boolean.class) && (wrapper == Boolean.class) || (base == byte.class) && (wrapper == Byte.class) + || (base == char.class) && (wrapper == Character.class) || (base == short.class) && (wrapper == Short.class) + || (base == int.class) && (wrapper == Integer.class) || (base == long.class) && (wrapper == Long.class) + || (base == float.class) && (wrapper == Float.class) || (base == double.class) && (wrapper == Double.class); + } + + private static final String EQUALS_METHOD = "equals"; + + private static final Class[] EQUALS_PARAMETERS = new Class[] {Object.class}; + + public static boolean declaredEquals (Class clazz) { + for (Method declaredMethod : clazz.getDeclaredMethods()) { + if (EQUALS_METHOD.equals(declaredMethod.getName()) + && Arrays.equals(declaredMethod.getParameterTypes(), EQUALS_PARAMETERS)) { + return true; + } + } + return false; + } + + public static String idOfClass (Class clazz) { + Class theClass = clazz; + StringBuilder sb = new StringBuilder(); + if (theClass.isArray()) { + do { + sb.append("Array"); //$NON-NLS-1$ + theClass = theClass.getComponentType(); + } while (theClass.isArray()); + } + String clazzName = theClass.getName(); + clazzName = clazzName.substring(clazzName.lastIndexOf('.') + 1); + return clazzName + sb.toString(); + } } diff --git a/extensions/beans/src/org/apache/harmony/beans/Command.java b/extensions/beans/src/org/apache/harmony/beans/Command.java index 1cdd2bbc30c..eb8c6061354 100644 --- a/extensions/beans/src/org/apache/harmony/beans/Command.java +++ b/extensions/beans/src/org/apache/harmony/beans/Command.java @@ -17,15 +17,6 @@ package org.apache.harmony.beans; -import com.badlogic.gdx.beans.BeanInfo; -import com.badlogic.gdx.beans.Expression; -import com.badlogic.gdx.beans.IndexedPropertyDescriptor; -import com.badlogic.gdx.beans.IntrospectionException; -import com.badlogic.gdx.beans.Introspector; -import com.badlogic.gdx.beans.PropertyDescriptor; -import com.badlogic.gdx.beans.Statement; -import com.badlogic.gdx.beans.XMLDecoder; - import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.HashMap; @@ -36,832 +27,821 @@ import org.apache.harmony.beans.internal.nls.Messages; import org.xml.sax.Attributes; +import com.badlogic.gdx.beans.BeanInfo; +import com.badlogic.gdx.beans.Expression; +import com.badlogic.gdx.beans.IndexedPropertyDescriptor; +import com.badlogic.gdx.beans.IntrospectionException; +import com.badlogic.gdx.beans.Introspector; +import com.badlogic.gdx.beans.PropertyDescriptor; +import com.badlogic.gdx.beans.Statement; +import com.badlogic.gdx.beans.XMLDecoder; public class Command { - private static final int INITIALIZED = 0; + private static final int INITIALIZED = 0; - private static final int CHILDREN_FILTERED = 1; + private static final int CHILDREN_FILTERED = 1; - private static final int COMMAND_EXECUTED = 2; + private static final int COMMAND_EXECUTED = 2; - private static final int CHILDREN_PROCESSED = 3; + private static final int CHILDREN_PROCESSED = 3; - private String tagName; // tag name + private String tagName; // tag name - private Map attrs; // set of attrs + private Map attrs; // set of attrs - private String data; // string data + private String data; // string data - // inner commands - private Vector commands = new Vector(); + // inner commands + private Vector commands = new Vector(); - // arguments - private Vector arguments = new Vector(); + // arguments + private Vector arguments = new Vector(); - // operations - private Vector operations = new Vector(); - - // additional arguments placed before others - private Vector auxArguments = new Vector(); - - private Argument result; // result argument - - private Object target; // target to execute a command on - - private String methodName; // method name - - private Command ctx; // context for command - - private int status; // commands - - private XMLDecoder decoder; - - // private int tabCount = 0; - - public Command(String tagName, Map attrs) { - this.tagName = tagName; - this.attrs = attrs; - this.status = initializeStatus(tagName); - } - - public Command(XMLDecoder decoder, String tagName, Map attrs) { - this.decoder = decoder; - this.tagName = tagName; - this.attrs = attrs; - this.status = initializeStatus(tagName); - } - - // set data for command - public void setData(String data) { - this.data = data; - } - - // set tab count to display log messages - // public void setTabCount(int tabCount) { - // this.tabCount = tabCount; - // } - - // set context - upper level command - public void setContext(Command ctx) { - this.ctx = ctx; - } - - // add child command - public void addChild(Command cmd) { - if (cmd != null) { - cmd.setContext(this); - commands.add(cmd); - } - } - - // remove child command - public void removeChild(Command cmd) { - if ((cmd != null) && commands.remove(cmd)) { - cmd.setContext(null); - } - } - - // command status - public int getStatus() { - return status; - } - - // check if one of arguments or operations is unresolved - private boolean isResolved() { - if (getStatus() < Command.CHILDREN_PROCESSED) { - return false; - } - for (int i = 0; i < arguments.size(); ++i) { - Command arg = arguments.elementAt(i); - - if (!arg.isResolved()) { - return false; - } - } - for (int j = 0; j < operations.size(); ++j) { - Command opr = operations.elementAt(j); - - if (!opr.isResolved()) { - return false; - } - } - return true; - } - - // execute command and return execution flags - public int exec(Map references) throws Exception { - // System.out.println("in exec() status = " + translateStatus(status) + - // "..."); - if (status < Command.CHILDREN_PROCESSED) { - if (status < Command.COMMAND_EXECUTED) { - if (status < Command.CHILDREN_FILTERED) { - status = doBeforeRun(references); - // System.out.println("after doBeforeRun() status = " + - // translateStatus(status)); - } - if (status == Command.CHILDREN_FILTERED) { - status = doRun(references); - // System.out.println("after doRun() status = " + - // translateStatus(status)); - } - } - if (status == Command.COMMAND_EXECUTED) { - status = doAfterRun(references); - // System.out.println("after doAfterRun() status = " + - // translateStatus(status)); - } - } - // System.out.println("...out of exec() status = " + - // translateStatus(status)); - return status; - } - - // execute commands in backtrack order - public boolean backtrack(Map references) throws Exception { - for (int i = 0; i < arguments.size(); ++i) { - Command arg = arguments.elementAt(i); - arg.backtrack(references); - } - for (int i = 0; i < operations.size(); ++i) { - Command opr = operations.elementAt(i); - opr.backtrack(references); - } - if (status == Command.CHILDREN_FILTERED) { - status = doRun(references); - } - if (status == Command.COMMAND_EXECUTED) { - status = doAfterRun(references); - return (getStatus() == Command.CHILDREN_PROCESSED); - } - return false; - } - - // put command in one of two collections - arguments or operations - private int doBeforeRun(Map references) throws Exception { - if (status == Command.INITIALIZED) { - for (int i = 0; i < commands.size(); ++i) { - Command cmd = commands.elementAt(i); - - // XXX is this correct? - if (cmd.isExecutable()) { - arguments.add(cmd); - } else { - operations.add(cmd); - } - } - return Command.CHILDREN_FILTERED; - } - return status; - } - - // run command - private int doRun(Map references) throws Exception { - if (status == Command.CHILDREN_FILTERED) { - if (isRoot()) { - result = new Argument(decoder); - // System.out.println("doRun(): result is decoder..."); - return Command.COMMAND_EXECUTED; - } - - if (isNull()) { - result = new Argument(null); - // System.out.println("doRun(): result is null..."); - return Command.COMMAND_EXECUTED; - } - - if (ctx != null && ctx.isArray() && (ctx.getResultValue() == null) - && !isExecutable()) { - // System.out.println("doRun(): context is array..."); - return status; - } - - Object target = getTarget(references); - if (target == null) { - // System.out.println("doRun(): target is null..."); - return status; - } - // if (target instanceof Class) { - // System.out.println("doRun(): target = " + - // ((Class)target).getName()); - // } else { - // System.out.println("doRun(): target = " + - // target.getClass().getName()); - // } - if (isReference()) { - result = getReferencedArgument(references); - // System.out.println("doRun(): reference - result is " + - // result.getType()); - } else { - String methodName = getMethodName(references); - // System.out.println("doRun(): methodName = " + - // methodName); - Argument[] arguments = getArguments(); - if (arguments == null) { - return status; - } - // for (Argument element : arguments) { - // if (element != null) { - // System.out.println("doRun(): arg [" + i + "] = " - // + arguments[i].getType()); - // } else { - // System.out.println("doRun(): arg [" + i + "] = - // null"); - // } - // } - - Expression expr = new Expression(target, methodName, - getArgumentsValues()); - result = new Argument(expr.getValue()); - - if (isPrimitiveClassName(getTagName())) { - result.setType(getPrimitiveClass(tagName)); - } - - // System.out.println("doRun(): method call - result is " + - // result.getType()); - } - return Command.COMMAND_EXECUTED; - } - return status; - } - - // run child commands - private int doAfterRun(Map references) throws Exception { - if (status == Command.COMMAND_EXECUTED) { - // System.out.println("doAfterRun(): command " + getResultType() + " - // processed..."); - Vector toBeRemoved = new Vector(); - try { - Statement[] statements = null; - - for (int i = 0; i < operations.size(); ++i) { - Command cmd = operations.elementAt(i); - - if (cmd.isArrayElement()) { - - if (cmd.isResolved()) { - if (statements == null) { - statements = new Statement[operations.size()]; - } - statements[i] = new Statement(getResultValue(), - "set", new Object[] { Integer.valueOf(i), //$NON-NLS-1$ - cmd.getResultValue() }); - if ((i + 1) == operations.size()) { - for (int j = 0; j < operations.size(); ++j) { - statements[j].execute(); - } - toBeRemoved.addAll(operations); - } - } else { - break; - } - - } else { - // since the call is Array.set() - if (!isArray()) { - cmd.setTarget(getResultValue()); - } - cmd.exec(references); - - if (cmd.isResolved()) { - // System.out.println("doAfterRun(): cmd = " + - // cmd.methodName + " is resolved"); - toBeRemoved.add(cmd); - } else { - // System.out.println("doAfterRun(): cmd = " + - // cmd.methodName + " is unresolved"); - break; - } - - } - - } - } catch (Exception e) { - throw new Exception(e); - } finally { - operations.removeAll(toBeRemoved); - } - - // if (operations.size() == 0) { - // System.out.println("doAfterRun(): command " + getResultType() - // + " completely processed."); - // } else { - // System.out.println("doAfterRun(): command " + getResultType() - // + " contains incomplete " + - // operations.size() + " commands."); - // } - return (operations.size() == 0) ? Command.CHILDREN_PROCESSED - : status; - } - return status; - } - - // Result accessors - - // Return result - Argument class - public Argument getResult() { - return result; - } - - // Returns result value - public Object getResultValue() { - return (result != null) ? result.getValue() : null; - } - - // Returns result type - public Class getResultType() throws ClassNotFoundException { - return (result != null) ? result.getType() : null; - } - - // accessors to XML tags and attrs - public boolean hasAttr(String name) { - return attrs.get(name) != null; - } - - public String getAttr(String name) { - return attrs.get(name); - } - - public boolean isTag(String name) { - return tagName.equals(name); - } - - public boolean hasAttr(String name, String value) { - return value.equals(attrs.get(name)); - } - - public String getTagName() { - return tagName; - } - - // Checks if the object is primitive - int, float, etc... - private boolean isPrimitive() { - return isPrimitiveClassName(tagName); - } - - // Checks if the object is constructor - private boolean isConstructor() { - return isPrimitive() || !isStaticMethod() && !isMethod() - && !isProperty() && !isField() && !isArray() && !isReference(); - } - - // Checks if the command is static method - private boolean isStaticMethod() { - return isTag("object") && hasAttr("method") || isTag("class"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - // Checks if the command is public method - private boolean isMethod() { - return isTag("void") && (hasAttr("method") || hasAttr("index")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - // Check if the command relates to property - getter ot setter depends on - // number of args - private boolean isProperty() { - return isTag("void") && hasAttr("property"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - // Check if the command is field accessor - private boolean isField() { - return isTag("object") && hasAttr("field"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - // Check if the command is array - private boolean isArray() { - return isTag("array"); //$NON-NLS-1$ - } - - // Check if the command is array element - private boolean isArrayElement() { - return (ctx != null) && (ctx.isArray()) && isExecutable(); - } - - private boolean isReference() { - return hasAttr("idref"); //$NON-NLS-1$ - } - - // Check if the command is root object - private boolean isRoot() { - return isTag("java"); //$NON-NLS-1$ - } - - // Check if the command is null - private boolean isNull() { - return isTag("null"); //$NON-NLS-1$ - } - - // Checks if the command could generate object - public boolean isExecutable() { - boolean result = isTag("object") || isTag("void") && hasAttr("class") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - && hasAttr("method") || isTag("array") || isPrimitive() //$NON-NLS-1$ //$NON-NLS-2$ - || isTag("class") || isTag("null"); //$NON-NLS-1$ //$NON-NLS-2$ - return result; - } - - private Argument getReferencedArgument(Map references) { - return references.get(getAttr("idref")).getResult(); //$NON-NLS-1$ - } - - // get a target through tag and attrs analysis - private Object getTarget(Map references) throws Exception { - if (target == null) { - if (isReference()) { - Command cmd = references.get(getAttr("idref")); //$NON-NLS-1$ - target = (cmd != null) ? cmd.getResultValue() : null; - } else if (isExecutable()) { - String className = null; - - if (isPrimitive()) { - className = getPrimitiveClassName(tagName); - } else if (isTag("class")) { //$NON-NLS-1$ - className = getPrimitiveClassName(tagName); - } else if (isConstructor() || isStaticMethod() || isField()) { - className = getAttr("class"); //$NON-NLS-1$ - } else if (isArray()) { - className = getAttr("class"); //$NON-NLS-1$ - Class componentType = isPrimitiveClassName(className) ? getPrimitiveClass(className) - : Class.forName(className, true, Thread - .currentThread().getContextClassLoader()); - className = Array.newInstance(componentType, 0).getClass() - .getName(); - } - - if (className != null) { - try { - target = Class.forName(className, true, Thread - .currentThread().getContextClassLoader()); - } catch (ClassNotFoundException e) { - target = Class.forName(className); - } - - if (isField()) { - String fieldName = getAttr("field"); //$NON-NLS-1$ - target = ((Class) target).getField(fieldName); - } - } else { - throw new Exception(Messages.getString( - "beans.42", className)); //$NON-NLS-1$ - } - } else if (ctx.isArray()) { - // target = ctx.getTarget(references); - target = Class.forName("java.lang.reflect.Array"); //$NON-NLS-1$ - } - } - return target; - } - - // set target to execute command on - private void setTarget(Object target) { - this.target = target; - } - - // Return a method name of command - private String getMethodName(Map references) - throws NoSuchMethodException, IntrospectionException, Exception { - if (methodName == null) { - String methodValue = null; - if (isTag("class")) { //$NON-NLS-1$ - addArgument(new Argument(String.class, data), 0); - methodValue = "forName"; //$NON-NLS-1$ - } else if (isPrimitive()) { - if (isTag("char")) { //$NON-NLS-1$ - if (data.length() != 1) { - throw new IntrospectionException(Messages.getString( - "beans.43", //$NON-NLS-1$ - data)); - } - addArgument(new Argument(char.class, Character.valueOf(data - .charAt(0))), 0); - } else { - addArgument(new Argument(String.class, data), 0); - } - methodValue = "new"; //$NON-NLS-1$ - } else if (isConstructor() || hasAttr("method", "new")) { //$NON-NLS-1$ //$NON-NLS-2$ - methodValue = "new"; //$NON-NLS-1$ - } else if (isArray()) { - methodValue = "new"; //$NON-NLS-1$ - int length = hasAttr("length") ? Integer //$NON-NLS-1$ - .parseInt(getAttr("length")) : getArgumentsNumber(); //$NON-NLS-1$ - copyArgumentsToCommands(); - addArgument(new Argument(int.class, Integer.valueOf(length)), 0); - } else if (hasAttr("property")) { //$NON-NLS-1$ - String propertyValue = getAttr("property"); //$NON-NLS-1$ - if (hasAttr("index")) { //$NON-NLS-1$ - addArgument(new Argument(int.class, new Integer( - getAttr("index"))), 0); //$NON-NLS-1$ - } - - BeanInfo beanInfo = Introspector.getBeanInfo(getTarget( - references).getClass()); - PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); - - boolean methodFound = false; - Method method = null; - for (PropertyDescriptor pd : pds) { - if (propertyValue.equals(pd.getName())) { - int argsNum = getArgumentsNumber(); - if (hasAttr("index")) { //$NON-NLS-1$ - IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd; - if (argsNum == 1) { - method = ipd.getIndexedReadMethod(); - } else if (argsNum == 0) { - method = ipd.getReadMethod(); - } - } else { - method = pd.getReadMethod(); - } - - if (method != null) { - methodFound = matchMethodParams(method, references); - } - - if (methodFound == false) { - if (hasAttr("index")) { //$NON-NLS-1$ - IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd; - if (argsNum == 2) { - method = ipd.getIndexedWriteMethod(); - } else if (argsNum == 1) { - method = ipd.getWriteMethod(); - } - } else { - method = pd.getWriteMethod(); - } - } - - if (method != null) { - methodFound = matchMethodParams(method, references); - } - } - } - - if (method == null) { - throw new NoSuchMethodException(Messages.getString( - "beans.44", //$NON-NLS-1$ - propertyValue)); - } - methodValue = method.getName(); - } else if (hasAttr("method")) { //$NON-NLS-1$ - if (hasAttr("index")) { //$NON-NLS-1$ - addArgument(new Argument(int.class, Integer - .valueOf(getAttr("index"))), 0); //$NON-NLS-1$ - } - methodValue = getAttr("method"); //$NON-NLS-1$ - } else if (hasAttr("index")) { //$NON-NLS-1$ - addArgument(new Argument(int.class, Integer - .valueOf(getAttr("index"))), 0); //$NON-NLS-1$ - methodValue = getArgumentsNumber() > 1 ? "set" : "get"; //$NON-NLS-1$ //$NON-NLS-2$ - if (ctx.isArray()) { - addArgument(ctx.getResult(), 0); - } - } else if (hasAttr("field")) { //$NON-NLS-1$ - addArgument(new Argument(Class.forName(getAttr("class"), true, //$NON-NLS-1$ - Thread.currentThread().getContextClassLoader())), 0); - - methodValue = "get"; //$NON-NLS-1$ - } else { - throw new Exception(Messages.getString("beans.45")); //$NON-NLS-1$ - } - methodName = methodValue; - } - return methodName; - } - - // return a list of arguments as of Argument type - private Argument[] getArguments() { - Argument[] args = new Argument[auxArguments.size() + arguments.size()]; - - for (int i = 0; i < auxArguments.size(); ++i) { - args[i] = auxArguments.elementAt(i); - } - for (int j = 0; j < arguments.size(); ++j) { - Command cmd = arguments.elementAt(j); - - if (cmd.getStatus() >= Command.COMMAND_EXECUTED) { - args[auxArguments.size() + j] = cmd.getResult(); - } else { - // System.out.println("arg: " + cmd.getResultValue()); - args = null; - break; - } - } - return args; - } - - // return argument values - private Object[] getArgumentsValues() { - Argument[] args = getArguments(); - Object[] result = new Object[args.length]; - for (int i = 0; i < args.length; ++i) { - result[i] = args[i].getValue(); - } - return result; - } - - // copy arguments to treat as commands - private void copyArgumentsToCommands() { - Iterator i = arguments.iterator(); - while (i.hasNext()) { - Command cmd = i.next(); - cmd.status = Command.CHILDREN_FILTERED; - operations.add(cmd); - } - arguments.clear(); - } - - // return number of arguments - private int getArgumentsNumber() { - return auxArguments.size() + arguments.size(); - } - - // return number of commands - // private int getOperationsNumber() { - // return operations.size(); - // } - - // add argument to the beginning of arguments - private void addArgument(Argument argument, int idx) { - auxArguments.insertElementAt(argument, idx); - } - - // Check if the name of class is primitive - public static boolean isPrimitiveClassName(String className) { - return className.equalsIgnoreCase("boolean") //$NON-NLS-1$ - || className.equalsIgnoreCase("byte") //$NON-NLS-1$ - || className.equalsIgnoreCase("char") //$NON-NLS-1$ - || className.equalsIgnoreCase("short") //$NON-NLS-1$ - || className.equalsIgnoreCase("int") //$NON-NLS-1$ - || className.equalsIgnoreCase("long") //$NON-NLS-1$ - || className.equalsIgnoreCase("float") //$NON-NLS-1$ - || className.equalsIgnoreCase("double") //$NON-NLS-1$ - || className.equalsIgnoreCase("string"); //$NON-NLS-1$ - } - - // Transforms a primitive class name - private String getPrimitiveClassName(String data) { - String shortClassName = null; - if (data.equals("int")) { //$NON-NLS-1$ - shortClassName = "Integer"; //$NON-NLS-1$ - } else if (data.equals("char")) { //$NON-NLS-1$ - shortClassName = "Character"; //$NON-NLS-1$ - } else { - shortClassName = data.substring(0, 1).toUpperCase() - + data.substring(1, data.length()); - } - return "java.lang." + shortClassName; //$NON-NLS-1$ - } - - public static Class getPrimitiveClass(String className) { - Class result = null; - if (className.equals("boolean")) { //$NON-NLS-1$ - result = boolean.class; - } else if (className.equals("byte")) { //$NON-NLS-1$ - result = byte.class; - } else if (className.equals("char")) { //$NON-NLS-1$ - result = char.class; - } else if (className.equals("short")) { //$NON-NLS-1$ - result = short.class; - } else if (className.equals("int")) { //$NON-NLS-1$ - result = int.class; - } else if (className.equals("long")) { //$NON-NLS-1$ - result = long.class; - } else if (className.equals("float")) { //$NON-NLS-1$ - result = float.class; - } else if (className.equals("double")) { //$NON-NLS-1$ - result = double.class; - } else if (className.equals("string")) { //$NON-NLS-1$ - result = String.class; - } - return result; - } - - private boolean matchMethodParams(Method method, Map references) { - Class[] paramTypes = method.getParameterTypes(); - Argument[] args = getArguments(); - if (args == null) { - return false; - } - boolean result = true; - if (paramTypes.length == args.length) { - for (int j = 0; j < paramTypes.length; ++j) { - // System.out.println("paramTypes[j] = " + paramTypes[j]); - // System.out.println("args[j] = " + args[j].getType()); - - boolean isAssignable = (args[j].getType() == null) ? !paramTypes[j] - .isPrimitive() - : paramTypes[j].isAssignableFrom(args[j].getType()); - - // System.out.println("args[j] = " + args[j].getType()); - - if (!isAssignable) { - result = false; - break; - } - } - } else { - result = false; - } - return result; - } - - public static Map parseAttrs(String tagName, Attributes attrs) { - Map result = new HashMap(); - if (tagName.equals("object")) { //$NON-NLS-1$ - for (String name : objectAttrNames) { - String value = attrs.getValue(name); - if (value != null) { - result.put(name, value); - } - } - } else if (tagName.equals("void")) { //$NON-NLS-1$ - for (String name : voidAttrNames) { - String value = attrs.getValue(name); - if (value != null) { - result.put(name, value); - } - } - } else if (tagName.equals("array")) { //$NON-NLS-1$ - for (String name : arrayAttrNames) { - String value = attrs.getValue(name); - if (value != null) { - result.put(name, value); - } - } - } else if (tagName.equals("java")) { //$NON-NLS-1$ - for (String name : javaAttrNames) { - String value = attrs.getValue(name); - if (value != null) { - result.put(name, value); - } - } - } - return result; - } - - // Auxiliary logging with tabs functions - public static void pr(String msg) { - // System.out.print(msg); - } - - public static void pr(int tabCount, String msg) { - String result = ""; //$NON-NLS-1$ - for (int i = 0; i < tabCount; ++i) { - result += '\t'; - } - result += msg; - // System.out.print(result); - } - - public static void prn(String msg) { - // System.out.println(msg); - } - - public static void prn(int tabCount, String msg) { - String result = ""; //$NON-NLS-1$ - for (int i = 0; i < tabCount; ++i) { - result += '\t'; - } - result += msg; - // System.out.println(result); - } - - public static void printAttrs(int tabCount, String tagName, Attributes attrs) { - pr(tabCount, tabCount + ">in <" + tagName); //$NON-NLS-1$ - for (int i = 0; i < attrs.getLength(); ++i) { - String attrName = attrs.getQName(i); - String attrValue = attrs.getValue(i); - pr(" " + attrName + "=" + attrValue); //$NON-NLS-1$ //$NON-NLS-2$ - } - prn(">"); //$NON-NLS-1$ - } - - private static int initializeStatus(String tagName) { - // return tagName.equals("java") ? Command.COMMAND_EXECUTED : - // Command.INITIALIZED; - return Command.INITIALIZED; - } - - // private static String translateStatus(int status) { - // String result = "unknown"; - // if(status == Command.INITIALIZED) { - // result = "initialized"; - // } else if(status == Command.CHILDREN_FILTERED) { - // result = "children filtered"; - // } else if(status == Command.COMMAND_EXECUTED) { - // result = "executed"; - // } else if(status == Command.CHILDREN_PROCESSED) { - // result = "children processed"; - // } - // return result; - // } - - private static final String[] objectAttrNames = { "id", "idref", "class", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - "field", "method", "property", "index" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - - private static final String[] voidAttrNames = { "id", "class", "method", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - "property", "index" }; //$NON-NLS-1$ //$NON-NLS-2$ - - private static final String[] arrayAttrNames = { "id", "class", "length" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - private static final String[] javaAttrNames = { "version", "class" }; //$NON-NLS-1$ //$NON-NLS-2$ + // operations + private Vector operations = new Vector(); + + // additional arguments placed before others + private Vector auxArguments = new Vector(); + + private Argument result; // result argument + + private Object target; // target to execute a command on + + private String methodName; // method name + + private Command ctx; // context for command + + private int status; // commands + + private XMLDecoder decoder; + + // private int tabCount = 0; + + public Command (String tagName, Map attrs) { + this.tagName = tagName; + this.attrs = attrs; + this.status = initializeStatus(tagName); + } + + public Command (XMLDecoder decoder, String tagName, Map attrs) { + this.decoder = decoder; + this.tagName = tagName; + this.attrs = attrs; + this.status = initializeStatus(tagName); + } + + // set data for command + public void setData (String data) { + this.data = data; + } + + // set tab count to display log messages + // public void setTabCount(int tabCount) { + // this.tabCount = tabCount; + // } + + // set context - upper level command + public void setContext (Command ctx) { + this.ctx = ctx; + } + + // add child command + public void addChild (Command cmd) { + if (cmd != null) { + cmd.setContext(this); + commands.add(cmd); + } + } + + // remove child command + public void removeChild (Command cmd) { + if ((cmd != null) && commands.remove(cmd)) { + cmd.setContext(null); + } + } + + // command status + public int getStatus () { + return status; + } + + // check if one of arguments or operations is unresolved + private boolean isResolved () { + if (getStatus() < Command.CHILDREN_PROCESSED) { + return false; + } + for (int i = 0; i < arguments.size(); ++i) { + Command arg = arguments.elementAt(i); + + if (!arg.isResolved()) { + return false; + } + } + for (int j = 0; j < operations.size(); ++j) { + Command opr = operations.elementAt(j); + + if (!opr.isResolved()) { + return false; + } + } + return true; + } + + // execute command and return execution flags + public int exec (Map references) throws Exception { + // System.out.println("in exec() status = " + translateStatus(status) + + // "..."); + if (status < Command.CHILDREN_PROCESSED) { + if (status < Command.COMMAND_EXECUTED) { + if (status < Command.CHILDREN_FILTERED) { + status = doBeforeRun(references); + // System.out.println("after doBeforeRun() status = " + + // translateStatus(status)); + } + if (status == Command.CHILDREN_FILTERED) { + status = doRun(references); + // System.out.println("after doRun() status = " + + // translateStatus(status)); + } + } + if (status == Command.COMMAND_EXECUTED) { + status = doAfterRun(references); + // System.out.println("after doAfterRun() status = " + + // translateStatus(status)); + } + } + // System.out.println("...out of exec() status = " + + // translateStatus(status)); + return status; + } + + // execute commands in backtrack order + public boolean backtrack (Map references) throws Exception { + for (int i = 0; i < arguments.size(); ++i) { + Command arg = arguments.elementAt(i); + arg.backtrack(references); + } + for (int i = 0; i < operations.size(); ++i) { + Command opr = operations.elementAt(i); + opr.backtrack(references); + } + if (status == Command.CHILDREN_FILTERED) { + status = doRun(references); + } + if (status == Command.COMMAND_EXECUTED) { + status = doAfterRun(references); + return (getStatus() == Command.CHILDREN_PROCESSED); + } + return false; + } + + // put command in one of two collections - arguments or operations + private int doBeforeRun (Map references) throws Exception { + if (status == Command.INITIALIZED) { + for (int i = 0; i < commands.size(); ++i) { + Command cmd = commands.elementAt(i); + + // XXX is this correct? + if (cmd.isExecutable()) { + arguments.add(cmd); + } else { + operations.add(cmd); + } + } + return Command.CHILDREN_FILTERED; + } + return status; + } + + // run command + private int doRun (Map references) throws Exception { + if (status == Command.CHILDREN_FILTERED) { + if (isRoot()) { + result = new Argument(decoder); + // System.out.println("doRun(): result is decoder..."); + return Command.COMMAND_EXECUTED; + } + + if (isNull()) { + result = new Argument(null); + // System.out.println("doRun(): result is null..."); + return Command.COMMAND_EXECUTED; + } + + if (ctx != null && ctx.isArray() && (ctx.getResultValue() == null) && !isExecutable()) { + // System.out.println("doRun(): context is array..."); + return status; + } + + Object target = getTarget(references); + if (target == null) { + // System.out.println("doRun(): target is null..."); + return status; + } + // if (target instanceof Class) { + // System.out.println("doRun(): target = " + + // ((Class)target).getName()); + // } else { + // System.out.println("doRun(): target = " + + // target.getClass().getName()); + // } + if (isReference()) { + result = getReferencedArgument(references); + // System.out.println("doRun(): reference - result is " + + // result.getType()); + } else { + String methodName = getMethodName(references); + // System.out.println("doRun(): methodName = " + + // methodName); + Argument[] arguments = getArguments(); + if (arguments == null) { + return status; + } + // for (Argument element : arguments) { + // if (element != null) { + // System.out.println("doRun(): arg [" + i + "] = " + // + arguments[i].getType()); + // } else { + // System.out.println("doRun(): arg [" + i + "] = + // null"); + // } + // } + + Expression expr = new Expression(target, methodName, getArgumentsValues()); + result = new Argument(expr.getValue()); + + if (isPrimitiveClassName(getTagName())) { + result.setType(getPrimitiveClass(tagName)); + } + + // System.out.println("doRun(): method call - result is " + + // result.getType()); + } + return Command.COMMAND_EXECUTED; + } + return status; + } + + // run child commands + private int doAfterRun (Map references) throws Exception { + if (status == Command.COMMAND_EXECUTED) { + // System.out.println("doAfterRun(): command " + getResultType() + " + // processed..."); + Vector toBeRemoved = new Vector(); + try { + Statement[] statements = null; + + for (int i = 0; i < operations.size(); ++i) { + Command cmd = operations.elementAt(i); + + if (cmd.isArrayElement()) { + + if (cmd.isResolved()) { + if (statements == null) { + statements = new Statement[operations.size()]; + } + statements[i] = new Statement(getResultValue(), "set", new Object[] {Integer.valueOf(i), //$NON-NLS-1$ + cmd.getResultValue()}); + if ((i + 1) == operations.size()) { + for (int j = 0; j < operations.size(); ++j) { + statements[j].execute(); + } + toBeRemoved.addAll(operations); + } + } else { + break; + } + + } else { + // since the call is Array.set() + if (!isArray()) { + cmd.setTarget(getResultValue()); + } + cmd.exec(references); + + if (cmd.isResolved()) { + // System.out.println("doAfterRun(): cmd = " + + // cmd.methodName + " is resolved"); + toBeRemoved.add(cmd); + } else { + // System.out.println("doAfterRun(): cmd = " + + // cmd.methodName + " is unresolved"); + break; + } + + } + + } + } catch (Exception e) { + throw new Exception(e); + } finally { + operations.removeAll(toBeRemoved); + } + + // if (operations.size() == 0) { + // System.out.println("doAfterRun(): command " + getResultType() + // + " completely processed."); + // } else { + // System.out.println("doAfterRun(): command " + getResultType() + // + " contains incomplete " + + // operations.size() + " commands."); + // } + return (operations.size() == 0) ? Command.CHILDREN_PROCESSED : status; + } + return status; + } + + // Result accessors + + // Return result - Argument class + public Argument getResult () { + return result; + } + + // Returns result value + public Object getResultValue () { + return (result != null) ? result.getValue() : null; + } + + // Returns result type + public Class getResultType () throws ClassNotFoundException { + return (result != null) ? result.getType() : null; + } + + // accessors to XML tags and attrs + public boolean hasAttr (String name) { + return attrs.get(name) != null; + } + + public String getAttr (String name) { + return attrs.get(name); + } + + public boolean isTag (String name) { + return tagName.equals(name); + } + + public boolean hasAttr (String name, String value) { + return value.equals(attrs.get(name)); + } + + public String getTagName () { + return tagName; + } + + // Checks if the object is primitive - int, float, etc... + private boolean isPrimitive () { + return isPrimitiveClassName(tagName); + } + + // Checks if the object is constructor + private boolean isConstructor () { + return isPrimitive() || !isStaticMethod() && !isMethod() && !isProperty() && !isField() && !isArray() && !isReference(); + } + + // Checks if the command is static method + private boolean isStaticMethod () { + return isTag("object") && hasAttr("method") || isTag("class"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + // Checks if the command is public method + private boolean isMethod () { + return isTag("void") && (hasAttr("method") || hasAttr("index")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + // Check if the command relates to property - getter ot setter depends on + // number of args + private boolean isProperty () { + return isTag("void") && hasAttr("property"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // Check if the command is field accessor + private boolean isField () { + return isTag("object") && hasAttr("field"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // Check if the command is array + private boolean isArray () { + return isTag("array"); //$NON-NLS-1$ + } + + // Check if the command is array element + private boolean isArrayElement () { + return (ctx != null) && (ctx.isArray()) && isExecutable(); + } + + private boolean isReference () { + return hasAttr("idref"); //$NON-NLS-1$ + } + + // Check if the command is root object + private boolean isRoot () { + return isTag("java"); //$NON-NLS-1$ + } + + // Check if the command is null + private boolean isNull () { + return isTag("null"); //$NON-NLS-1$ + } + + // Checks if the command could generate object + public boolean isExecutable () { + boolean result = isTag("object") || isTag("void") && hasAttr("class") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + && hasAttr("method") || isTag("array") || isPrimitive() //$NON-NLS-1$ //$NON-NLS-2$ + || isTag("class") || isTag("null"); //$NON-NLS-1$ //$NON-NLS-2$ + return result; + } + + private Argument getReferencedArgument (Map references) { + return references.get(getAttr("idref")).getResult(); //$NON-NLS-1$ + } + + // get a target through tag and attrs analysis + private Object getTarget (Map references) throws Exception { + if (target == null) { + if (isReference()) { + Command cmd = references.get(getAttr("idref")); //$NON-NLS-1$ + target = (cmd != null) ? cmd.getResultValue() : null; + } else if (isExecutable()) { + String className = null; + + if (isPrimitive()) { + className = getPrimitiveClassName(tagName); + } else if (isTag("class")) { //$NON-NLS-1$ + className = getPrimitiveClassName(tagName); + } else if (isConstructor() || isStaticMethod() || isField()) { + className = getAttr("class"); //$NON-NLS-1$ + } else if (isArray()) { + className = getAttr("class"); //$NON-NLS-1$ + Class componentType = isPrimitiveClassName(className) ? getPrimitiveClass(className) : Class.forName(className, + true, Thread.currentThread().getContextClassLoader()); + className = Array.newInstance(componentType, 0).getClass().getName(); + } + + if (className != null) { + try { + target = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); + } catch (ClassNotFoundException e) { + target = Class.forName(className); + } + + if (isField()) { + String fieldName = getAttr("field"); //$NON-NLS-1$ + target = ((Class)target).getField(fieldName); + } + } else { + throw new Exception(Messages.getString("beans.42", className)); //$NON-NLS-1$ + } + } else if (ctx.isArray()) { + // target = ctx.getTarget(references); + target = Class.forName("java.lang.reflect.Array"); //$NON-NLS-1$ + } + } + return target; + } + + // set target to execute command on + private void setTarget (Object target) { + this.target = target; + } + + // Return a method name of command + private String getMethodName (Map references) throws NoSuchMethodException, IntrospectionException, Exception { + if (methodName == null) { + String methodValue = null; + if (isTag("class")) { //$NON-NLS-1$ + addArgument(new Argument(String.class, data), 0); + methodValue = "forName"; //$NON-NLS-1$ + } else if (isPrimitive()) { + if (isTag("char")) { //$NON-NLS-1$ + if (data.length() != 1) { + throw new IntrospectionException(Messages.getString("beans.43", //$NON-NLS-1$ + data)); + } + addArgument(new Argument(char.class, Character.valueOf(data.charAt(0))), 0); + } else { + addArgument(new Argument(String.class, data), 0); + } + methodValue = "new"; //$NON-NLS-1$ + } else if (isConstructor() || hasAttr("method", "new")) { //$NON-NLS-1$ //$NON-NLS-2$ + methodValue = "new"; //$NON-NLS-1$ + } else if (isArray()) { + methodValue = "new"; //$NON-NLS-1$ + int length = hasAttr("length") ? Integer //$NON-NLS-1$ + .parseInt(getAttr("length")) : getArgumentsNumber(); //$NON-NLS-1$ + copyArgumentsToCommands(); + addArgument(new Argument(int.class, Integer.valueOf(length)), 0); + } else if (hasAttr("property")) { //$NON-NLS-1$ + String propertyValue = getAttr("property"); //$NON-NLS-1$ + if (hasAttr("index")) { //$NON-NLS-1$ + addArgument(new Argument(int.class, new Integer(getAttr("index"))), 0); //$NON-NLS-1$ + } + + BeanInfo beanInfo = Introspector.getBeanInfo(getTarget(references).getClass()); + PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); + + boolean methodFound = false; + Method method = null; + for (PropertyDescriptor pd : pds) { + if (propertyValue.equals(pd.getName())) { + int argsNum = getArgumentsNumber(); + if (hasAttr("index")) { //$NON-NLS-1$ + IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor)pd; + if (argsNum == 1) { + method = ipd.getIndexedReadMethod(); + } else if (argsNum == 0) { + method = ipd.getReadMethod(); + } + } else { + method = pd.getReadMethod(); + } + + if (method != null) { + methodFound = matchMethodParams(method, references); + } + + if (methodFound == false) { + if (hasAttr("index")) { //$NON-NLS-1$ + IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor)pd; + if (argsNum == 2) { + method = ipd.getIndexedWriteMethod(); + } else if (argsNum == 1) { + method = ipd.getWriteMethod(); + } + } else { + method = pd.getWriteMethod(); + } + } + + if (method != null) { + methodFound = matchMethodParams(method, references); + } + } + } + + if (method == null) { + throw new NoSuchMethodException(Messages.getString("beans.44", //$NON-NLS-1$ + propertyValue)); + } + methodValue = method.getName(); + } else if (hasAttr("method")) { //$NON-NLS-1$ + if (hasAttr("index")) { //$NON-NLS-1$ + addArgument(new Argument(int.class, Integer.valueOf(getAttr("index"))), 0); //$NON-NLS-1$ + } + methodValue = getAttr("method"); //$NON-NLS-1$ + } else if (hasAttr("index")) { //$NON-NLS-1$ + addArgument(new Argument(int.class, Integer.valueOf(getAttr("index"))), 0); //$NON-NLS-1$ + methodValue = getArgumentsNumber() > 1 ? "set" : "get"; //$NON-NLS-1$ //$NON-NLS-2$ + if (ctx.isArray()) { + addArgument(ctx.getResult(), 0); + } + } else if (hasAttr("field")) { //$NON-NLS-1$ + addArgument(new Argument(Class.forName(getAttr("class"), true, //$NON-NLS-1$ + Thread.currentThread().getContextClassLoader())), 0); + + methodValue = "get"; //$NON-NLS-1$ + } else { + throw new Exception(Messages.getString("beans.45")); //$NON-NLS-1$ + } + methodName = methodValue; + } + return methodName; + } + + // return a list of arguments as of Argument type + private Argument[] getArguments () { + Argument[] args = new Argument[auxArguments.size() + arguments.size()]; + + for (int i = 0; i < auxArguments.size(); ++i) { + args[i] = auxArguments.elementAt(i); + } + for (int j = 0; j < arguments.size(); ++j) { + Command cmd = arguments.elementAt(j); + + if (cmd.getStatus() >= Command.COMMAND_EXECUTED) { + args[auxArguments.size() + j] = cmd.getResult(); + } else { + // System.out.println("arg: " + cmd.getResultValue()); + args = null; + break; + } + } + return args; + } + + // return argument values + private Object[] getArgumentsValues () { + Argument[] args = getArguments(); + Object[] result = new Object[args.length]; + for (int i = 0; i < args.length; ++i) { + result[i] = args[i].getValue(); + } + return result; + } + + // copy arguments to treat as commands + private void copyArgumentsToCommands () { + Iterator i = arguments.iterator(); + while (i.hasNext()) { + Command cmd = i.next(); + cmd.status = Command.CHILDREN_FILTERED; + operations.add(cmd); + } + arguments.clear(); + } + + // return number of arguments + private int getArgumentsNumber () { + return auxArguments.size() + arguments.size(); + } + + // return number of commands + // private int getOperationsNumber() { + // return operations.size(); + // } + + // add argument to the beginning of arguments + private void addArgument (Argument argument, int idx) { + auxArguments.insertElementAt(argument, idx); + } + + // Check if the name of class is primitive + public static boolean isPrimitiveClassName (String className) { + return className.equalsIgnoreCase("boolean") //$NON-NLS-1$ + || className.equalsIgnoreCase("byte") //$NON-NLS-1$ + || className.equalsIgnoreCase("char") //$NON-NLS-1$ + || className.equalsIgnoreCase("short") //$NON-NLS-1$ + || className.equalsIgnoreCase("int") //$NON-NLS-1$ + || className.equalsIgnoreCase("long") //$NON-NLS-1$ + || className.equalsIgnoreCase("float") //$NON-NLS-1$ + || className.equalsIgnoreCase("double") //$NON-NLS-1$ + || className.equalsIgnoreCase("string"); //$NON-NLS-1$ + } + + // Transforms a primitive class name + private String getPrimitiveClassName (String data) { + String shortClassName = null; + if (data.equals("int")) { //$NON-NLS-1$ + shortClassName = "Integer"; //$NON-NLS-1$ + } else if (data.equals("char")) { //$NON-NLS-1$ + shortClassName = "Character"; //$NON-NLS-1$ + } else { + shortClassName = data.substring(0, 1).toUpperCase() + data.substring(1, data.length()); + } + return "java.lang." + shortClassName; //$NON-NLS-1$ + } + + public static Class getPrimitiveClass (String className) { + Class result = null; + if (className.equals("boolean")) { //$NON-NLS-1$ + result = boolean.class; + } else if (className.equals("byte")) { //$NON-NLS-1$ + result = byte.class; + } else if (className.equals("char")) { //$NON-NLS-1$ + result = char.class; + } else if (className.equals("short")) { //$NON-NLS-1$ + result = short.class; + } else if (className.equals("int")) { //$NON-NLS-1$ + result = int.class; + } else if (className.equals("long")) { //$NON-NLS-1$ + result = long.class; + } else if (className.equals("float")) { //$NON-NLS-1$ + result = float.class; + } else if (className.equals("double")) { //$NON-NLS-1$ + result = double.class; + } else if (className.equals("string")) { //$NON-NLS-1$ + result = String.class; + } + return result; + } + + private boolean matchMethodParams (Method method, Map references) { + Class[] paramTypes = method.getParameterTypes(); + Argument[] args = getArguments(); + if (args == null) { + return false; + } + boolean result = true; + if (paramTypes.length == args.length) { + for (int j = 0; j < paramTypes.length; ++j) { + // System.out.println("paramTypes[j] = " + paramTypes[j]); + // System.out.println("args[j] = " + args[j].getType()); + + boolean isAssignable = (args[j].getType() == null) ? !paramTypes[j].isPrimitive() : paramTypes[j] + .isAssignableFrom(args[j].getType()); + + // System.out.println("args[j] = " + args[j].getType()); + + if (!isAssignable) { + result = false; + break; + } + } + } else { + result = false; + } + return result; + } + + public static Map parseAttrs (String tagName, Attributes attrs) { + Map result = new HashMap(); + if (tagName.equals("object")) { //$NON-NLS-1$ + for (String name : objectAttrNames) { + String value = attrs.getValue(name); + if (value != null) { + result.put(name, value); + } + } + } else if (tagName.equals("void")) { //$NON-NLS-1$ + for (String name : voidAttrNames) { + String value = attrs.getValue(name); + if (value != null) { + result.put(name, value); + } + } + } else if (tagName.equals("array")) { //$NON-NLS-1$ + for (String name : arrayAttrNames) { + String value = attrs.getValue(name); + if (value != null) { + result.put(name, value); + } + } + } else if (tagName.equals("java")) { //$NON-NLS-1$ + for (String name : javaAttrNames) { + String value = attrs.getValue(name); + if (value != null) { + result.put(name, value); + } + } + } + return result; + } + + // Auxiliary logging with tabs functions + public static void pr (String msg) { + // System.out.print(msg); + } + + public static void pr (int tabCount, String msg) { + String result = ""; //$NON-NLS-1$ + for (int i = 0; i < tabCount; ++i) { + result += '\t'; + } + result += msg; + // System.out.print(result); + } + + public static void prn (String msg) { + // System.out.println(msg); + } + + public static void prn (int tabCount, String msg) { + String result = ""; //$NON-NLS-1$ + for (int i = 0; i < tabCount; ++i) { + result += '\t'; + } + result += msg; + // System.out.println(result); + } + + public static void printAttrs (int tabCount, String tagName, Attributes attrs) { + pr(tabCount, tabCount + ">in <" + tagName); //$NON-NLS-1$ + for (int i = 0; i < attrs.getLength(); ++i) { + String attrName = attrs.getQName(i); + String attrValue = attrs.getValue(i); + pr(" " + attrName + "=" + attrValue); //$NON-NLS-1$ //$NON-NLS-2$ + } + prn(">"); //$NON-NLS-1$ + } + + private static int initializeStatus (String tagName) { + // return tagName.equals("java") ? Command.COMMAND_EXECUTED : + // Command.INITIALIZED; + return Command.INITIALIZED; + } + + // private static String translateStatus(int status) { + // String result = "unknown"; + // if(status == Command.INITIALIZED) { + // result = "initialized"; + // } else if(status == Command.CHILDREN_FILTERED) { + // result = "children filtered"; + // } else if(status == Command.COMMAND_EXECUTED) { + // result = "executed"; + // } else if(status == Command.CHILDREN_PROCESSED) { + // result = "children processed"; + // } + // return result; + // } + + private static final String[] objectAttrNames = {"id", "idref", "class", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "field", "method", "property", "index"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + + private static final String[] voidAttrNames = {"id", "class", "method", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "property", "index"}; //$NON-NLS-1$ //$NON-NLS-2$ + + private static final String[] arrayAttrNames = {"id", "class", "length"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + private static final String[] javaAttrNames = {"version", "class"}; //$NON-NLS-1$ //$NON-NLS-2$ } diff --git a/extensions/beans/src/org/apache/harmony/beans/Handler.java b/extensions/beans/src/org/apache/harmony/beans/Handler.java index 8b69226469d..818574d5d4d 100644 --- a/extensions/beans/src/org/apache/harmony/beans/Handler.java +++ b/extensions/beans/src/org/apache/harmony/beans/Handler.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.Stack; import java.util.Vector; + import org.apache.harmony.beans.internal.nls.Messages; import org.xml.sax.Attributes; import org.xml.sax.SAXException; @@ -30,118 +31,113 @@ public class Handler extends DefaultHandler { - private Vector result; - - private Vector commands; - - private XMLDecoder decoder; - - private Map references; - - private Stack stack; - - private int tabCount; - - public Handler(XMLDecoder decoder, Vector result) { - this.decoder = decoder; - this.result = result; - this.commands = new Vector(); - this.references = new HashMap(); - this.stack = new Stack(); - } - - // clear collections to prepare parsing document - @Override - public void startDocument() { - references.clear(); - tabCount = 0; - } - - // create new command and put it on stack - @Override - public void startElement(String namespaceURI, String localeName, - String tagName, Attributes attrs) throws SAXException { - Command.printAttrs(tabCount, tagName, attrs); - Command cmd = tagName.equals("java") ? new Command(decoder, tagName, //$NON-NLS-1$ - Command.parseAttrs(tagName, attrs)) : new Command(tagName, - Command.parseAttrs(tagName, attrs)); - stack.push(cmd); - ++tabCount; - } - - // add data to command - @Override - public void characters(char[] text, int start, int length) - throws SAXException { - if (length > 0) { - String data = String.valueOf(text, start, length) - .replace('\n', ' ').replace('\t', ' ').trim(); - if (data.length() > 0) { - Command.prn(tabCount, tabCount + ">setting data=" + data //$NON-NLS-1$ - + ""); //$NON-NLS-1$ - Command cmd = stack.peek(); - cmd.setData(data); - } - } - } - - // pop command from stack and put it to one of collections - @Override - public void endElement(String namespaceURI, String localeName, - String tagName) throws SAXException { - Command cmd = stack.pop(); - // cmd.setTabCount(tabCount); - - // find if command works in context - if (!stack.isEmpty()) { - Command ctx = stack.peek(); - ctx.addChild(cmd); - } - - // upper level commands - if (stack.size() == 1 && cmd.isExecutable()) { - commands.add(cmd); - } - - // store reference to command - if (cmd.hasAttr("id")) { //$NON-NLS-1$ - references.put(cmd.getAttr("id"), cmd); //$NON-NLS-1$ - } - - try { - cmd.exec(references); - } catch (Exception e) { - SAXException e2 = new SAXException(e.getMessage()); - - e2.initCause(e); - throw e2; - } - - if (--tabCount < 0) { - tabCount = 0; - } - - Command.prn(tabCount, tabCount + ">...<" + tagName + "> end"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - // iterate over deferred commands and execute them again - @Override - public void endDocument() throws SAXException { - for (int i = 0; i < commands.size(); ++i) { - Command cmd = commands.elementAt(i); - try { - cmd.backtrack(references); - } catch (Exception e) { - throw new SAXException(Messages.getString("beans.0B")); //$NON-NLS-1$ - } - // if(!backtracked) - // throw new SAXException("Command " + cmd.getTagName() + - // " is unresolved on second run() call."); - } - - for (int i = 0; i < commands.size(); ++i) { - Command cmd = commands.elementAt(i); - result.add(cmd.getResultValue()); - } - } + private Vector result; + + private Vector commands; + + private XMLDecoder decoder; + + private Map references; + + private Stack stack; + + private int tabCount; + + public Handler (XMLDecoder decoder, Vector result) { + this.decoder = decoder; + this.result = result; + this.commands = new Vector(); + this.references = new HashMap(); + this.stack = new Stack(); + } + + // clear collections to prepare parsing document + @Override + public void startDocument () { + references.clear(); + tabCount = 0; + } + + // create new command and put it on stack + @Override + public void startElement (String namespaceURI, String localeName, String tagName, Attributes attrs) throws SAXException { + Command.printAttrs(tabCount, tagName, attrs); + Command cmd = tagName.equals("java") ? new Command(decoder, tagName, //$NON-NLS-1$ + Command.parseAttrs(tagName, attrs)) : new Command(tagName, Command.parseAttrs(tagName, attrs)); + stack.push(cmd); + ++tabCount; + } + + // add data to command + @Override + public void characters (char[] text, int start, int length) throws SAXException { + if (length > 0) { + String data = String.valueOf(text, start, length).replace('\n', ' ').replace('\t', ' ').trim(); + if (data.length() > 0) { + Command.prn(tabCount, tabCount + ">setting data=" + data //$NON-NLS-1$ + + ""); //$NON-NLS-1$ + Command cmd = stack.peek(); + cmd.setData(data); + } + } + } + + // pop command from stack and put it to one of collections + @Override + public void endElement (String namespaceURI, String localeName, String tagName) throws SAXException { + Command cmd = stack.pop(); + // cmd.setTabCount(tabCount); + + // find if command works in context + if (!stack.isEmpty()) { + Command ctx = stack.peek(); + ctx.addChild(cmd); + } + + // upper level commands + if (stack.size() == 1 && cmd.isExecutable()) { + commands.add(cmd); + } + + // store reference to command + if (cmd.hasAttr("id")) { //$NON-NLS-1$ + references.put(cmd.getAttr("id"), cmd); //$NON-NLS-1$ + } + + try { + cmd.exec(references); + } catch (Exception e) { + SAXException e2 = new SAXException(e.getMessage()); + + e2.initCause(e); + throw e2; + } + + if (--tabCount < 0) { + tabCount = 0; + } + + Command.prn(tabCount, tabCount + ">...<" + tagName + "> end"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // iterate over deferred commands and execute them again + @Override + public void endDocument () throws SAXException { + for (int i = 0; i < commands.size(); ++i) { + Command cmd = commands.elementAt(i); + try { + cmd.backtrack(references); + } catch (Exception e) { + throw new SAXException(Messages.getString("beans.0B")); //$NON-NLS-1$ + } + // if(!backtracked) + // throw new SAXException("Command " + cmd.getTagName() + + // " is unresolved on second run() call."); + } + + for (int i = 0; i < commands.size(); ++i) { + Command cmd = commands.elementAt(i); + result.add(cmd.getResultValue()); + } + } } diff --git a/extensions/beans/src/org/apache/harmony/beans/internal/nls/Messages.java b/extensions/beans/src/org/apache/harmony/beans/internal/nls/Messages.java index b34f881e0bc..1ba77c97922 100644 --- a/extensions/beans/src/org/apache/harmony/beans/internal/nls/Messages.java +++ b/extensions/beans/src/org/apache/harmony/beans/internal/nls/Messages.java @@ -23,184 +23,140 @@ package org.apache.harmony.beans.internal.nls; - import java.util.MissingResourceException; import java.util.ResourceBundle; -/** - * This class retrieves strings from a resource bundle and returns them, - * formatting them with MessageFormat when required. +/** This class retrieves strings from a resource bundle and returns them, formatting them with MessageFormat when required. *

        - * It is used by the system classes to provide national language support, by - * looking up messages in the + * It is used by the system classes to provide national language support, by looking up messages in the * org.apache.harmony.beans.internal.nls.messages - * - * resource bundle. Note that if this file is not available, or an invalid key - * is looked up, or resource bundle support is not available, the key itself - * will be returned as the associated message. This means that the KEY - * should a reasonable human-readable (english) string. - * - */ + * resource bundle. Note that if this file is not available, or an invalid key is looked up, or resource bundle support is + * not available, the key itself will be returned as the associated message. This means that the KEY should a reasonable + * human-readable (english) string. */ public class Messages { - // ResourceBundle holding the system messages. - static private ResourceBundle bundle = null; + // ResourceBundle holding the system messages. + static private ResourceBundle bundle = null; + + /** Retrieves a message which has no arguments. + * + * @param msg String the key to look up. + * @return String the message for that key in the system message bundle. */ + static public String getString (String msg) { + if (bundle == null) return msg; + try { + return bundle.getString(msg); + } catch (MissingResourceException e) { + return "Missing message: " + msg; //$NON-NLS-1$ + } + } - /** - * Retrieves a message which has no arguments. - * - * @param msg - * String the key to look up. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg) { - if (bundle == null) - return msg; - try { - return bundle.getString(msg); - } catch (MissingResourceException e) { - return "Missing message: " + msg; //$NON-NLS-1$ - } - } + /** Retrieves a message which takes 1 argument. + * + * @param msg String the key to look up. + * @param arg Object the object to insert in the formatted output. + * @return String the message for that key in the system message bundle. */ + static public String getString (String msg, Object arg) { + return getString(msg, new Object[] {arg}); + } - /** - * Retrieves a message which takes 1 argument. - * - * @param msg - * String the key to look up. - * @param arg - * Object the object to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, Object arg) { - return getString(msg, new Object[] { arg }); - } + /** Retrieves a message which takes 1 integer argument. + * + * @param msg String the key to look up. + * @param arg int the integer to insert in the formatted output. + * @return String the message for that key in the system message bundle. */ + static public String getString (String msg, int arg) { + return getString(msg, new Object[] {Integer.toString(arg)}); + } - /** - * Retrieves a message which takes 1 integer argument. - * - * @param msg - * String the key to look up. - * @param arg - * int the integer to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, int arg) { - return getString(msg, new Object[] { Integer.toString(arg) }); - } + /** Retrieves a message which takes 1 character argument. + * + * @param msg String the key to look up. + * @param arg char the character to insert in the formatted output. + * @return String the message for that key in the system message bundle. */ + static public String getString (String msg, char arg) { + return getString(msg, new Object[] {String.valueOf(arg)}); + } - /** - * Retrieves a message which takes 1 character argument. - * - * @param msg - * String the key to look up. - * @param arg - * char the character to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, char arg) { - return getString(msg, new Object[] { String.valueOf(arg) }); - } + /** Retrieves a message which takes 2 arguments. + * + * @param msg String the key to look up. + * @param arg1 Object an object to insert in the formatted output. + * @param arg2 Object another object to insert in the formatted output. + * @return String the message for that key in the system message bundle. */ + static public String getString (String msg, Object arg1, Object arg2) { + return getString(msg, new Object[] {arg1, arg2}); + } - /** - * Retrieves a message which takes 2 arguments. - * - * @param msg - * String the key to look up. - * @param arg1 - * Object an object to insert in the formatted output. - * @param arg2 - * Object another object to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, Object arg1, Object arg2) { - return getString(msg, new Object[] { arg1, arg2 }); - } + /** Retrieves a message which takes several arguments. + * + * @param msg String the key to look up. + * @param args Object[] the objects to insert in the formatted output. + * @return String the message for that key in the system message bundle. */ + static public String getString (String msg, Object[] args) { + String format = msg; - /** - * Retrieves a message which takes several arguments. - * - * @param msg - * String the key to look up. - * @param args - * Object[] the objects to insert in the formatted output. - * @return String the message for that key in the system message bundle. - */ - static public String getString(String msg, Object[] args) { - String format = msg; + if (bundle != null) { + try { + format = bundle.getString(msg); + } catch (MissingResourceException e) { + } + } - if (bundle != null) { - try { - format = bundle.getString(msg); - } catch (MissingResourceException e) { - } - } + return format(format, args); + } - return format(format, args); - } - - /** - * Generates a formatted text string given a source string containing - * "argument markers" of the form "{argNum}" where each argNum must be in - * the range 0..9. The result is generated by inserting the toString of each - * argument into the position indicated in the string. - *

        - * To insert the "{" character into the output, use a single backslash - * character to escape it (i.e. "\{"). The "}" character does not need to be - * escaped. - * - * @param format - * String the format to use when printing. - * @param args - * Object[] the arguments to use. - * @return String the formatted message. - */ - public static String format(String format, Object[] args) { - StringBuilder answer = new StringBuilder(format.length() - + (args.length * 20)); - String[] argStrings = new String[args.length]; - for (int i = 0; i < args.length; ++i) { - if (args[i] == null) - argStrings[i] = ""; //$NON-NLS-1$ - else - argStrings[i] = args[i].toString(); - } - int lastI = 0; - for (int i = format.indexOf('{', 0); i >= 0; i = format.indexOf('{', - lastI)) { - if (i != 0 && format.charAt(i - 1) == '\\') { - // It's escaped, just print and loop. - if (i != 1) - answer.append(format.substring(lastI, i - 1)); - answer.append('{'); - lastI = i + 1; - } else { - // It's a format character. - if (i > format.length() - 3) { - // Bad format, just print and loop. - answer.append(format.substring(lastI, format.length())); - lastI = format.length(); - } else { - int argnum = (byte) Character.digit(format.charAt(i + 1), - 10); - if (argnum < 0 || format.charAt(i + 2) != '}') { - // Bad format, just print and loop. + /** Generates a formatted text string given a source string containing "argument markers" of the form "{argNum}" where each + * argNum must be in the range 0..9. The result is generated by inserting the toString of each argument into the position + * indicated in the string. + *

        + * To insert the "{" character into the output, use a single backslash character to escape it (i.e. "\{"). The "}" character + * does not need to be escaped. + * + * @param format String the format to use when printing. + * @param args Object[] the arguments to use. + * @return String the formatted message. */ + public static String format (String format, Object[] args) { + StringBuilder answer = new StringBuilder(format.length() + (args.length * 20)); + String[] argStrings = new String[args.length]; + for (int i = 0; i < args.length; ++i) { + if (args[i] == null) + argStrings[i] = ""; //$NON-NLS-1$ + else + argStrings[i] = args[i].toString(); + } + int lastI = 0; + for (int i = format.indexOf('{', 0); i >= 0; i = format.indexOf('{', lastI)) { + if (i != 0 && format.charAt(i - 1) == '\\') { + // It's escaped, just print and loop. + if (i != 1) answer.append(format.substring(lastI, i - 1)); + answer.append('{'); + lastI = i + 1; + } else { + // It's a format character. + if (i > format.length() - 3) { + // Bad format, just print and loop. + answer.append(format.substring(lastI, format.length())); + lastI = format.length(); + } else { + int argnum = (byte)Character.digit(format.charAt(i + 1), 10); + if (argnum < 0 || format.charAt(i + 2) != '}') { + // Bad format, just print and loop. answer.append(format.substring(lastI, i + 1)); lastI = i + 1; - } else { - // Got a good one! - answer.append(format.substring(lastI, i)); - if (argnum >= argStrings.length) - answer.append(""); //$NON-NLS-1$ - else - answer.append(argStrings[argnum]); + } else { + // Got a good one! + answer.append(format.substring(lastI, i)); + if (argnum >= argStrings.length) + answer.append(""); //$NON-NLS-1$ + else + answer.append(argStrings[argnum]); lastI = i + 3; - } - } - } - } - if (lastI < format.length()) - answer.append(format.substring(lastI, format.length())); - return answer.toString(); - } + } + } + } + } + if (lastI < format.length()) answer.append(format.substring(lastI, format.length())); + return answer.toString(); + } } diff --git a/extensions/gdx-remote/src/com/badlogic/gdx/remote/GdxRemote.java b/extensions/gdx-remote/src/com/badlogic/gdx/remote/GdxRemote.java index 490645b0fb1..28e87d8a699 100644 --- a/extensions/gdx-remote/src/com/badlogic/gdx/remote/GdxRemote.java +++ b/extensions/gdx-remote/src/com/badlogic/gdx/remote/GdxRemote.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.remote; import android.app.Activity; @@ -26,34 +27,36 @@ import android.widget.EditText; public class GdxRemote extends Activity { - - @Override public void onCreate (Bundle savedInstanceState) { + + @Override + public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final SharedPreferences prefs = getSharedPreferences("ip-settings", 0); String ip = prefs.getString("ip", "192.168.1.66"); String port = prefs.getString("port", "8190"); - + final EditText ipText = (EditText)findViewById(R.id.ip); final EditText portText = (EditText)findViewById(R.id.port); ipText.setText(ip); portText.setText(port); - + Button connect = (Button)findViewById(R.id.connect); - connect.setOnClickListener(new OnClickListener() { - @Override public void onClick (View v) { + connect.setOnClickListener(new OnClickListener() { + @Override + public void onClick (View v) { Editor edit = prefs.edit(); edit.putString("ip", ipText.getText().toString()); edit.putString("port", portText.getText().toString()); edit.commit(); - + Bundle bundle = new Bundle(); bundle.putString("ip", ipText.getText().toString()); bundle.putString("port", portText.getText().toString()); // Intent intent = new Intent(GdxRemote.this, UxAndroid.class); intent.putExtras(bundle); - startActivity(intent); + startActivity(intent); } }); } diff --git a/extensions/gdx-remote/src/com/badlogic/gdx/remote/UxAndroid.java b/extensions/gdx-remote/src/com/badlogic/gdx/remote/UxAndroid.java index 0898cd97086..dbc8bfaf9f6 100644 --- a/extensions/gdx-remote/src/com/badlogic/gdx/remote/UxAndroid.java +++ b/extensions/gdx-remote/src/com/badlogic/gdx/remote/UxAndroid.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.remote; import javax.microedition.khronos.opengles.GL10; @@ -32,70 +33,77 @@ public class UxAndroid extends AndroidApplication { String IP = null; int PORT = 0; RemoteSender sender; - - @Override public void onCreate (Bundle savedInstanceState) { + + @Override + public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getIntent().getExtras(); IP = bundle.getString("ip"); PORT = Integer.parseInt(bundle.getString("port")); Log.d("UxAndroid", "ip: " + IP + ", port: " + PORT); initialize(new ApplicationListener() { - + BitmapFont font; - SpriteBatch batch; + SpriteBatch batch; - @Override public void create () { + @Override + public void create () { new Thread(new Runnable() { - @Override public void run () { + @Override + public void run () { try { RemoteSender sender = new RemoteSender(IP, PORT); - synchronized(UxAndroid.this) { + synchronized (UxAndroid.this) { UxAndroid.this.sender = sender; } - } catch(GdxRuntimeException e) { - } + } catch (GdxRuntimeException e) { + } } - + }).start(); - + batch = new SpriteBatch(); font = new BitmapFont(); } - - @Override public void resume () { + + @Override + public void resume () { } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { batch.getProjectionMatrix().setToOrtho2D(0, 0, width, height); } - @Override public void render () { + @Override + public void render () { boolean connected = false; - synchronized(UxAndroid.this) { - if(sender != null) { + synchronized (UxAndroid.this) { + if (sender != null) { sender.sendUpdate(); connected = sender.isConnected(); } } - + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - batch.begin(); - if(connected) { - font.draw(batch, "accel:" + Gdx.input.getAccelerometerX() + ", " + - Gdx.input.getAccelerometerY() + ", " + - Gdx.input.getAccelerometerZ() + ", fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20); + batch.begin(); + if (connected) { + font.draw(batch, "accel:" + Gdx.input.getAccelerometerX() + ", " + Gdx.input.getAccelerometerY() + ", " + + Gdx.input.getAccelerometerZ() + ", fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20); } else { font.draw(batch, "No connection to " + IP + ":" + PORT, 10, 20); } - batch.end(); - } + batch.end(); + } - @Override public void pause () { + @Override + public void pause () { } - @Override public void dispose () { + @Override + public void dispose () { } }, false); diff --git a/extensions/model-loaders/model-loaders-android/src/com/badlogic/gdx/graphics/g3d/tests/ModelViewerActivity.java b/extensions/model-loaders/model-loaders-android/src/com/badlogic/gdx/graphics/g3d/tests/ModelViewerActivity.java index f3774b84770..2a05ebbed4d 100644 --- a/extensions/model-loaders/model-loaders-android/src/com/badlogic/gdx/graphics/g3d/tests/ModelViewerActivity.java +++ b/extensions/model-loaders/model-loaders-android/src/com/badlogic/gdx/graphics/g3d/tests/ModelViewerActivity.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.tests; import android.os.Bundle; @@ -5,21 +6,19 @@ import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.graphics.g3d.test.KeyframedModelViewer; -import com.badlogic.gdx.graphics.g3d.test.QbobViewer; -import com.badlogic.gdx.graphics.g3d.test.SkeletonModelViewer; public class ModelViewerActivity extends AndroidApplication { - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); - config.useAccelerometer = false; - config.useCompass = false; - config.useWakelock = true; - -// initialize(new QbobViewer(), config); - initialize(new KeyframedModelViewer("data/knight.g3d", "data/knight.jpg"), config); -// initialize(new SkeletonModelViewer("data/ninja.mesh.xml", "data/ninja.jpg"), config); - } -} \ No newline at end of file + /** Called when the activity is first created. */ + @Override + public void onCreate (Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); + config.useAccelerometer = false; + config.useCompass = false; + config.useWakelock = true; + +// initialize(new QbobViewer(), config); + initialize(new KeyframedModelViewer("data/knight.g3d", "data/knight.jpg"), config); +// initialize(new SkeletonModelViewer("data/ninja.mesh.xml", "data/ninja.jpg"), config); + } +} diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/AnimatedModelInstance.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/AnimatedModelInstance.java index edb8f4e0ae6..e22402981e4 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/AnimatedModelInstance.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/AnimatedModelInstance.java @@ -1,7 +1,10 @@ + package com.badlogic.gdx.graphics.g3d; public interface AnimatedModelInstance extends StillModelInstance { - public String getAnimation(); - public float getAnimationTime(); - public boolean isLooping(); + public String getAnimation (); + + public float getAnimationTime (); + + public boolean isLooping (); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelLoaderHints.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelLoaderHints.java index 11a2c79e936..33e85526d79 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelLoaderHints.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelLoaderHints.java @@ -1,17 +1,15 @@ + package com.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.graphics.g3d.loaders.ModelLoaderRegistry; -/** - * Hints passed to a loader which might ignore them. See {@link ModelLoaderRegistry}. - * @author mzechner - * - */ +/** Hints passed to a loader which might ignore them. See {@link ModelLoaderRegistry}. + * @author mzechner */ public class ModelLoaderHints { - /** whether to flip the v texture coordinate **/ + /** whether to flip the v texture coordinate **/ public final boolean flipV; - - public ModelLoaderHints(boolean flipV) { + + public ModelLoaderHints (boolean flipV) { this.flipV = flipV; } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelRenderer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelRenderer.java index caf059d388e..564812d2882 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelRenderer.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/ModelRenderer.java @@ -1,10 +1,14 @@ + package com.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.graphics.g3d.model.still.StillModel; public interface ModelRenderer { - public void begin(); - public void draw(StillModel model, StillModelInstance instance); - public void draw(StillModel model, AnimatedModelInstance instance); - public void end(); + public void begin (); + + public void draw (StillModel model, StillModelInstance instance); + + public void draw (StillModel model, AnimatedModelInstance instance); + + public void end (); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/StillModelInstance.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/StillModelInstance.java index 9bab6ca6df9..3c65e1f05ce 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/StillModelInstance.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/StillModelInstance.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.graphics.g3d.materials.Material; @@ -5,7 +6,9 @@ import com.badlogic.gdx.math.Vector3; public interface StillModelInstance { - public Matrix4 getTransform(); - public Vector3 getSortCenter(); - public Material[] getMaterials(); + public Matrix4 getTransform (); + + public Vector3 getSortCenter (); + + public Material[] getMaterials (); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/Test.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/Test.java index e7c6da57dc0..34dec46307a 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/Test.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/Test.java @@ -1,25 +1,25 @@ + package com.badlogic.gdx.graphics.g3d; public class Test { - public static void main(String[] argv) { - float accel = 10; - float time = 0.1f; - for(int i = 0; i < 10; i++) { - accel = accel - (accel * 0.1f) * time; + public static void main (String[] argv) { + float accel = 10; + float time = 0.1f; + for (int i = 0; i < 10; i++) { + accel = accel - (accel * 0.1f) * time; } System.out.println(accel); - - -// float acc30 = decay(0.1f, 10); -// float acc60 = decay(60, 10); -// System.out.println("decay@30: " + acc30 + ", decay@60: " + acc60); + +// float acc30 = decay(0.1f, 10); +// float acc60 = decay(60, 10); +// System.out.println("decay@30: " + acc30 + ", decay@60: " + acc60); } - - public static float decay(float fps, int seconds) { + + public static float decay (float fps, int seconds) { float acc = 100; float decayRate = 0.1f; - - for(float i = 0; i < fps * seconds; i++) { + + for (float i = 0; i < fps * seconds; i++) { float decay = acc * decayRate; acc = acc - decay * (1.0f / fps); System.out.println("frame #" + i + ": " + acc); diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/KeyframedModelLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/KeyframedModelLoader.java index 9c246f449af..fc010e33eca 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/KeyframedModelLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/KeyframedModelLoader.java @@ -1,14 +1,12 @@ + package com.badlogic.gdx.graphics.g3d.loaders; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g3d.ModelLoaderHints; import com.badlogic.gdx.graphics.g3d.model.keyframe.KeyframedModel; -/** - * Interface for classes loading {@link KeyframedModel} instances. - * @author mzechner - * - */ +/** Interface for classes loading {@link KeyframedModel} instances. + * @author mzechner */ public interface KeyframedModelLoader extends ModelLoader { - public KeyframedModel load(FileHandle handle, ModelLoaderHints hints); + public KeyframedModel load (FileHandle handle, ModelLoaderHints hints); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoader.java index fd325347456..83fe75a7b51 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoader.java @@ -1,17 +1,14 @@ + package com.badlogic.gdx.graphics.g3d.loaders; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g3d.ModelLoaderHints; import com.badlogic.gdx.graphics.g3d.model.Model; -/** - * Interface for all loaders. Loaders that need more files - * need to derrive the other file names by the given file. - * A bit of a hack, but most formats are self contained. +/** Interface for all loaders. Loaders that need more files need to derrive the other file names by the given file. A bit of a + * hack, but most formats are self contained. * - * @author mzechner - * - */ -public interface ModelLoader { - public Model load(FileHandle file, ModelLoaderHints hints); + * @author mzechner */ +public interface ModelLoader { + public Model load (FileHandle file, ModelLoaderHints hints); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoaderRegistry.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoaderRegistry.java index 5b211e073ad..f83f5ae6a0d 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoaderRegistry.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ModelLoaderRegistry.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders; import java.util.HashMap; @@ -21,16 +22,12 @@ import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Simple "pluggable" class for loading models. Keeps a list of {@link ModelLoader} instances - * on a per file suffix basis. Use one of the static methods to load a {@link Model}. The registry - * will then try out all the registered loaders for that extension and eventually return a Model - * or throw a {@link GdxRuntimeException}. Per default all loaders of libgdx except the {@link OgreXmlLoader} - * which won't work on Android due to the JAXB dependency. +/** Simple "pluggable" class for loading models. Keeps a list of {@link ModelLoader} instances on a per file suffix basis. Use one + * of the static methods to load a {@link Model}. The registry will then try out all the registered loaders for that extension and + * eventually return a Model or throw a {@link GdxRuntimeException}. Per default all loaders of libgdx except the + * {@link OgreXmlLoader} which won't work on Android due to the JAXB dependency. * - * @author mzechner - * - */ + * @author mzechner */ public class ModelLoaderRegistry { private static Map> loaders = new HashMap>(); private static Map> defaultHints = new HashMap>(); @@ -39,327 +36,335 @@ public class ModelLoaderRegistry { static { registerLoader("dae", new ColladaLoader(), new ModelLoaderHints(false)); registerLoader("obj", new ObjLoader(), new ModelLoaderHints(false)); - registerLoader("md2", new MD2Loader(), new MD2LoaderHints(0.2f) ); + registerLoader("md2", new MD2Loader(), new MD2LoaderHints(0.2f)); registerLoader("g3dt", new G3dtStillModelLoader(), new ModelLoaderHints(true)); registerLoader("g3dt", new G3dtKeyframedModelLoader(), new ModelLoaderHints(true)); - registerLoader("g3d", new G3dStillModelLoader(), new ModelLoaderHints(false)); + registerLoader("g3d", new G3dStillModelLoader(), new ModelLoaderHints(false)); registerLoader("g3d", new G3dKeyframedModelLoader(), new ModelLoaderHints(false)); } - - /** - * Registers a new loader with the registry. The extension will be used - * to match the loader against a file to be loaded. The extension will - * be compared case insensitive. If multiple loaders are registered per - * extension they will be tried on a file in the sequence they have been - * registered until one succeeds or none succeed. + + /** Registers a new loader with the registry. The extension will be used to match the loader against a file to be loaded. The + * extension will be compared case insensitive. If multiple loaders are registered per extension they will be tried on a file + * in the sequence they have been registered until one succeeds or none succeed. * * @param extension the extension string, e.g. "dae" or "obj" * @param loader the {@link ModelLoader} - * @param defaultHints the default {@link ModelLoaderHints} to be used with this loader. - */ - public static void registerLoader(String extension, ModelLoader loader, ModelLoaderHints defaultHints) { + * @param defaultHints the default {@link ModelLoaderHints} to be used with this loader. */ + public static void registerLoader (String extension, ModelLoader loader, ModelLoaderHints defaultHints) { Array loaders = ModelLoaderRegistry.loaders.get(extension); - if(loaders == null) { + if (loaders == null) { loaders = new Array(); ModelLoaderRegistry.loaders.put(extension.toLowerCase(), loaders); - } + } loaders.add(loader); - + Array hints = ModelLoaderRegistry.defaultHints.get(extension); - if(hints == null) { + if (hints == null) { hints = new Array(); ModelLoaderRegistry.defaultHints.put(extension.toLowerCase(), hints); } hints.add(defaultHints); } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. - * @param file the file to be loaded + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. + * @param file the file to be loaded * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static Model load(FileHandle file) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static Model load (FileHandle file) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - + Array loaders = ModelLoaderRegistry.loaders.get(extension); Array hints = ModelLoaderRegistry.defaultHints.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - if(hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); - + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + if (hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); + Model model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { + for (int i = 0; i < loaders.size; i++) { ModelLoader loader = loaders.get(i); ModelLoaderHints hint = hints.get(i); - try { + try { model = loader.load(file, hint); - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage() + "\n"); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage() + "\n"); } } - - if(model == null) throw new GdxRuntimeException(errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException(errors.toString()); + else + return model; } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. - * @param file the file to be loaded + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. + * @param file the file to be loaded * @param hints the {@link ModelLoaderHints} to use * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static Model load(FileHandle file, ModelLoaderHints hints) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static Model load (FileHandle file, ModelLoaderHints hints) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - - Array loaders = ModelLoaderRegistry.loaders.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - + + Array loaders = ModelLoaderRegistry.loaders.get(extension); + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + Model model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { - ModelLoader loader = loaders.get(i); - try { + for (int i = 0; i < loaders.size; i++) { + ModelLoader loader = loaders.get(i); + try { model = loader.load(file, hints); - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage() + "\n"); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage() + "\n"); } } - - if(model == null) throw new GdxRuntimeException(errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException(errors.toString()); + else + return model; } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. Uses only - * {@link StillModelLoader} instances. - * @param file the file to be loaded + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. Uses only {@link StillModelLoader} instances. + * @param file the file to be loaded * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static StillModel loadStillModel(FileHandle file) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static StillModel loadStillModel (FileHandle file) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - + Array loaders = ModelLoaderRegistry.loaders.get(extension); Array hints = ModelLoaderRegistry.defaultHints.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - if(hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); - + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + if (hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); + StillModel model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { + for (int i = 0; i < loaders.size; i++) { ModelLoader loader = loaders.get(i); ModelLoaderHints hint = hints.get(i); - try { - if(loader instanceof StillModelLoader) { + try { + if (loader instanceof StillModelLoader) { model = ((StillModelLoader)loader).load(file, hint); } - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage() + "\n"); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage() + "\n"); } } - - if(model == null) throw new GdxRuntimeException("Couldn't load model '" + file.name() + "', " + errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException("Couldn't load model '" + file.name() + "', " + errors.toString()); + else + return model; } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. Uses only - * {@link StillModelLoader} instances. - * @param file the file to be loaded + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. Uses only {@link StillModelLoader} instances. + * @param file the file to be loaded * @oaram hints the ModelLoaderHints to be used. * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static StillModel loadStillModel(FileHandle file, ModelLoaderHints hints) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static StillModel loadStillModel (FileHandle file, ModelLoaderHints hints) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - - Array loaders = ModelLoaderRegistry.loaders.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - + + Array loaders = ModelLoaderRegistry.loaders.get(extension); + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + StillModel model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { - ModelLoader loader = loaders.get(i); - try { - if(loader instanceof StillModelLoader) { + for (int i = 0; i < loaders.size; i++) { + ModelLoader loader = loaders.get(i); + try { + if (loader instanceof StillModelLoader) { model = ((StillModelLoader)loader).load(file, hints); } - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage() + "\n"); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage() + "\n"); } } - - if(model == null) throw new GdxRuntimeException("Couldn't load model '" + file.name() + "', " + errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException("Couldn't load model '" + file.name() + "', " + errors.toString()); + else + return model; } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. Uses only - * {@link KeyframedModelLoader} instances. - * @param file the file to be loaded + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. Uses only {@link KeyframedModelLoader} + * instances. + * @param file the file to be loaded * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static KeyframedModel loadKeyframedModel(FileHandle file) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static KeyframedModel loadKeyframedModel (FileHandle file) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - + Array loaders = ModelLoaderRegistry.loaders.get(extension); Array hints = ModelLoaderRegistry.defaultHints.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - if(hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); - + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + if (hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); + KeyframedModel model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { + for (int i = 0; i < loaders.size; i++) { ModelLoader loader = loaders.get(i); ModelLoaderHints hint = hints.get(i); try { - if(loader instanceof KeyframedModelLoader) { + if (loader instanceof KeyframedModelLoader) { model = ((KeyframedModelLoader)loader).load(file, hint); } - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage() + "\n"); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage() + "\n"); } } - - if(model == null) throw new GdxRuntimeException(errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException(errors.toString()); + else + return model; } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. Uses only - * {@link KeyframedModelLoader} instances. + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. Uses only {@link KeyframedModelLoader} + * instances. * @param file the file to be loaded - * @param hints the Model + * @param hints the Model * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static KeyframedModel loadKeyframedModel(FileHandle file, ModelLoaderHints hints) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static KeyframedModel loadKeyframedModel (FileHandle file, ModelLoaderHints hints) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - - Array loaders = ModelLoaderRegistry.loaders.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - + + Array loaders = ModelLoaderRegistry.loaders.get(extension); + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + KeyframedModel model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { - ModelLoader loader = loaders.get(i); + for (int i = 0; i < loaders.size; i++) { + ModelLoader loader = loaders.get(i); try { - if(loader instanceof KeyframedModelLoader) { + if (loader instanceof KeyframedModelLoader) { model = ((KeyframedModelLoader)loader).load(file, hints); } - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage() + "\n"); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage() + "\n"); } } - - if(model == null) throw new GdxRuntimeException(errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException(errors.toString()); + else + return model; } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. Uses only - * {@link SkeletonModelLoader} instances. - * @param file the file to be loaded + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. Uses only {@link SkeletonModelLoader} instances. + * @param file the file to be loaded * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static SkeletonModel loadSkeletonModel(FileHandle file) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static SkeletonModel loadSkeletonModel (FileHandle file) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - + Array loaders = ModelLoaderRegistry.loaders.get(extension); Array hints = ModelLoaderRegistry.defaultHints.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - if(hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); - + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + if (hints == null) throw new GdxRuntimeException("no default hints for extension '" + extension + "'"); + SkeletonModel model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { + for (int i = 0; i < loaders.size; i++) { ModelLoader loader = loaders.get(i); ModelLoaderHints hint = hints.get(i); try { - if(loader instanceof SkeletonModelLoader) { + if (loader instanceof SkeletonModelLoader) { model = ((SkeletonModelLoader)loader).load(file, hint); } - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage()); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage()); } } - - if(model == null) throw new GdxRuntimeException(errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException(errors.toString()); + else + return model; } - - /** - * Loads the specified file with one of the loaders registered with this - * ModelLoaderRegistry. Uses the extension to determine which loader to use. - * The comparison of extensions is done case insensitive. Uses only - * {@link SkeletonModelLoader} instances. - * @param file the file to be loaded + + /** Loads the specified file with one of the loaders registered with this ModelLoaderRegistry. Uses the extension to determine + * which loader to use. The comparison of extensions is done case insensitive. Uses only {@link SkeletonModelLoader} instances. + * @param file the file to be loaded * @param hints the ModelLoaderHints to use * @return the {@link Model} - * @throws GdxRuntimeException in case the model could not be loaded. - */ - public static SkeletonModel loadSkeletonModel(FileHandle file, ModelLoaderHints hints) { + * @throws GdxRuntimeException in case the model could not be loaded. */ + public static SkeletonModel loadSkeletonModel (FileHandle file, ModelLoaderHints hints) { String name = file.name(); int dotIndex = name.lastIndexOf('.'); - if (dotIndex == -1) throw new GdxRuntimeException("file '" + file.name() + "' does not have an extension that can be matched to a ModelLoader"); + if (dotIndex == -1) + throw new GdxRuntimeException("file '" + file.name() + + "' does not have an extension that can be matched to a ModelLoader"); String extension = name.substring(dotIndex + 1).toLowerCase(); - - Array loaders = ModelLoaderRegistry.loaders.get(extension); - if(loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); - + + Array loaders = ModelLoaderRegistry.loaders.get(extension); + if (loaders == null) throw new GdxRuntimeException("no loaders for extension '" + extension + "'"); + SkeletonModel model = null; StringBuilder errors = new StringBuilder(); - for(int i = 0; i < loaders.size; i++) { - ModelLoader loader = loaders.get(i); + for (int i = 0; i < loaders.size; i++) { + ModelLoader loader = loaders.get(i); try { - if(loader instanceof SkeletonModelLoader) { + if (loader instanceof SkeletonModelLoader) { model = ((SkeletonModelLoader)loader).load(file, hints); } - } catch(GdxRuntimeException e) { - errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + e.getMessage()); + } catch (GdxRuntimeException e) { + errors.append("Couldn't load '" + file.name() + "' with loader of type " + loader.getClass().getSimpleName() + ": " + + e.getMessage()); } } - - if(model == null) throw new GdxRuntimeException(errors.toString()); - else return model; + + if (model == null) + throw new GdxRuntimeException(errors.toString()); + else + return model; } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/SkeletonModelLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/SkeletonModelLoader.java index edd11657b7a..ad56e89cb2a 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/SkeletonModelLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/SkeletonModelLoader.java @@ -1,14 +1,12 @@ + package com.badlogic.gdx.graphics.g3d.loaders; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g3d.ModelLoaderHints; import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonModel; -/** - * Interface for classes loading {@link SkeletonModel} instances. - * @author mzechner - * - */ +/** Interface for classes loading {@link SkeletonModel} instances. + * @author mzechner */ public interface SkeletonModelLoader extends ModelLoader { - public SkeletonModel load(FileHandle file, ModelLoaderHints hints); + public SkeletonModel load (FileHandle file, ModelLoaderHints hints); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/StillModelLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/StillModelLoader.java index 5e17c9a50f7..cb5b1076f33 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/StillModelLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/StillModelLoader.java @@ -1,14 +1,12 @@ + package com.badlogic.gdx.graphics.g3d.loaders; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g3d.ModelLoaderHints; import com.badlogic.gdx.graphics.g3d.model.still.StillModel; -/** - * Interface for loaders loading {@link StillModel} instances. - * @author mzechner - * - */ -public interface StillModelLoader extends ModelLoader { - public StillModel load(FileHandle handle, ModelLoaderHints hints); +/** Interface for loaders loading {@link StillModel} instances. + * @author mzechner */ +public interface StillModelLoader extends ModelLoader { + public StillModel load (FileHandle handle, ModelLoaderHints hints); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/ColladaLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/ColladaLoader.java index 86e040011dc..eabbb539939 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/ColladaLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/ColladaLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.collada; import java.io.InputStream; @@ -15,68 +16,66 @@ import com.badlogic.gdx.utils.Xml.Element; public class ColladaLoader implements StillModelLoader { - public static StillModel loadStillModel(FileHandle handle) { + public static StillModel loadStillModel (FileHandle handle) { return loadStillModel(handle.read()); } - - public static StillModel loadStillModel(InputStream in) { + + public static StillModel loadStillModel (InputStream in) { Xml xml = new Xml(); Element root = null; try { root = xml.parse(in); - } catch(Exception e) { + } catch (Exception e) { throw new GdxRuntimeException("Couldn't load Collada model", e); } - + // get geometries Array geos = readGeometries(root); - + // convert geometries to meshes StillSubMesh[] meshes = createMeshes(geos); - + // create StillModel - StillModel model = new StillModel(meshes); + StillModel model = new StillModel(meshes); return model; } - - private static Array readGeometries(Element root) { + + private static Array readGeometries (Element root) { // check whether the library_geometries element is there Element colladaGeoLibrary = root.getChildByName("library_geometries"); - if(colladaGeoLibrary == null) throw new GdxRuntimeException("not element in file"); - + if (colladaGeoLibrary == null) throw new GdxRuntimeException("not element in file"); + // check for geometries Array colladaGeos = colladaGeoLibrary.getChildrenByName("geometry"); - if(colladaGeos.size == 0) throw new GdxRuntimeException("no elements in file"); - + if (colladaGeos.size == 0) throw new GdxRuntimeException("no elements in file"); + Array geometries = new Array(); - + // read in all geometries - for(int i = 0; i < colladaGeos.size; i++) { + for (int i = 0; i < colladaGeos.size; i++) { try { geometries.add(new Geometry(colladaGeos.get(i))); - } catch(GdxRuntimeException e) { + } catch (GdxRuntimeException e) { System.out.println("warning: " + e.getMessage()); } } - + return geometries; - } - - private static StillSubMesh[] createMeshes(Array geos) { + } + + private static StillSubMesh[] createMeshes (Array geos) { StillSubMesh[] meshes = new StillSubMesh[geos.size]; - for(int i = 0; i < geos.size; i++) { - StillSubMesh subMesh = new StillSubMesh(geos.get(i).id, geos.get(i).getMesh(), GL10.GL_TRIANGLES); - subMesh.material = new Material("Null Material"); + for (int i = 0; i < geos.size; i++) { + StillSubMesh subMesh = new StillSubMesh(geos.get(i).id, geos.get(i).getMesh(), GL10.GL_TRIANGLES); + subMesh.material = new Material("Null Material"); meshes[i] = subMesh; } - return meshes; - } + return meshes; + } - /** - * Loads all the meshes in a Collada file, does not interpret the visual_scene tag! - * Hints are ignored. - */ - @Override public StillModel load (FileHandle handle, ModelLoaderHints hints) { + /** Loads all the meshes in a Collada file, does not interpret the visual_scene tag! Hints are ignored. */ + @Override + public StillModel load (FileHandle handle, ModelLoaderHints hints) { return loadStillModel(handle); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Faces.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Faces.java index f4a7be0a924..a95cfef4492 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Faces.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Faces.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.collada; import java.util.Arrays; @@ -18,8 +19,8 @@ public class Faces { protected static final String TEXCOORD = "TEXCOORD"; protected static final String NORMAL = "NORMAL"; protected static final String TANGENT = "TEXTANGENT"; - protected static final String BITANGENT = "TEXBINORMAL"; - + protected static final String BITANGENT = "TEXBINORMAL"; + int count = 0; final Map sourcesMap; final Map mappings; @@ -30,237 +31,234 @@ public class Faces { int numVertices = 0; int numIndices = 0; int primitiveType = GL10.GL_TRIANGLES; - + public Faces (Element faces, Map mappings, Map sources) { this.sourcesMap = sources; this.mappings = mappings; parseVertices(faces); triangulate(faces); - this.numIndices = triangles.size; + this.numIndices = triangles.size; } - - /** - * Conditions the inputs for a triangles/polylist list of faces and - * generates unique vertices while merging duplicate vertices. - * @param faces - */ - private void parseVertices(Element faces) { + + /** Conditions the inputs for a triangles/polylist list of faces and generates unique vertices while merging duplicate vertices. + * @param faces */ + private void parseVertices (Element faces) { inputs = faces.getChildrenByName("input"); - if(inputs == null) throw new GdxRuntimeException("no elements in /"); - + if (inputs == null) throw new GdxRuntimeException("no elements in /"); + int[] offsets = new int[inputs.size]; - int stride = 0; - + int stride = 0; + // normalize source references, should use the URI/address scheme of Collada FIXME // calculate stride and prepare to untangle the index lists mess... sources = new Source[inputs.size]; - for(int i = 0; i < inputs.size; i++) { + for (int i = 0; i < inputs.size; i++) { Element input = inputs.get(i); - + // map source if it was defined in tag String source = input.getAttribute("source").substring(1); - if(mappings.containsKey(source)) { + if (mappings.containsKey(source)) { input.setAttribute("source", mappings.get(source)); } else { input.setAttribute("source", source); } - + // check whether source exists source = input.getAttribute("source"); - if(!sourcesMap.containsKey(source)) throw new GdxRuntimeException("source '" + source + "' not in mesh> but in "); + if (!sourcesMap.containsKey(source)) + throw new GdxRuntimeException("source '" + source + "' not in mesh> but in "); sources[i] = sourcesMap.get(source); offsets[i] = Integer.parseInt(input.getAttribute("offset")); - stride = Math.max(offsets[i], stride); + stride = Math.max(offsets[i], stride); } - + // addjust for zero source offsets stride += 1; - + // parse

        indices, yeah, that takes up a bit more memory. String[] tokens = faces.getChildByName("p").getText().split("\\s+"); int[] indices = new int[tokens.length]; - for(int i = 0; i < tokens.length; i++) { + for (int i = 0; i < tokens.length; i++) { indices[i] = Integer.parseInt(tokens[i]); } - + // untangle indices on a per source basis Map indicesSet = new HashMap(); VertexIndices vertex = new VertexIndices(inputs.size); triangles = new Array(indices.length / stride); vertices = new Array(indices.length / stride); int index = 0; - for(int i = 0; i < indices.length; i+= stride) { - for(int j = 0; j < inputs.size; j++) { - vertex.indices[j] = indices[i+offsets[j]]; + for (int i = 0; i < indices.length; i += stride) { + for (int j = 0; j < inputs.size; j++) { + vertex.indices[j] = indices[i + offsets[j]]; vertex.index = index; } - + VertexIndices lookup = indicesSet.get(vertex); - if(lookup != null) { + if (lookup != null) { triangles.add(lookup); } else { triangles.add(vertex); vertices.add(vertex); - indicesSet.put(vertex, vertex); + indicesSet.put(vertex, vertex); vertex = new VertexIndices(inputs.size); index++; - } - } + } + } numVertices = index; - } - - /** - * This method triangulates the faces if they are given as a polylist. Does - * nothing in case the faces are given as triangles already. - * - * @param polyList - */ - private void triangulate(Element polyList) { - if(!polyList.getName().equals("polylist")) return; - + } + + /** This method triangulates the faces if they are given as a polylist. Does nothing in case the faces are given as triangles + * already. + * + * @param polyList */ + private void triangulate (Element polyList) { + if (!polyList.getName().equals("polylist")) return; + Element colladaPolys = polyList.getChildByName("vcount"); - if(colladaPolys == null) throw new GdxRuntimeException(" does not contain element"); - + if (colladaPolys == null) throw new GdxRuntimeException(" does not contain element"); + String[] tokens = colladaPolys.getText().split("\\s+"); int[] polys = new int[tokens.length]; int vertexCount = 0; - for(int i = 0;i < tokens.length; i++) { + for (int i = 0; i < tokens.length; i++) { int verts = Integer.parseInt(tokens[i]); polys[i] = verts; - vertexCount += verts; + vertexCount += verts; } - + Array newVertices = new Array(vertexCount); int idx = 0; - for(int i = 0; i < polys.length; i++) { + for (int i = 0; i < polys.length; i++) { int numVertices = polys[i]; VertexIndices baseVertex = triangles.get(idx++); - for(int j = 1; j < numVertices-1; j++) { + for (int j = 1; j < numVertices - 1; j++) { newVertices.add(baseVertex); newVertices.add(triangles.get(idx)); - newVertices.add(triangles.get(idx+1)); + newVertices.add(triangles.get(idx + 1)); idx++; } idx++; } triangles = newVertices; } - - public Mesh getMesh () { + + public Mesh getMesh () { float[] verts = new float[getVertexSize() * numVertices]; short[] indices = new short[numIndices]; VertexAttribute[] attributes = getVertexAttributes(); - - for(int i = 0; i < numIndices; i++) { + + for (int i = 0; i < numIndices; i++) { VertexIndices vertex = triangles.get(i); - if(vertex.index > Short.MAX_VALUE || - vertex.index < Short.MIN_VALUE) throw new GdxRuntimeException("index to big for short: " + vertex.index); + if (vertex.index > Short.MAX_VALUE || vertex.index < Short.MIN_VALUE) + throw new GdxRuntimeException("index to big for short: " + vertex.index); indices[i] = (short)vertex.index; - } - - int idx = 0; + } + + int idx = 0; int destOffset = 0; - - for(int i = 0; i < vertices.size; i++) { + + for (int i = 0; i < vertices.size; i++) { VertexIndices vertex = vertices.get(i); - - for(int j = 0; j < sources.length; j++) { + + for (int j = 0; j < sources.length; j++) { Source source = sources[j]; float[] data = source.data; int index = vertex.indices[j]; - int components = source.components; + int components = source.components; int sourceOffset = index * components; - - for(int k = 0; k < components; k++) { - if((attributes[j].usage == Usage.TextureCoordinates) && k == 1) { - verts[destOffset++] = 1- data[sourceOffset++]; + + for (int k = 0; k < components; k++) { + if ((attributes[j].usage == Usage.TextureCoordinates) && k == 1) { + verts[destOffset++] = 1 - data[sourceOffset++]; } else { verts[destOffset++] = data[sourceOffset++]; } - } - } + } + } } - + Mesh mesh = new Mesh(true, vertices.size, indices.length, attributes); mesh.setVertices(verts); mesh.setIndices(indices); return mesh; } - - private VertexAttribute[] getVertexAttributes() { + + private VertexAttribute[] getVertexAttributes () { VertexAttribute[] attributes = new VertexAttribute[inputs.size]; - + int texUnit = 0; - for(int i = 0; i < inputs.size; i++) { + for (int i = 0; i < inputs.size; i++) { Element input = inputs.get(i); String semantic = input.getAttribute("semantic"); Source source = sourcesMap.get(input.getAttribute("source")); - + int usage = getVertexAttributeUsage(semantic); int components = source.components; String alias = getVertexAttributeAlias(semantic); - if(alias.equals(ShaderProgram.TEXCOORD_ATTRIBUTE)) alias += texUnit++; + if (alias.equals(ShaderProgram.TEXCOORD_ATTRIBUTE)) alias += texUnit++; attributes[i] = new VertexAttribute(usage, components, alias); } return attributes; - } + } - private int getVertexSize() { + private int getVertexSize () { int size = 0; - for(int i = 0; i < inputs.size; i++) { + for (int i = 0; i < inputs.size; i++) { size += sourcesMap.get(inputs.get(i).getAttribute("source")).components; } return size; } - - private int getVertexAttributeUsage(String attribute) { - if(attribute.equals(VERTEX)) return Usage.Position; - if(attribute.equals(TEXCOORD)) return Usage.TextureCoordinates; - if(attribute.equals(NORMAL)) return Usage.Normal; + + private int getVertexAttributeUsage (String attribute) { + if (attribute.equals(VERTEX)) return Usage.Position; + if (attribute.equals(TEXCOORD)) return Usage.TextureCoordinates; + if (attribute.equals(NORMAL)) return Usage.Normal; return Usage.Generic; - } - + } + private String getVertexAttributeAlias (String attribute) { - if(attribute.equals(VERTEX)) return ShaderProgram.POSITION_ATTRIBUTE; - if(attribute.equals(TEXCOORD)) return ShaderProgram.TEXCOORD_ATTRIBUTE; - if(attribute.equals(NORMAL)) return ShaderProgram.NORMAL_ATTRIBUTE; - if(attribute.equals(TANGENT)) return ShaderProgram.TANGENT_ATTRIBUTE; - if(attribute.equals(BITANGENT)) return ShaderProgram.BINORMAL_ATTRIBUTE; - throw new GdxRuntimeException("can't map semantic '" + attribute + "' to alias, must be VERTEX, TEXCOORD, NORMAL, TANGENT or BITANGENT"); + if (attribute.equals(VERTEX)) return ShaderProgram.POSITION_ATTRIBUTE; + if (attribute.equals(TEXCOORD)) return ShaderProgram.TEXCOORD_ATTRIBUTE; + if (attribute.equals(NORMAL)) return ShaderProgram.NORMAL_ATTRIBUTE; + if (attribute.equals(TANGENT)) return ShaderProgram.TANGENT_ATTRIBUTE; + if (attribute.equals(BITANGENT)) return ShaderProgram.BINORMAL_ATTRIBUTE; + throw new GdxRuntimeException("can't map semantic '" + attribute + + "' to alias, must be VERTEX, TEXCOORD, NORMAL, TANGENT or BITANGENT"); } - - /** - * Helper class that stores a vertex in form of - * indices into sources. + + /** Helper class that stores a vertex in form of indices into sources. * - * @author mzechner - * - */ + * @author mzechner */ static class VertexIndices { int[] indices; int index; - - public VertexIndices(int size) { + + public VertexIndices (int size) { this.indices = new int[size]; } - @Override public int hashCode () { + + @Override + public int hashCode () { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(indices); return result; } - @Override public boolean equals (Object obj) { + + @Override + public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VertexIndices other = (VertexIndices)obj; if (!Arrays.equals(indices, other.indices)) return false; return true; - } - + } + @Override - public String toString() { + public String toString () { return index + ": " + Arrays.toString(indices); } } -} \ No newline at end of file +} diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Geometry.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Geometry.java index 7c99033dfec..cf2c167b0b9 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Geometry.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Geometry.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.collada; import java.util.HashMap; @@ -9,49 +10,48 @@ import com.badlogic.gdx.utils.Xml.Element; public class Geometry { - public String id; - public Faces faces; + public String id; + public Faces faces; - public Geometry(Element colladaGeo) { + public Geometry (Element colladaGeo) { id = colladaGeo.getAttribute("id"); - + // we only support geometries. Element colladaMesh = colladaGeo.getChildByName("mesh"); - if(colladaMesh == null) throw new GdxRuntimeException("no in '" + id + "'"); - + if (colladaMesh == null) throw new GdxRuntimeException("no in '" + id + "'"); + // collect sources and store them in Geometry Array colladaSources = colladaMesh.getChildrenByName("source"); Map sources = new HashMap(); - for(int j = 0; j < colladaSources.size; j++) { + for (int j = 0; j < colladaSources.size; j++) { Element colladaSource = colladaSources.get(j); - sources.put(colladaSource.getAttribute("id"),new Source(colladaSource)); + sources.put(colladaSource.getAttribute("id"), new Source(colladaSource)); } - + // read vertices map (this is pretty much bollocks FIXME). Map mappings = new HashMap(); Element vertices = colladaMesh.getChildByName("vertices"); - if(vertices != null) { + if (vertices != null) { Array inputs = vertices.getChildrenByName("input"); - for(int j = 0; j < inputs.size; j++) { + for (int j = 0; j < inputs.size; j++) { Element input = inputs.get(j); - if(!input.getAttribute("semantic").equals("POSITION")) continue; // FIXME, baaad assumption... + if (!input.getAttribute("semantic").equals("POSITION")) continue; // FIXME, baaad assumption... mappings.put(vertices.getAttribute("id"), input.getAttribute("source").substring(1)); } } - + // read faces - Element colladaFaces = null; - if((colladaFaces = colladaMesh.getChildByName("triangles")) != null) { - faces = new Faces(colladaFaces, mappings, sources); - } else - if((colladaFaces = colladaMesh.getChildByName("polylist")) != null) { - faces = new Faces(colladaFaces, mappings, sources); + Element colladaFaces = null; + if ((colladaFaces = colladaMesh.getChildByName("triangles")) != null) { + faces = new Faces(colladaFaces, mappings, sources); + } else if ((colladaFaces = colladaMesh.getChildByName("polylist")) != null) { + faces = new Faces(colladaFaces, mappings, sources); } else { throw new GdxRuntimeException("no / element in geometry '" + colladaGeo.getAttribute("id") + "'"); - } + } } - - public Mesh getMesh() { + + public Mesh getMesh () { return faces.getMesh(); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Source.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Source.java index d0858449ac3..5ab9083b3fd 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Source.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/collada/Source.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.collada; import com.badlogic.gdx.utils.GdxRuntimeException; @@ -7,30 +8,30 @@ public class Source { String id; int components; int count; - float[] data; - + float[] data; + public Source (Element source) { this.id = source.getAttribute("id"); parseComponents(source); } - - private void parseComponents(Element source) { + + private void parseComponents (Element source) { Element floatArray = source.getChildByName("float_array"); - Element technique = source.getChildByName("technique_common"); - if(floatArray == null) throw new GdxRuntimeException("no element in source '" + id + "'"); - if(technique == null) throw new GdxRuntimeException("no element in source '" + id + "'"); + Element technique = source.getChildByName("technique_common"); + if (floatArray == null) throw new GdxRuntimeException("no element in source '" + id + "'"); + if (technique == null) throw new GdxRuntimeException("no element in source '" + id + "'"); Element accessor = technique.getChildByName("accessor"); - if(accessor == null) throw new GdxRuntimeException("no element in source '" + id + "'"); - + if (accessor == null) throw new GdxRuntimeException("no element in source '" + id + "'"); + // read number of elements, number of components per element (e.g. 3 for x, y, z) data = new float[Integer.parseInt(floatArray.getAttribute("count"))]; count = Integer.parseInt(accessor.getAttribute("count")); components = Integer.parseInt(accessor.getAttribute("stride")); - + // read elements into data[] String[] tokens = floatArray.getText().split("\\s+"); - for(int i = 0; i < tokens.length; i++) { + for (int i = 0; i < tokens.length; i++) { data[i] = Float.parseFloat(tokens[i]); - } + } } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dConstants.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dConstants.java index 0fabd257c46..84a17643155 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dConstants.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dConstants.java @@ -9,20 +9,20 @@ public class G3dConstants { // Unique IDs for chunk declarations public static final int G3D_ROOT = 0x4733441A; public static final int VERSION_INFO = 0x0001; - + // still model specific constants public static final int STILL_MODEL = 0x1000; public static final int STILL_SUBMESH = 0x1100; - + // keyframed model specific constants public static final int KEYFRAMED_MODEL = 0x2000; public static final int KEYFRAMED_SUBMESH = 0x2200; public static final int KEYFRAMED_ANIMATION = 0x2300; public static final int KEYFRAMED_FRAME = 0x2400; - + // constants used for all types of models, mostly to describe a mesh public static final int VERTEX_LIST = 0x1110; public static final int INDEX_LIST = 0x1111; public static final int VERTEX_ATTRIBUTES = 0x1120; - public static final int VERTEX_ATTRIBUTE = 0x1121; + public static final int VERTEX_ATTRIBUTE = 0x1121; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dLoader.java index bcfc31b4cc0..c16f2c93bab 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.g3d; import java.io.IOException; @@ -5,7 +6,6 @@ import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Mesh; -import com.badlogic.gdx.graphics.Mesh.VertexDataType; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.g3d.ModelLoaderHints; import com.badlogic.gdx.graphics.g3d.loaders.KeyframedModelLoader; @@ -23,181 +23,206 @@ import com.badlogic.gdx.utils.ObjectMap; public class G3dLoader { - public static StillModel loadStillModel(FileHandle handle) { + public static StillModel loadStillModel (FileHandle handle) { Chunk root = null; InputStream in = null; try { in = handle.read(); root = ChunkReader.readChunks(in); - + // check root tag - if(root.getId() != G3dConstants.G3D_ROOT) throw new GdxRuntimeException("Invalid root tag id: " + root.getId()); - + if (root.getId() != G3dConstants.G3D_ROOT) throw new GdxRuntimeException("Invalid root tag id: " + root.getId()); + // check version Chunk version = root.getChild(G3dConstants.VERSION_INFO); - if(version == null) throw new GdxRuntimeException("No version chunk found"); + if (version == null) throw new GdxRuntimeException("No version chunk found"); int major = version.readByte(); int minor = version.readByte(); - if(major != 0 || minor != 1) throw new GdxRuntimeException("Invalid version, required 0.1, got " + major + "." + minor); - + if (major != 0 || minor != 1) + throw new GdxRuntimeException("Invalid version, required 0.1, got " + major + "." + minor); + // read stillmodel - Chunk stillModel = root.getChild(G3dConstants.STILL_MODEL); - if(stillModel == null) throw new GdxRuntimeException("No stillmodel chunk found"); + Chunk stillModel = root.getChild(G3dConstants.STILL_MODEL); + if (stillModel == null) throw new GdxRuntimeException("No stillmodel chunk found"); int numSubMeshes = stillModel.readInt(); - + // read submeshes StillSubMesh[] meshes = new StillSubMesh[numSubMeshes]; Chunk[] meshChunks = stillModel.getChildren(G3dConstants.STILL_SUBMESH); - if(meshChunks.length != numSubMeshes) throw new GdxRuntimeException("Number of submeshes not equal to number specified in still model chunk, expected " + numSubMeshes + ", got " + meshChunks.length); - for(int i = 0; i < numSubMeshes; i++) { + if (meshChunks.length != numSubMeshes) + throw new GdxRuntimeException("Number of submeshes not equal to number specified in still model chunk, expected " + + numSubMeshes + ", got " + meshChunks.length); + for (int i = 0; i < numSubMeshes; i++) { // read submesh name and primitive type Chunk subMesh = meshChunks[i]; String name = subMesh.readString(); int primitiveType = subMesh.readInt(); - + // read attributes Chunk attributes = subMesh.getChild(G3dConstants.VERTEX_ATTRIBUTES); - if(attributes == null) throw new GdxRuntimeException("No vertex attribute chunk given"); + if (attributes == null) throw new GdxRuntimeException("No vertex attribute chunk given"); int numAttributes = attributes.readInt(); Chunk[] attributeChunks = attributes.getChildren(G3dConstants.VERTEX_ATTRIBUTE); - if(attributeChunks.length != numAttributes) new GdxRuntimeException("Number of attributes not equal to number specified in attributes chunk, expected " + numAttributes + ", got " + attributeChunks.length); + if (attributeChunks.length != numAttributes) + new GdxRuntimeException("Number of attributes not equal to number specified in attributes chunk, expected " + + numAttributes + ", got " + attributeChunks.length); VertexAttribute[] vertAttribs = new VertexAttribute[numAttributes]; - for(int j = 0; j < numAttributes; j++) { - vertAttribs[j] = new VertexAttribute(attributeChunks[j].readInt(), attributeChunks[j].readInt(), attributeChunks[j].readString()); + for (int j = 0; j < numAttributes; j++) { + vertAttribs[j] = new VertexAttribute(attributeChunks[j].readInt(), attributeChunks[j].readInt(), + attributeChunks[j].readString()); } - + // read vertices Chunk vertices = subMesh.getChild(G3dConstants.VERTEX_LIST); int numVertices = vertices.readInt(); float[] vertexData = vertices.readFloats(); - - // read indices + + // read indices Chunk indices = subMesh.getChild(G3dConstants.INDEX_LIST); int numIndices = indices.readInt(); short[] indexData = indices.readShorts(); - + StillSubMesh mesh = new StillSubMesh(name, new Mesh(true, numVertices, numIndices, vertAttribs), primitiveType); mesh.mesh.setVertices(vertexData); mesh.mesh.setIndices(indexData); mesh.material = new Material("default"); meshes[i] = mesh; } - - StillModel model = new StillModel(meshes); + + StillModel model = new StillModel(meshes); model.setMaterial(new Material("default")); return model; - } catch(IOException e) { - throw new GdxRuntimeException("Couldn't load still model from '" + handle.name() +"', " + e.getMessage(), e); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't load still model from '" + handle.name() + "', " + e.getMessage(), e); } finally { - if(in != null) try { in.close(); } catch(IOException e) { } - } + if (in != null) try { + in.close(); + } catch (IOException e) { + } + } } - - public static KeyframedModel loadKeyframedModel(FileHandle handle) { + + public static KeyframedModel loadKeyframedModel (FileHandle handle) { Chunk root = null; InputStream in = null; try { in = handle.read(); root = ChunkReader.readChunks(in); - + // check root tag - if(root.getId() != G3dConstants.G3D_ROOT) throw new GdxRuntimeException("Invalid root tag id: " + root.getId()); - + if (root.getId() != G3dConstants.G3D_ROOT) throw new GdxRuntimeException("Invalid root tag id: " + root.getId()); + // check version Chunk version = root.getChild(G3dConstants.VERSION_INFO); - if(version == null) throw new GdxRuntimeException("No version chunk found"); + if (version == null) throw new GdxRuntimeException("No version chunk found"); int major = version.readByte(); int minor = version.readByte(); - if(major != 0 || minor != 1) throw new GdxRuntimeException("Invalid version, required 0.1, got " + major + "." + minor); - + if (major != 0 || minor != 1) + throw new GdxRuntimeException("Invalid version, required 0.1, got " + major + "." + minor); + // read keyframed model - Chunk stillModel = root.getChild(G3dConstants.KEYFRAMED_MODEL); - if(stillModel == null) throw new GdxRuntimeException("No stillmodel chunk found"); + Chunk stillModel = root.getChild(G3dConstants.KEYFRAMED_MODEL); + if (stillModel == null) throw new GdxRuntimeException("No stillmodel chunk found"); int numSubMeshes = stillModel.readInt(); - + // read submeshes KeyframedSubMesh[] meshes = new KeyframedSubMesh[numSubMeshes]; Chunk[] meshChunks = stillModel.getChildren(G3dConstants.KEYFRAMED_SUBMESH); - if(meshChunks.length != numSubMeshes) throw new GdxRuntimeException("Number of submeshes not equal to number specified in still model chunk, expected " + numSubMeshes + ", got " + meshChunks.length); - for(int i = 0; i < numSubMeshes; i++) { + if (meshChunks.length != numSubMeshes) + throw new GdxRuntimeException("Number of submeshes not equal to number specified in still model chunk, expected " + + numSubMeshes + ", got " + meshChunks.length); + for (int i = 0; i < numSubMeshes; i++) { // read submesh name and primitive type Chunk subMesh = meshChunks[i]; String meshName = subMesh.readString(); int primitiveType = subMesh.readInt(); int animatedComponents = subMesh.readInt(); int numAnimations = subMesh.readInt(); - + // read attributes Chunk attributes = subMesh.getChild(G3dConstants.VERTEX_ATTRIBUTES); - if(attributes == null) throw new GdxRuntimeException("No vertex attribute chunk given"); + if (attributes == null) throw new GdxRuntimeException("No vertex attribute chunk given"); int numAttributes = attributes.readInt(); Chunk[] attributeChunks = attributes.getChildren(G3dConstants.VERTEX_ATTRIBUTE); - if(attributeChunks.length != numAttributes) new GdxRuntimeException("Number of attributes not equal to number specified in attributes chunk, expected " + numAttributes + ", got " + attributeChunks.length); + if (attributeChunks.length != numAttributes) + new GdxRuntimeException("Number of attributes not equal to number specified in attributes chunk, expected " + + numAttributes + ", got " + attributeChunks.length); VertexAttribute[] vertAttribs = new VertexAttribute[numAttributes]; - for(int j = 0; j < numAttributes; j++) { - vertAttribs[j] = new VertexAttribute(attributeChunks[j].readInt(), attributeChunks[j].readInt(), attributeChunks[j].readString()); + for (int j = 0; j < numAttributes; j++) { + vertAttribs[j] = new VertexAttribute(attributeChunks[j].readInt(), attributeChunks[j].readInt(), + attributeChunks[j].readString()); } - + // read static components, sort of like a bind pose mesh - Chunk vertices = subMesh.getChild(G3dConstants.VERTEX_LIST); + Chunk vertices = subMesh.getChild(G3dConstants.VERTEX_LIST); int numVertices = vertices.readInt(); float[] vertexData = vertices.readFloats(); - - // read indices + + // read indices Chunk indices = subMesh.getChild(G3dConstants.INDEX_LIST); int numIndices = indices.readInt(); short[] indexData = indices.readShorts(); - + // read animations ObjectMap animations = new ObjectMap(); Chunk[] animationChunks = subMesh.getChildren(G3dConstants.KEYFRAMED_ANIMATION); - if(numAnimations != animationChunks.length) throw new GdxRuntimeException("number of keyframed animations not equal to number specified in keyframed submesh chunk, was " + animationChunks.length + ", expected " + numAnimations); - for(int j = 0; j < numAnimations; j++) { + if (numAnimations != animationChunks.length) + throw new GdxRuntimeException( + "number of keyframed animations not equal to number specified in keyframed submesh chunk, was " + + animationChunks.length + ", expected " + numAnimations); + for (int j = 0; j < numAnimations; j++) { Chunk animationChunk = animationChunks[j]; String animationName = animationChunk.readString(); float frameDuration = animationChunk.readFloat(); - + // read keyframes int numKeyframes = animationChunk.readInt(); Keyframe[] keyframes = new Keyframe[numKeyframes]; Chunk[] keyframeChunks = animationChunk.getChildren(G3dConstants.KEYFRAMED_FRAME); - if(numKeyframes != keyframeChunks.length) throw new GdxRuntimeException("number of keyframes not equal to number specified in keyframed animation, was " + keyframeChunks.length + ", expected " + numKeyframes); - for(int k = 0; k < numKeyframes; k++) { + if (numKeyframes != keyframeChunks.length) + throw new GdxRuntimeException("number of keyframes not equal to number specified in keyframed animation, was " + + keyframeChunks.length + ", expected " + numKeyframes); + for (int k = 0; k < numKeyframes; k++) { Chunk keyframeChunk = keyframeChunks[k]; float timeStamp = keyframeChunk.readFloat(); float[] keyframeVertices = keyframeChunk.readFloats(); - + keyframes[k] = new Keyframe(timeStamp, keyframeVertices); } - + animations.put(animationName, new KeyframedAnimation(animationName, frameDuration, keyframes)); } - + Mesh mesh = new Mesh(false, numVertices, numIndices, vertAttribs); meshes[i] = new KeyframedSubMesh(meshName, mesh, vertexData, animations, animatedComponents, primitiveType); mesh.setVertices(vertexData); mesh.setIndices(indexData); } - - KeyframedModel model = new KeyframedModel(meshes); + + KeyframedModel model = new KeyframedModel(meshes); model.setMaterial(new Material("default")); return model; - } catch(IOException e) { - throw new GdxRuntimeException("Couldn't load still model from '" + handle.name() +"', " + e.getMessage(), e); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't load still model from '" + handle.name() + "', " + e.getMessage(), e); } finally { - if(in != null) try { in.close(); } catch(IOException e) { } - } + if (in != null) try { + in.close(); + } catch (IOException e) { + } + } } - + public static class G3dStillModelLoader implements StillModelLoader { - @Override public StillModel load (FileHandle handle, ModelLoaderHints hints) { + @Override + public StillModel load (FileHandle handle, ModelLoaderHints hints) { return G3dLoader.loadStillModel(handle); - } + } } - + public static class G3dKeyframedModelLoader implements KeyframedModelLoader { - @Override public KeyframedModel load (FileHandle handle, ModelLoaderHints hints) { + @Override + public KeyframedModel load (FileHandle handle, ModelLoaderHints hints) { return G3dLoader.loadKeyframedModel(handle); - } + } } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dtLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dtLoader.java index 7ae51f663ae..b31c1073d97 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dtLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/G3dtLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.g3d; import java.io.BufferedReader; @@ -27,301 +28,302 @@ import com.badlogic.gdx.utils.IntArray; import com.badlogic.gdx.utils.ObjectMap; -/** - * Class to import the G3D text format. - * @author mzechner - * - */ +/** Class to import the G3D text format. + * @author mzechner */ public class G3dtLoader { - public static KeyframedModel loadKeyframedModel(FileHandle handle, boolean flipV) { + public static KeyframedModel loadKeyframedModel (FileHandle handle, boolean flipV) { return loadKeyframedModel(handle.read(), flipV); } - - public static StillModel loadStillModel(FileHandle handle, boolean flipV) { + + public static StillModel loadStillModel (FileHandle handle, boolean flipV) { return loadStillModel(handle.read(), flipV); } - + static int lineNum = 0; static String line = null; - - public static StillModel loadStillModel(InputStream stream, boolean flipV) { + + public static StillModel loadStillModel (InputStream stream, boolean flipV) { BufferedReader in = new BufferedReader(new InputStreamReader(stream)); - + lineNum = 1; try { String version = readString(in); - if(!version.equals("g3dt-still-1.0")) throw new GdxRuntimeException("incorrect version"); + if (!version.equals("g3dt-still-1.0")) throw new GdxRuntimeException("incorrect version"); int numMeshes = readInt(in); StillSubMesh[] subMeshes = new StillSubMesh[numMeshes]; - for(int i = 0; i < numMeshes; i++) { + for (int i = 0; i < numMeshes; i++) { subMeshes[i] = readStillSubMesh(in, flipV); } - StillModel model = new StillModel(subMeshes); + StillModel model = new StillModel(subMeshes); return model; - } catch(Throwable e) { - throw new GdxRuntimeException("Couldn't read keyframed model, error in line " + lineNum + ", '" + line + "' : " + e.getMessage(), e); + } catch (Throwable e) { + throw new GdxRuntimeException("Couldn't read keyframed model, error in line " + lineNum + ", '" + line + "' : " + + e.getMessage(), e); } } - - private static StillSubMesh readStillSubMesh(BufferedReader in, boolean flipV) throws IOException { + + private static StillSubMesh readStillSubMesh (BufferedReader in, boolean flipV) throws IOException { String name = readString(in); IntArray indices = readFaces(in); int numVertices = readInt(in); - int numAttributes = readInt(in); - - if(!readString(in).equals("position")) throw new GdxRuntimeException("first attribute must be position."); + int numAttributes = readInt(in); + + if (!readString(in).equals("position")) throw new GdxRuntimeException("first attribute must be position."); int numUvs = 0; boolean hasNormals = false; - for(int i = 1; i < numAttributes; i++) { + for (int i = 1; i < numAttributes; i++) { String attributeType = readString(in); - - if(!attributeType.equals("normal") && !attributeType.equals("uv")) throw new GdxRuntimeException("attribute name must be normal or uv"); - - if(attributeType.equals("normal")) { - if(i != 1) throw new GdxRuntimeException("attribute normal must be second attribute"); + + if (!attributeType.equals("normal") && !attributeType.equals("uv")) + throw new GdxRuntimeException("attribute name must be normal or uv"); + + if (attributeType.equals("normal")) { + if (i != 1) throw new GdxRuntimeException("attribute normal must be second attribute"); hasNormals = true; } - if(attributeType.equals("uv")) { + if (attributeType.equals("uv")) { numUvs++; } - } - VertexAttribute[] vertexAttributes = createVertexAttributes(hasNormals, numUvs); + } + VertexAttribute[] vertexAttributes = createVertexAttributes(hasNormals, numUvs); int vertexSize = new VertexAttributes(vertexAttributes).vertexSize / 4; float[] vertices = new float[numVertices * vertexSize]; int idx = 0; - int uvOffset = hasNormals?6:3; - for(int i = 0; i < numVertices; i++) { + int uvOffset = hasNormals ? 6 : 3; + for (int i = 0; i < numVertices; i++) { readFloatArray(in, vertices, idx); - if(flipV) { - for(int j = idx + uvOffset + 1; j < idx + uvOffset + numUvs * 2; j+=2) { + if (flipV) { + for (int j = idx + uvOffset + 1; j < idx + uvOffset + numUvs * 2; j += 2) { vertices[j] = 1 - vertices[j]; } } - idx+=vertexSize; + idx += vertexSize; } - + Mesh mesh = new Mesh(true, numVertices, indices.size, vertexAttributes); mesh.setVertices(vertices); mesh.setIndices(convertToShortArray(indices)); return new StillSubMesh(name, mesh, GL10.GL_TRIANGLES); } - - public static KeyframedModel loadKeyframedModel(InputStream stream, boolean flipV) { + + public static KeyframedModel loadKeyframedModel (InputStream stream, boolean flipV) { BufferedReader in = new BufferedReader(new InputStreamReader(stream)); - + lineNum = 1; try { String version = readString(in); - if(!version.equals("g3dt-keyframed-1.0")) throw new GdxRuntimeException("incorrect version"); + if (!version.equals("g3dt-keyframed-1.0")) throw new GdxRuntimeException("incorrect version"); int numMeshes = readInt(in); KeyframedSubMesh[] subMeshes = new KeyframedSubMesh[numMeshes]; - for(int i = 0; i < numMeshes; i++) { + for (int i = 0; i < numMeshes; i++) { subMeshes[i] = readMesh(in, flipV); } - KeyframedModel model = new KeyframedModel(subMeshes); + KeyframedModel model = new KeyframedModel(subMeshes); model.setAnimation(model.getAnimations()[0].name, 0, false); return model; - } catch(Throwable e) { - throw new GdxRuntimeException("Couldn't read keyframed model, error in line " + lineNum + ", '" + line + "' : " + e.getMessage(), e); - } - } - - private static KeyframedSubMesh readMesh(BufferedReader in, boolean flipV) throws IOException { + } catch (Throwable e) { + throw new GdxRuntimeException("Couldn't read keyframed model, error in line " + lineNum + ", '" + line + "' : " + + e.getMessage(), e); + } + } + + private static KeyframedSubMesh readMesh (BufferedReader in, boolean flipV) throws IOException { String name = readString(in); IntArray indices = readFaces(in); int numVertices = readInt(in); - int numAttributes = readInt(in); - - if(!readString(in).equals("position")) throw new GdxRuntimeException("first attribute must be position."); + int numAttributes = readInt(in); + + if (!readString(in).equals("position")) throw new GdxRuntimeException("first attribute must be position."); Array uvSets = new Array(); boolean hasNormals = false; - for(int i = 1; i < numAttributes; i++) { + for (int i = 1; i < numAttributes; i++) { String attributeType = readString(in); - - if(!attributeType.equals("normal") && !attributeType.equals("uv")) throw new GdxRuntimeException("attribute name must be normal or uv"); - - if(attributeType.equals("normal")) { - if(i != 1) throw new GdxRuntimeException("attribute normal must be second attribute"); + + if (!attributeType.equals("normal") && !attributeType.equals("uv")) + throw new GdxRuntimeException("attribute name must be normal or uv"); + + if (attributeType.equals("normal")) { + if (i != 1) throw new GdxRuntimeException("attribute normal must be second attribute"); hasNormals = true; } - if(attributeType.equals("uv")) { + if (attributeType.equals("uv")) { uvSets.add(readUVSet(in, numVertices, flipV)); } } - int animatedComponents = hasNormals?6:3; - + int animatedComponents = hasNormals ? 6 : 3; + VertexAttribute[] vertexAttributes = createVertexAttributes(hasNormals, uvSets.size); - + int numAnimations = readInt(in); ObjectMap animations = new ObjectMap(numAnimations); - for(int i = 0; i < numAnimations; i++) { + for (int i = 0; i < numAnimations; i++) { String animationName = readString(in); int numKeyframes = readInt(in); - float frameDuration = readFloat(in); - + float frameDuration = readFloat(in); + Keyframe[] keyframes = new Keyframe[numKeyframes]; float time = 0; FloatArray vertex = new FloatArray(animatedComponents); - for(int frame = 0; frame < numKeyframes; frame++) { - float[] vertices = new float[numVertices*(animatedComponents)]; + for (int frame = 0; frame < numKeyframes; frame++) { + float[] vertices = new float[numVertices * (animatedComponents)]; int idx = 0; - for(int j = 0; j < numVertices; j++) { - idx = readFloatArray(in, vertices, idx); + for (int j = 0; j < numVertices; j++) { + idx = readFloatArray(in, vertices, idx); } - Keyframe keyframe = new Keyframe(time, vertices); + Keyframe keyframe = new Keyframe(time, vertices); keyframes[frame] = keyframe; - time += frameDuration; - } - + time += frameDuration; + } + KeyframedAnimation animation = new KeyframedAnimation(animationName, frameDuration, keyframes); animations.put(animationName, animation); - } - - KeyframedSubMesh mesh = new KeyframedSubMesh(name, - new Mesh(false, numVertices, indices.size, createVertexAttributes(hasNormals, uvSets.size)), - buildVertices(numVertices, hasNormals, uvSets), - animations, animatedComponents, - GL10.GL_TRIANGLES); + } + + KeyframedSubMesh mesh = new KeyframedSubMesh(name, new Mesh(false, numVertices, indices.size, createVertexAttributes( + hasNormals, uvSets.size)), buildVertices(numVertices, hasNormals, uvSets), animations, animatedComponents, + GL10.GL_TRIANGLES); mesh.mesh.setIndices(convertToShortArray(indices)); mesh.mesh.setVertices(mesh.blendedVertices); return mesh; } - private static float[] buildVertices(int numVertices, boolean hasNormals, Array uvSets) { - float[] vertices = new float[numVertices * (3 + (hasNormals?3:0) + uvSets.size * 2)]; - + private static float[] buildVertices (int numVertices, boolean hasNormals, Array uvSets) { + float[] vertices = new float[numVertices * (3 + (hasNormals ? 3 : 0) + uvSets.size * 2)]; + int idx = 0; int idxUv = 0; - for(int i = 0; i < numVertices; i++) { + for (int i = 0; i < numVertices; i++) { vertices[idx++] = 0; vertices[idx++] = 0; vertices[idx++] = 0; - if(hasNormals) { + if (hasNormals) { vertices[idx++] = 0; vertices[idx++] = 0; vertices[idx++] = 0; } - for(int j = 0; j < uvSets.size; j++) { + for (int j = 0; j < uvSets.size; j++) { vertices[idx++] = uvSets.get(j).get(idxUv); - vertices[idx++] = uvSets.get(j).get(idxUv+1); + vertices[idx++] = uvSets.get(j).get(idxUv + 1); } - idxUv+=2; + idxUv += 2; } return vertices; } - + private static VertexAttribute[] createVertexAttributes (boolean hasNormals, int uvs) { - VertexAttribute[] attributes = new VertexAttribute[1 + (hasNormals?1:0) + uvs]; + VertexAttribute[] attributes = new VertexAttribute[1 + (hasNormals ? 1 : 0) + uvs]; int idx = 0; attributes[idx++] = new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE); - if(hasNormals) attributes[idx++] = new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE); - for(int i = 0; i < uvs; i++) { + if (hasNormals) attributes[idx++] = new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE); + for (int i = 0; i < uvs; i++) { attributes[idx++] = new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + i); - } + } return attributes; } - private static FloatArray readUVSet(BufferedReader in, int numVertices, boolean flipV) throws IOException { + private static FloatArray readUVSet (BufferedReader in, int numVertices, boolean flipV) throws IOException { FloatArray uvSet = new FloatArray(numVertices * 2); FloatArray uv = new FloatArray(2); - for(int i = 0; i < numVertices; i++) { + for (int i = 0; i < numVertices; i++) { readFloatArray(in, uv); uvSet.add(uv.items[0]); - uvSet.add(flipV?1-uv.items[1]:uv.items[1]); + uvSet.add(flipV ? 1 - uv.items[1] : uv.items[1]); } return uvSet; } - - private static IntArray readFaces(BufferedReader in) throws NumberFormatException, IOException { + + private static IntArray readFaces (BufferedReader in) throws NumberFormatException, IOException { int numFaces = readInt(in); IntArray faceIndices = new IntArray(); IntArray triangles = new IntArray(); IntArray indices = new IntArray(); - - for(int face = 0; face < numFaces; face++) { + + for (int face = 0; face < numFaces; face++) { readIntArray(in, faceIndices); int numIndices = faceIndices.get(0); triangles.clear(); - int baseIndex = faceIndices.get(1); - for(int i = 2; i < numIndices; i++) { + int baseIndex = faceIndices.get(1); + for (int i = 2; i < numIndices; i++) { triangles.add(baseIndex); triangles.add(faceIndices.items[i]); - triangles.add(faceIndices.items[i+1]); + triangles.add(faceIndices.items[i + 1]); } indices.addAll(triangles); } - + indices.shrink(); return indices; } - - private static short[] convertToShortArray(IntArray array) { + + private static short[] convertToShortArray (IntArray array) { short[] shortArray = new short[array.size]; - for(int i = 0; i < array.size; i++) { + for (int i = 0; i < array.size; i++) { shortArray[i] = (short)array.items[i]; } return shortArray; } - - private static float readFloat(BufferedReader in) throws NumberFormatException, IOException { + + private static float readFloat (BufferedReader in) throws NumberFormatException, IOException { lineNum++; return Float.parseFloat(read(in).trim()); } - - private static int readInt(BufferedReader in) throws NumberFormatException, IOException { + + private static int readInt (BufferedReader in) throws NumberFormatException, IOException { lineNum++; return (int)(Math.floor(Float.parseFloat(read(in).trim()))); } - - private static String readString(BufferedReader in) throws IOException { + + private static String readString (BufferedReader in) throws IOException { lineNum++; - return read(in); - } - - private static void readFloatArray(BufferedReader in, FloatArray array) throws IOException { + return read(in); + } + + private static void readFloatArray (BufferedReader in, FloatArray array) throws IOException { lineNum++; - String[] tokens = read(in).split(","); + String[] tokens = read(in).split(","); int len = tokens.length; array.clear(); - for(int i = 0; i < len; i++) { - array.add(Float.parseFloat(tokens[i].trim())); - } + for (int i = 0; i < len; i++) { + array.add(Float.parseFloat(tokens[i].trim())); + } } - + private static int readFloatArray (BufferedReader in, float[] array, int idx) throws IOException { lineNum++; - String[] tokens = read(in).split(","); - int len = tokens.length; - for(int i = 0; i < len; i++) { - array[idx++] = Float.parseFloat(tokens[i].trim()); + String[] tokens = read(in).split(","); + int len = tokens.length; + for (int i = 0; i < len; i++) { + array[idx++] = Float.parseFloat(tokens[i].trim()); } return idx; } - - private static void readIntArray(BufferedReader in, IntArray array) throws IOException { - String[] tokens = read(in).split(","); + + private static void readIntArray (BufferedReader in, IntArray array) throws IOException { + String[] tokens = read(in).split(","); int len = tokens.length; array.clear(); - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { array.add(Integer.parseInt(tokens[i].trim())); } } - - private static String read(BufferedReader in) throws IOException { + + private static String read (BufferedReader in) throws IOException { line = in.readLine(); return line; - } - + } + public static class G3dtStillModelLoader implements StillModelLoader { - @Override public StillModel load (FileHandle handle, ModelLoaderHints hints) { + @Override + public StillModel load (FileHandle handle, ModelLoaderHints hints) { return G3dtLoader.loadStillModel(handle, hints.flipV); - } + } } - + public static class G3dtKeyframedModelLoader implements KeyframedModelLoader { - @Override public KeyframedModel load (FileHandle handle, ModelLoaderHints hints) { + @Override + public KeyframedModel load (FileHandle handle, ModelLoaderHints hints) { return G3dtLoader.loadKeyframedModel(handle, hints.flipV); - } + } } -} \ No newline at end of file +} diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkReader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkReader.java index b5528a02aa1..554dcc8d1b2 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkReader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkReader.java @@ -1,13 +1,5 @@ -package com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.G3D_ROOT; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.INDEX_LIST; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.STILL_MODEL; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.STILL_SUBMESH; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERSION_INFO; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERTEX_ATTRIBUTE; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERTEX_ATTRIBUTES; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERTEX_LIST; +package com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -19,200 +11,226 @@ import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; -public class ChunkReader { +import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.*; + +public class ChunkReader { public static class Chunk { int id; Chunk parent; - Array children = new Array(); - ByteArrayInputStream payload; + Array children = new Array(); + ByteArrayInputStream payload; byte[] payloadBytes; int offset = 0; CountingDataInputStream in; - - protected Chunk(int id, Chunk parent, byte[] bytes, int offset, int size) throws IOException { + + protected Chunk (int id, Chunk parent, byte[] bytes, int offset, int size) throws IOException { this.id = id; - this.parent = parent; + this.parent = parent; this.payload = new ByteArrayInputStream(bytes, offset, size); this.payloadBytes = bytes; this.offset = offset; - this.in = new CountingDataInputStream(payload); + this.in = new CountingDataInputStream(payload); } - - public int getId() { + + public int getId () { return id; } - - public Chunk getParent() { + + public Chunk getParent () { return parent; } - - public Array getChildren() { + + public Array getChildren () { return children; } - - public int readByte() { - try { return in.readByte(); } catch(IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } + + public int readByte () { + try { + return in.readByte(); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); + } } - - public short readShort() { - try { return in.readShort(); } catch(IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } + + public short readShort () { + try { + return in.readShort(); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); + } } - - public int readInt() { - try { return in.readInt(); } catch(IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } + + public int readInt () { + try { + return in.readInt(); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); + } } - - public long readLong() { - try { return in.readLong(); } catch(IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } + + public long readLong () { + try { + return in.readLong(); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); + } } - - public float readFloat() { - try { return in.readFloat(); } catch(IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } + + public float readFloat () { + try { + return in.readFloat(); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); + } } - - public double readDouble() { - try { return in.readDouble(); } catch(IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } + + public double readDouble () { + try { + return in.readDouble(); + } catch (IOException e) { + throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); + } } - - public byte[] readBytes() { - try { + + public byte[] readBytes () { + try { int len = in.readInt(); byte[] v = new byte[len]; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { v[i] = in.readByte(); } return v; - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } } - - public short[] readShorts() { - try { + + public short[] readShorts () { + try { int len = in.readInt(); short[] v = new short[len]; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { v[i] = in.readShort(); } return v; - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } } - - public int[] readInts() { - try { + + public int[] readInts () { + try { int len = in.readInt(); int[] v = new int[len]; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { v[i] = in.readInt(); } return v; - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } } - - public long[] readLongs() { - try { + + public long[] readLongs () { + try { int len = in.readInt(); long[] v = new long[len]; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { v[i] = in.readLong(); } return v; - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } } - - public float[] readFloats() { - try { + + public float[] readFloats () { + try { int len = in.readInt(); float[] v = new float[len]; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { v[i] = in.readFloat(); } return v; - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } } - - public double[] readDoubles() { - try { + + public double[] readDoubles () { + try { int len = in.readInt(); double[] v = new double[len]; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { v[i] = in.readDouble(); } return v; - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } } - - public String readString() { + + public String readString () { try { int len = in.readInt(); byte[] bytes = new byte[len]; in.readFully(bytes); return new String(bytes, "UTF-8"); - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't read payload, " + e.getMessage(), e); } } public Chunk getChild (int id) { - for(int i = 0; i < children.size; i++) { + for (int i = 0; i < children.size; i++) { Chunk child = children.get(i); - if(child.getId() == id) return child; + if (child.getId() == id) return child; } return null; } - public Chunk[] getChildren(int id) { + public Chunk[] getChildren (int id) { Array meshes = new Array(true, 16, Chunk.class); - for(int i = 0; i < children.size; i++) { + for (int i = 0; i < children.size; i++) { Chunk child = children.get(i); - if(child.getId() == id) meshes.add(child); + if (child.getId() == id) meshes.add(child); } meshes.shrink(); return meshes.items; } - } - - public static Chunk readChunks(InputStream in) throws IOException { + } + + public static Chunk readChunks (InputStream in) throws IOException { return loadChunks(in, 0); } - - private static Chunk loadChunks(InputStream in, int fileSize) throws IOException { + + private static Chunk loadChunks (InputStream in, int fileSize) throws IOException { byte[] bytes = readStream(in, fileSize); - CountingDataInputStream din = new CountingDataInputStream(new ByteArrayInputStream(bytes)); + CountingDataInputStream din = new CountingDataInputStream(new ByteArrayInputStream(bytes)); return loadChunk(din, bytes); - } - - private static Chunk loadChunk(CountingDataInputStream din, byte[] bytes) throws IOException { + } + + private static Chunk loadChunk (CountingDataInputStream din, byte[] bytes) throws IOException { int id = din.readInt(); int payloadSize = din.readInt(); - int numChildren = din.readInt(); + int numChildren = din.readInt(); int offset = din.getReadBytes(); - din.skipBytes(payloadSize); + din.skipBytes(payloadSize); Chunk chunk = new Chunk(id, null, bytes, offset, payloadSize); - for(int i = 0; i < numChildren; i++) { + for (int i = 0; i < numChildren; i++) { Chunk child = loadChunk(din, bytes); child.parent = chunk; chunk.children.add(child); } return chunk; } - - private static byte[] readStream(InputStream in, int size) throws IOException { - if(size == 0) { + + private static byte[] readStream (InputStream in, int size) throws IOException { + if (size == 0) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - byte[] buffer = new byte[10*1024]; + byte[] buffer = new byte[10 * 1024]; int readBytes = 0; - while((readBytes = in.read(buffer)) != -1) { + while ((readBytes = in.read(buffer)) != -1) { bytes.write(buffer, 0, readBytes); } return bytes.toByteArray(); @@ -223,78 +241,77 @@ private static byte[] readStream(InputStream in, int size) throws IOException { return bytes; } } - - /** - * Prints a textual representation of the given Chunk hierarchy - * @param chunk the hierarchy root {@link Chunk} - */ - public static void printChunks(Chunk chunk) { + + /** Prints a textual representation of the given Chunk hierarchy + * @param chunk the hierarchy root {@link Chunk} */ + public static void printChunks (Chunk chunk) { printChunks(chunk, 0); } - - private static void printChunks(Chunk chunk, int level) { + + private static void printChunks (Chunk chunk, int level) { String id = null; String payload = null; - switch(chunk.getId()) { - case G3D_ROOT: - id = "G3D_ROOT"; - break; - case VERSION_INFO: - id = "VERSION_INFO"; - int major = chunk.readByte(); - int minor = chunk.readByte(); - payload = rep(" ", level + 1) + "major: " + major + ", minor: " + minor; - break; - case STILL_MODEL: - id = "STILL_MODEL"; - int subMeshes = chunk.readInt(); - payload = rep(" ", level + 1) + "#submeshes: " + subMeshes; - break; - case STILL_SUBMESH: - id = "STILL_SUBMESH"; - payload = rep(" ", level + 1) + "name: " + chunk.readString() + ", primitive type: " + chunk.readInt(); - break; - case VERTEX_ATTRIBUTE: - id = "VERTEX_ATTRIBUTE"; - int usage = chunk.readInt(); - int components = chunk.readInt(); - String name = chunk.readString(); - payload = rep(" ", level + 1) + "usage: " + usage + ", components: " + components + ", name: " + name; - break; - case VERTEX_ATTRIBUTES: - id = "VERTEX_ATTRIBUTES"; - int numAttributes = chunk.readInt(); - payload = rep(" ", level + 1) + "#attributes: " + numAttributes; - break; - case VERTEX_LIST: - id = "VERTEX_LIST"; - int numVertices = chunk.readInt(); - float[] vertices = chunk.readFloats(); - payload = rep(" ", level + 1) + "#vertices: " + numVertices + ": " + Arrays.toString(vertices).substring(0, 400); - break; - case INDEX_LIST: - id = "INDEX_LIST"; - int numIndices = chunk.readInt(); - short[] indices = chunk.readShorts(); - payload = rep(" ", level + 1) + "#indices: " + numIndices + ": " + Arrays.toString(indices).substring(0, 400); - break; - default: - id ="unknown [" + id + "]"; - payload = rep(" ", level + 1) + "unknown"; - break; + switch (chunk.getId()) { + case G3D_ROOT: + id = "G3D_ROOT"; + break; + case VERSION_INFO: + id = "VERSION_INFO"; + int major = chunk.readByte(); + int minor = chunk.readByte(); + payload = rep(" ", level + 1) + "major: " + major + ", minor: " + minor; + break; + case STILL_MODEL: + id = "STILL_MODEL"; + int subMeshes = chunk.readInt(); + payload = rep(" ", level + 1) + "#submeshes: " + subMeshes; + break; + case STILL_SUBMESH: + id = "STILL_SUBMESH"; + payload = rep(" ", level + 1) + "name: " + chunk.readString() + ", primitive type: " + chunk.readInt(); + break; + case VERTEX_ATTRIBUTE: + id = "VERTEX_ATTRIBUTE"; + int usage = chunk.readInt(); + int components = chunk.readInt(); + String name = chunk.readString(); + payload = rep(" ", level + 1) + "usage: " + usage + ", components: " + components + ", name: " + name; + break; + case VERTEX_ATTRIBUTES: + id = "VERTEX_ATTRIBUTES"; + int numAttributes = chunk.readInt(); + payload = rep(" ", level + 1) + "#attributes: " + numAttributes; + break; + case VERTEX_LIST: + id = "VERTEX_LIST"; + int numVertices = chunk.readInt(); + float[] vertices = chunk.readFloats(); + payload = rep(" ", level + 1) + "#vertices: " + numVertices + ": " + Arrays.toString(vertices).substring(0, 400); + break; + case INDEX_LIST: + id = "INDEX_LIST"; + int numIndices = chunk.readInt(); + short[] indices = chunk.readShorts(); + payload = rep(" ", level + 1) + "#indices: " + numIndices + ": " + Arrays.toString(indices).substring(0, 400); + break; + default: + id = "unknown [" + id + "]"; + payload = rep(" ", level + 1) + "unknown"; + break; } - + System.out.println(rep(" ", level) + id + " {"); - if(payload != null) System.out.println(payload); - for(Chunk child: chunk.getChildren()) { - printChunks(child, level+1); + if (payload != null) System.out.println(payload); + for (Chunk child : chunk.getChildren()) { + printChunks(child, level + 1); } System.out.println(rep(" ", level) + "}"); } - - private static String rep(String c, int n) { + + private static String rep (String c, int n) { StringBuffer buf = new StringBuffer(); - for(int i = 0; i < n; i++) buf.append(c); + for (int i = 0; i < n; i++) + buf.append(c); return buf.toString(); - } + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkWriter.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkWriter.java index b7c10923380..e62eb21bb8b 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkWriter.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/ChunkWriter.java @@ -1,6 +1,5 @@ -package com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.G3D_ROOT; +package com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -9,154 +8,180 @@ import com.badlogic.gdx.utils.Array; +import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.*; + public class ChunkWriter { - + class Chunk { final int id; final Chunk parent; final Array children = new Array(); final ByteArrayOutputStream payload = new ByteArrayOutputStream(); - final DataOutputStream out = new DataOutputStream(payload); - - public Chunk(int id) { + final DataOutputStream out = new DataOutputStream(payload); + + public Chunk (int id) { this.id = id; this.parent = null; } - - public Chunk(int id, Chunk parent) { + + public Chunk (int id, Chunk parent) { this.id = id; this.parent = parent; - } + } } - + final Chunk root; Chunk currChunk; - - public ChunkWriter() { + + public ChunkWriter () { root = new Chunk(G3D_ROOT); currChunk = root; } - - public void newChunk(int id) { + + public void newChunk (int id) { Chunk chunk = new Chunk(id, currChunk); currChunk.children.add(chunk); currChunk = chunk; } - - public void endChunk() { + + public void endChunk () { currChunk = currChunk.parent; } - - public void writeByte(int v) { - try { currChunk.out.writeByte(v); } catch (IOException e) { }; + + public void writeByte (int v) { + try { + currChunk.out.writeByte(v); + } catch (IOException e) { + } + ; } - - public void writeShort(short v) { - try { currChunk.out.writeShort(v); } catch (IOException e) { }; + + public void writeShort (short v) { + try { + currChunk.out.writeShort(v); + } catch (IOException e) { + } + ; } - - public void writeInt(int v) { - try { currChunk.out.writeInt(v); } catch (IOException e) { }; - } - - public void writeLong(long v) { - try { currChunk.out.writeLong(v); } catch (IOException e) { }; + + public void writeInt (int v) { + try { + currChunk.out.writeInt(v); + } catch (IOException e) { + } + ; + } + + public void writeLong (long v) { + try { + currChunk.out.writeLong(v); + } catch (IOException e) { + } + ; } - - public void writeFloat(float v) { - try { currChunk.out.writeFloat(v); } catch (IOException e) { }; + + public void writeFloat (float v) { + try { + currChunk.out.writeFloat(v); + } catch (IOException e) { + } + ; } - - public void writeDouble(double v) { - try { currChunk.out.writeDouble(v); } catch (IOException e) { }; + + public void writeDouble (double v) { + try { + currChunk.out.writeDouble(v); + } catch (IOException e) { + } + ; } - - public void writeString(String v) { + + public void writeString (String v) { try { byte[] bytes = v.getBytes("UTF-8"); currChunk.out.writeInt(bytes.length); currChunk.out.write(bytes); - } catch(IOException e) { + } catch (IOException e) { } } - - public void writeToStream(OutputStream out) throws IOException { + + public void writeToStream (OutputStream out) throws IOException { writeToStream(root, new DataOutputStream(out)); } - - private void writeToStream(Chunk chunk, DataOutputStream out) throws IOException { + + private void writeToStream (Chunk chunk, DataOutputStream out) throws IOException { // write id, payload size in bytes and number of children out.writeInt(chunk.id); out.writeInt(chunk.payload.size()); - out.writeInt(chunk.children.size); - + out.writeInt(chunk.children.size); + // write payload - out.write(chunk.payload.toByteArray()); - + out.write(chunk.payload.toByteArray()); + // recursively write children - for(int i = 0; i < chunk.children.size; i++) { + for (int i = 0; i < chunk.children.size; i++) { Chunk child = chunk.children.get(i); writeToStream(child, out); } } - + public void writeBytes (byte[] v) { try { currChunk.out.writeInt(v.length); - for(int i = 0; i < v.length; i++) { + for (int i = 0; i < v.length; i++) { currChunk.out.writeByte(v[i]); } - } catch(IOException e) { + } catch (IOException e) { } } public void writeShorts (short[] v) { try { currChunk.out.writeInt(v.length); - for(int i = 0; i < v.length; i++) { + for (int i = 0; i < v.length; i++) { currChunk.out.writeShort(v[i]); } - } catch(IOException e) { + } catch (IOException e) { } } - + public void writeInts (int[] v) { try { currChunk.out.writeInt(v.length); - for(int i = 0; i < v.length; i++) { + for (int i = 0; i < v.length; i++) { currChunk.out.writeInt(v[i]); } - } catch(IOException e) { + } catch (IOException e) { } - } - + } + public void writeLongs (long[] v) { try { currChunk.out.writeInt(v.length); - for(int i = 0; i < v.length; i++) { + for (int i = 0; i < v.length; i++) { currChunk.out.writeLong(v[i]); } - } catch(IOException e) { + } catch (IOException e) { } - } - + } + public void writeFloats (float[] v) { try { currChunk.out.writeInt(v.length); - for(int i = 0; i < v.length; i++) { + for (int i = 0; i < v.length; i++) { currChunk.out.writeFloat(v[i]); } - } catch(IOException e) { + } catch (IOException e) { } - } - + } + public void writeDoubles (double[] v) { try { currChunk.out.writeInt(v.length); - for(int i = 0; i < v.length; i++) { + for (int i = 0; i < v.length; i++) { currChunk.out.writeDouble(v[i]); } - } catch(IOException e) { + } catch (IOException e) { } - } + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/CountingDataInputStream.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/CountingDataInputStream.java index da50e4d02c5..7775b1b7ef2 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/CountingDataInputStream.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/CountingDataInputStream.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks; import java.io.DataInput; @@ -8,86 +9,101 @@ public class CountingDataInputStream implements DataInput { int readBytes = 0; DataInputStream in; - + public CountingDataInputStream (InputStream in) { this.in = new DataInputStream(in); - } - - public int getReadBytes() { + } + + public int getReadBytes () { return readBytes; } - @Override public void readFully (byte[] b) throws IOException { + @Override + public void readFully (byte[] b) throws IOException { readBytes += b.length; in.readFully(b); } - @Override public void readFully (byte[] b, int off, int len) throws IOException { + @Override + public void readFully (byte[] b, int off, int len) throws IOException { readBytes += len; in.readFully(b, off, len); } - @Override public int skipBytes (int n) throws IOException { + @Override + public int skipBytes (int n) throws IOException { int skipped = in.skipBytes(n); readBytes += skipped; return skipped; } - @Override public boolean readBoolean () throws IOException { + @Override + public boolean readBoolean () throws IOException { readBytes += 1; return in.readBoolean(); } - @Override public byte readByte () throws IOException { + @Override + public byte readByte () throws IOException { readBytes += 1; return in.readByte(); } - @Override public int readUnsignedByte () throws IOException { + @Override + public int readUnsignedByte () throws IOException { readBytes += 1; return in.readUnsignedByte(); } - @Override public short readShort () throws IOException { + @Override + public short readShort () throws IOException { readBytes += 2; return in.readShort(); } - @Override public int readUnsignedShort () throws IOException { + @Override + public int readUnsignedShort () throws IOException { readBytes += 2; return in.readUnsignedShort(); } - @Override public char readChar () throws IOException { + @Override + public char readChar () throws IOException { readBytes += 2; return in.readChar(); } - @Override public int readInt () throws IOException { + @Override + public int readInt () throws IOException { readBytes += 4; return in.readInt(); } - @Override public long readLong () throws IOException { + @Override + public long readLong () throws IOException { readBytes += 8; return in.readLong(); } - @Override public float readFloat () throws IOException { + @Override + public float readFloat () throws IOException { readBytes += 4; return in.readFloat(); } - @Override public double readDouble () throws IOException { + @Override + public double readDouble () throws IOException { readBytes += 8; return in.readDouble(); } - @Override public String readLine () throws IOException { + @Override + public String readLine () throws IOException { throw new UnsupportedOperationException("Not implemented"); } - @Override public String readUTF () throws IOException { + @Override + public String readUTF () throws IOException { throw new UnsupportedOperationException("Not implemented"); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/G3dExporter.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/G3dExporter.java index 93280379438..6e1908a9369 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/G3dExporter.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/g3d/chunks/G3dExporter.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks; import java.io.IOException; @@ -15,30 +16,30 @@ import com.badlogic.gdx.utils.GdxRuntimeException; public class G3dExporter { - public static void export(StillModel model, FileHandle file) { + public static void export (StillModel model, FileHandle file) { ChunkWriter writer = new ChunkWriter(); - + // write version info writer.newChunk(G3dConstants.VERSION_INFO); writer.writeByte(G3dConstants.MAJOR_VERSION); writer.writeByte(G3dConstants.MINOR_VERSION); writer.endChunk(); - + // write still model writer.newChunk(G3dConstants.STILL_MODEL); writer.writeInt(model.subMeshes.length); - + // write sub mesh - for(StillSubMesh mesh: model.subMeshes) { + for (StillSubMesh mesh : model.subMeshes) { // start sub mesh writer.newChunk(G3dConstants.STILL_SUBMESH); - writer.writeString(mesh.name == null?"": mesh.name); + writer.writeString(mesh.name == null ? "" : mesh.name); writer.writeInt(mesh.primitiveType); - + // write vertex attributes writer.newChunk(G3dConstants.VERTEX_ATTRIBUTES); writer.writeInt(mesh.mesh.getVertexAttributes().size()); - for(int i = 0; i < mesh.mesh.getVertexAttributes().size(); i++) { + for (int i = 0; i < mesh.mesh.getVertexAttributes().size(); i++) { VertexAttribute attribute = mesh.mesh.getVertexAttributes().get(i); writer.newChunk(G3dConstants.VERTEX_ATTRIBUTE); writer.writeInt(attribute.usage); @@ -47,69 +48,72 @@ public static void export(StillModel model, FileHandle file) { writer.endChunk(); } writer.endChunk(); - + // write vertices writer.newChunk(G3dConstants.VERTEX_LIST); int numFloats = mesh.mesh.getNumVertices() * mesh.mesh.getVertexSize() / 4; - float[] vertices = new float[numFloats]; - mesh.mesh.getVertices(vertices); + float[] vertices = new float[numFloats]; + mesh.mesh.getVertices(vertices); writer.writeInt(mesh.mesh.getNumVertices()); writer.writeFloats(vertices); writer.endChunk(); - + // write indices writer.newChunk(G3dConstants.INDEX_LIST); int numShorts = mesh.mesh.getNumIndices(); short[] indices = new short[numShorts]; - mesh.mesh.getIndices(indices); + mesh.mesh.getIndices(indices); writer.writeInt(numShorts); writer.writeShorts(indices); - writer.endChunk(); - + writer.endChunk(); + // end sub mesh writer.endChunk(); } - + // end still model writer.endChunk(); - + // write to file OutputStream out = null; try { out = file.write(false); writer.writeToStream(out); - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("An error occured while exporting the still model, " + e.getMessage(), e); } finally { - if(out != null) try { out.close(); } catch(IOException e) { } + if (out != null) try { + out.close(); + } catch (IOException e) { + } } - } - - public static void export(KeyframedModel model, FileHandle file) { + } + + public static void export (KeyframedModel model, FileHandle file) { ChunkWriter writer = new ChunkWriter(); - + // write version info writer.newChunk(G3dConstants.VERSION_INFO); writer.writeByte(G3dConstants.MAJOR_VERSION); writer.writeByte(G3dConstants.MINOR_VERSION); writer.endChunk(); - + // write keyframed model writer.newChunk(G3dConstants.KEYFRAMED_MODEL); writer.writeInt(model.subMeshes.length); - - for(KeyframedSubMesh mesh: model.subMeshes) { + + for (KeyframedSubMesh mesh : model.subMeshes) { // writes keyframed submesh writer.newChunk(G3dConstants.KEYFRAMED_SUBMESH); - writer.writeString(mesh.name == null? "": mesh.name); + writer.writeString(mesh.name == null ? "" : mesh.name); writer.writeInt(mesh.primitiveType); writer.writeInt(mesh.animatedComponents); writer.writeInt(mesh.animations.size); - + // write vertex attributes - writer.newChunk(G3dConstants.VERTEX_ATTRIBUTES); + writer.newChunk(G3dConstants.VERTEX_ATTRIBUTES); writer.writeInt(mesh.mesh.getVertexAttributes().size()); - for(int i = 0; i < mesh.mesh.getVertexAttributes().size(); i++) { + for (int i = 0; i < mesh.mesh.getVertexAttributes().size(); i++) { VertexAttribute attribute = mesh.mesh.getVertexAttributes().get(i); writer.newChunk(G3dConstants.VERTEX_ATTRIBUTE); writer.writeInt(attribute.usage); @@ -118,63 +122,66 @@ public static void export(KeyframedModel model, FileHandle file) { writer.endChunk(); } writer.endChunk(); - + // write static components, sort of like a bind pose mesh writer.newChunk(G3dConstants.VERTEX_LIST); int numFloats = mesh.mesh.getNumVertices() * mesh.mesh.getVertexSize() / 4; - float[] vertices = new float[numFloats]; + float[] vertices = new float[numFloats]; mesh.mesh.getVertices(vertices); writer.writeInt(mesh.mesh.getNumVertices()); writer.writeFloats(vertices); writer.endChunk(); - + // write indices writer.newChunk(G3dConstants.INDEX_LIST); int numShorts = mesh.mesh.getNumIndices(); short[] indices = new short[numShorts]; - mesh.mesh.getIndices(indices); + mesh.mesh.getIndices(indices); writer.writeInt(mesh.mesh.getNumIndices()); writer.writeShorts(indices); - writer.endChunk(); - - // write animations - for(String animationName: mesh.animations.keys()) { + writer.endChunk(); + + // write animations + for (String animationName : mesh.animations.keys()) { KeyframedAnimation animation = mesh.animations.get(animationName); - + // write keyframed animation writer.newChunk(G3dConstants.KEYFRAMED_ANIMATION); writer.writeString(animation.name); writer.writeFloat(animation.frameDuration); - + // write key frames writer.writeInt(animation.keyframes.length); - for(Keyframe keyframe: animation.keyframes) { + for (Keyframe keyframe : animation.keyframes) { // write keyframed writer.newChunk(G3dConstants.KEYFRAMED_FRAME); - writer.writeFloat(keyframe.timeStamp); - writer.writeFloats(keyframe.vertices); + writer.writeFloat(keyframe.timeStamp); + writer.writeFloats(keyframe.vertices); writer.endChunk(); } // end keyframed animation writer.endChunk(); } - + // end keyframed submesh writer.endChunk(); } - + // end keyframed model writer.endChunk(); - + // write to file OutputStream out = null; try { out = file.write(false); writer.writeToStream(out); - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("An error occured while exporting the still model, " + e.getMessage(), e); } finally { - if(out != null) try { out.close(); } catch(IOException e) { } + if (out != null) try { + out.close(); + } catch (IOException e) { + } } } -} \ No newline at end of file +} diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Frame.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Frame.java index 4c806652c93..13efd8ebe1c 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Frame.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Frame.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.md2; public class MD2Frame { diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Header.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Header.java index 44789d73a85..fae1553f413 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Header.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Header.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.md2; public class MD2Header { diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Loader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Loader.java index 66096761f39..910fdfd8b30 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Loader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Loader.java @@ -22,15 +22,15 @@ import com.badlogic.gdx.utils.LittleEndianInputStream; import com.badlogic.gdx.utils.ObjectMap; -public class MD2Loader implements KeyframedModelLoader { - public KeyframedModel load(FileHandle file, ModelLoaderHints hints) { +public class MD2Loader implements KeyframedModelLoader { + public KeyframedModel load (FileHandle file, ModelLoaderHints hints) { float frameDuration = 0.2f; - if(hints instanceof MD2LoaderHints) { + if (hints instanceof MD2LoaderHints) { frameDuration = ((MD2LoaderHints)hints).frameDuration; } return load(file, frameDuration); } - + public KeyframedModel load (FileHandle fileHandle, float frameDuration) { InputStream in = fileHandle.read(); try { @@ -60,7 +60,8 @@ public KeyframedModel load (InputStream in, float frameDuration) { } } - private KeyframedModel buildModel (MD2Header header, MD2Triangle[] triangles, float[] texCoords, MD2Frame[] frames, float frameDuration) { + private KeyframedModel buildModel (MD2Header header, MD2Triangle[] triangles, float[] texCoords, MD2Frame[] frames, + float frameDuration) { ArrayList vertCombos = new ArrayList(); short[] indices = new short[triangles.length * 3]; int idx = 0; @@ -111,9 +112,9 @@ private KeyframedModel buildModel (MD2Header header, MD2Triangle[] triangles, fl } header.numVertices = vertCombos.size(); - + float[] blendedVertices = new float[header.numVertices * 5]; - MD2Frame frame = frames[0]; + MD2Frame frame = frames[0]; idx = 0; int idxV = 0; int idxT = 0; @@ -124,34 +125,33 @@ private KeyframedModel buildModel (MD2Header header, MD2Triangle[] triangles, fl blendedVertices[idx++] = uvs[idxT++]; blendedVertices[idx++] = uvs[idxT++]; } - + KeyframedAnimation animation = new KeyframedAnimation("all", frameDuration, new Keyframe[frames.length]); float timeStamp = 0; for (int frameNum = 0; frameNum < frames.length; frameNum++) { frame = frames[frameNum]; float[] vertices = new float[header.numVertices * 3]; - idx = 0; + idx = 0; idxV = 0; for (int i = 0; i < header.numVertices; i++) { vertices[idx++] = frame.vertices[idxV++]; vertices[idx++] = frame.vertices[idxV++]; - vertices[idx++] = frame.vertices[idxV++]; + vertices[idx++] = frame.vertices[idxV++]; } - Keyframe keyFrame = new Keyframe(frameNum * frameDuration, vertices); + Keyframe keyFrame = new Keyframe(frameNum * frameDuration, vertices); animation.keyframes[frameNum] = keyFrame; } - - Mesh mesh = new Mesh(false, header.numVertices, indices.length, - new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), - new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); + Mesh mesh = new Mesh(false, header.numVertices, indices.length, new VertexAttribute(Usage.Position, 3, + ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + + "0")); mesh.setIndices(indices); ObjectMap animations = new ObjectMap(); animations.put("all", animation); - - KeyframedSubMesh subMesh = new KeyframedSubMesh("md2-mesh", mesh, blendedVertices, animations, 3, GL10.GL_TRIANGLES); - KeyframedModel model = new KeyframedModel(new KeyframedSubMesh[] {subMesh}); + + KeyframedSubMesh subMesh = new KeyframedSubMesh("md2-mesh", mesh, blendedVertices, animations, 3, GL10.GL_TRIANGLES); + KeyframedModel model = new KeyframedModel(new KeyframedSubMesh[] {subMesh}); model.setAnimation("all", 0, false); return model; } @@ -319,7 +319,8 @@ public VertexIndices (short vIdx, short tIdx, short nIdx) { this.nIdx = nIdx; } - @Override public int hashCode () { + @Override + public int hashCode () { final int prime = 31; int result = 1; result = prime * result + tIdx; @@ -327,7 +328,8 @@ public VertexIndices (short vIdx, short tIdx, short nIdx) { return result; } - @Override public boolean equals (Object obj) { + @Override + public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @@ -341,11 +343,11 @@ public VertexIndices (short vIdx, short tIdx, short nIdx) { public short tIdx; public short nIdx; } - + public static class MD2LoaderHints extends ModelLoaderHints { public final float frameDuration; - - public MD2LoaderHints(float frameDuration) { + + public MD2LoaderHints (float frameDuration) { super(false); this.frameDuration = frameDuration; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Triangle.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Triangle.java index a9e69ac0f2e..e5162461595 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Triangle.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/md2/MD2Triangle.java @@ -1,7 +1,7 @@ + package com.badlogic.gdx.graphics.g3d.loaders.md2; -public class MD2Triangle -{ +public class MD2Triangle { public short[] vertices = new short[3]; public short[] texCoords = new short[3]; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java index 31528e49792..ac147544b2b 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/OgreXmlLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.loaders.ogre; import java.io.InputStream; @@ -44,7 +45,7 @@ import com.badlogic.gdx.utils.IntArray; public class OgreXmlLoader { - public SkeletonSubMesh[] loadMeshes(FileHandle file) { + public SkeletonSubMesh[] loadMeshes (FileHandle file) { InputStream in = null; try { in = file.read(); @@ -52,170 +53,205 @@ public SkeletonSubMesh[] loadMeshes(FileHandle file) { } catch (Throwable t) { throw new GdxRuntimeException("Couldn't load file '" + file.name() + "'", t); } finally { - if(in != null) try { in.close(); } catch (Exception e) { } + if (in != null) try { + in.close(); + } catch (Exception e) { + } } } - - public SkeletonSubMesh[] loadMesh(InputStream in) { - try { - Mesh ogreMesh = loadOgreMesh(in); - SkeletonSubMesh[] meshes = generateSubMeshes(ogreMesh); + + public SkeletonSubMesh[] loadMesh (InputStream in) { + try { + Mesh ogreMesh = loadOgreMesh(in); + SkeletonSubMesh[] meshes = generateSubMeshes(ogreMesh); return meshes; - } catch(Throwable t) { + } catch (Throwable t) { throw new GdxRuntimeException("Couldn't load meshes", t); } } - - public SkeletonModel load(FileHandle mesh, FileHandle skeleton) { + + public SkeletonModel load (FileHandle mesh, FileHandle skeleton) { SkeletonSubMesh[] meshes = loadMeshes(mesh); - Skeleton skel = loadSkeleton(skeleton); + Skeleton skel = loadSkeleton(skeleton); return new SkeletonModel(skel, meshes); } - - private SkeletonSubMesh[] generateSubMeshes(Mesh ogreMesh) { + + private SkeletonSubMesh[] generateSubMeshes (Mesh ogreMesh) { List ogreSubmeshes = ogreMesh.getSubmeshes().getSubmesh(); SkeletonSubMesh[] submeshes = new SkeletonSubMesh[ogreSubmeshes.size()]; - - for(int i = 0; i < ogreSubmeshes.size(); i++) { + + for (int i = 0; i < ogreSubmeshes.size(); i++) { Submesh ogreSubmesh = ogreSubmeshes.get(i); boolean usesTriangleList = false; - - if(ogreSubmesh.useSharedVertices) throw new GdxRuntimeException("submesh '" + i + "' uses shared vertices"); - if(ogreSubmesh.use32Bitindexes) throw new GdxRuntimeException("submesh '" + i + "' uses 32-bit indices"); - if(ogreSubmesh.getOperationtype().equals("triangle_list")) { - usesTriangleList = true; - } - - short[] indices = new short[ogreSubmesh.getFaces().count * (usesTriangleList?3:1)]; - for(int j = 0, idx = 0; j < ogreSubmesh.getFaces().count; j++) { + + if (ogreSubmesh.useSharedVertices) throw new GdxRuntimeException("submesh '" + i + "' uses shared vertices"); + if (ogreSubmesh.use32Bitindexes) throw new GdxRuntimeException("submesh '" + i + "' uses 32-bit indices"); + if (ogreSubmesh.getOperationtype().equals("triangle_list")) { + usesTriangleList = true; + } + + short[] indices = new short[ogreSubmesh.getFaces().count * (usesTriangleList ? 3 : 1)]; + for (int j = 0, idx = 0; j < ogreSubmesh.getFaces().count; j++) { Face face = ogreSubmesh.getFaces().getFace().get(j); indices[idx++] = (short)face.v1; - if(usesTriangleList || j == 0) { + if (usesTriangleList || j == 0) { indices[idx++] = (short)face.v2; indices[idx++] = (short)face.v3; } } - + List attributes = new ArrayList(); IntArray offsets = new IntArray(); int offset = 0; - for(int j = 0; j < ogreSubmesh.getGeometry().getVertexbuffer().size(); j++) { + for (int j = 0; j < ogreSubmesh.getGeometry().getVertexbuffer().size(); j++) { Vertexbuffer buffer = ogreSubmesh.getGeometry().getVertexbuffer().get(j); - offsets.add(offset); - if(buffer.positions) { - attributes.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); - offset += 3; + offsets.add(offset); + if (buffer.positions) { + attributes.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); + offset += 3; } - if(buffer.normals) { - attributes.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); + if (buffer.normals) { + attributes.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); offset += 3; } - if(buffer.tangents) { - attributes.add(new VertexAttribute(Usage.Generic, buffer.tangentDimensions, ShaderProgram.TANGENT_ATTRIBUTE)); + if (buffer.tangents) { + attributes.add(new VertexAttribute(Usage.Generic, buffer.tangentDimensions, ShaderProgram.TANGENT_ATTRIBUTE)); offset += buffer.tangentDimensions; } - if(buffer.binormals) { - attributes.add(new VertexAttribute(Usage.Generic, 3, ShaderProgram.BINORMAL_ATTRIBUTE)); + if (buffer.binormals) { + attributes.add(new VertexAttribute(Usage.Generic, 3, ShaderProgram.BINORMAL_ATTRIBUTE)); offset += 3; } - if(buffer.coloursDiffuse) { - attributes.add(new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE)); + if (buffer.coloursDiffuse) { + attributes.add(new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE)); offset += 4; } - - for(int k = 0; k < buffer.textureCoords; k++) { + + for (int k = 0; k < buffer.textureCoords; k++) { try { int numTexCoords = 0; - switch(k) { - case 0: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions0()); break; - case 1: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions1()); break; - case 2: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions2()); break; - case 3: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions3()); break; - case 4: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions4()); break; - case 5: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions5()); break; - case 6: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions6()); break; - case 7: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions7()); break; + switch (k) { + case 0: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions0()); + break; + case 1: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions1()); + break; + case 2: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions2()); + break; + case 3: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions3()); + break; + case 4: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions4()); + break; + case 5: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions5()); + break; + case 6: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions6()); + break; + case 7: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions7()); + break; } - attributes.add(new VertexAttribute(Usage.TextureCoordinates, numTexCoords, ShaderProgram.TEXCOORD_ATTRIBUTE + k)); + attributes + .add(new VertexAttribute(Usage.TextureCoordinates, numTexCoords, ShaderProgram.TEXCOORD_ATTRIBUTE + k)); offset += numTexCoords; - } catch(NumberFormatException e) { + } catch (NumberFormatException e) { throw new GdxRuntimeException("Can't process texture coords with dimensions != 1, 2, 3, 4 (e.g. float1)"); } } } - + VertexAttributes attribs = new VertexAttributes(attributes.toArray(new VertexAttribute[0])); - int vertexSize = offset; + int vertexSize = offset; float[] vertices = new float[ogreSubmesh.getGeometry().vertexcount * offset]; - for(int j = 0; j < ogreSubmesh.getGeometry().getVertexbuffer().size(); j++) { + for (int j = 0; j < ogreSubmesh.getGeometry().getVertexbuffer().size(); j++) { Vertexbuffer buffer = ogreSubmesh.getGeometry().getVertexbuffer().get(j); offset = offsets.get(j); int idx = offset; - - for(int k = 0; k < buffer.getVertex().size(); k++) { + + for (int k = 0; k < buffer.getVertex().size(); k++) { Vertex v = buffer.getVertex().get(k); - if(v.getPosition()!=null) { + if (v.getPosition() != null) { vertices[idx++] = v.getPosition().x; vertices[idx++] = v.getPosition().y; vertices[idx++] = v.getPosition().z; } - - if(v.getNormal()!=null) { + + if (v.getNormal() != null) { vertices[idx++] = v.getNormal().x; vertices[idx++] = v.getNormal().y; vertices[idx++] = v.getNormal().z; } - - if(v.getTangent()!=null) { + + if (v.getTangent() != null) { vertices[idx++] = v.getTangent().x; vertices[idx++] = v.getTangent().y; vertices[idx++] = v.getTangent().z; - if(buffer.tangentDimensions == 4) - vertices[idx++] = v.getTangent().w; + if (buffer.tangentDimensions == 4) vertices[idx++] = v.getTangent().w; } - - if(v.getBinormal()!=null) { + + if (v.getBinormal() != null) { vertices[idx++] = v.getBinormal().x; vertices[idx++] = v.getBinormal().y; vertices[idx++] = v.getBinormal().z; } - - if(v.getColourDiffuse() != null) { + + if (v.getColourDiffuse() != null) { float color = getColor(v.getColourDiffuse()); vertices[idx++] = color; } - - if(v.getTexcoord() != null) { - for(int l = 0; l < v.getTexcoord().size(); l++) { + + if (v.getTexcoord() != null) { + for (int l = 0; l < v.getTexcoord().size(); l++) { Texcoord texCoord = v.getTexcoord().get(l); int numTexCoords = 0; - switch(l) { - case 0: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions0()); break; - case 1: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions1()); break; - case 2: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions2()); break; - case 3: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions3()); break; - case 4: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions4()); break; - case 5: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions5()); break; - case 6: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions6()); break; - case 7: numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions7()); break; + switch (l) { + case 0: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions0()); + break; + case 1: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions1()); + break; + case 2: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions2()); + break; + case 3: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions3()); + break; + case 4: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions4()); + break; + case 5: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions5()); + break; + case 6: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions6()); + break; + case 7: + numTexCoords = Integer.valueOf(buffer.getTextureCoordDimensions7()); + break; } - - if(numTexCoords == 1) { + + if (numTexCoords == 1) { vertices[idx++] = texCoord.u; } - - if(numTexCoords == 2) { + + if (numTexCoords == 2) { vertices[idx++] = texCoord.u; - vertices[idx++] = texCoord.v; + vertices[idx++] = texCoord.v; } - - if(numTexCoords == 3) { + + if (numTexCoords == 3) { vertices[idx++] = texCoord.u; vertices[idx++] = texCoord.v; vertices[idx++] = texCoord.w; } - - if(numTexCoords == 4) { + + if (numTexCoords == 4) { vertices[idx++] = texCoord.u; vertices[idx++] = texCoord.v; vertices[idx++] = texCoord.w; @@ -223,84 +259,86 @@ private SkeletonSubMesh[] generateSubMeshes(Mesh ogreMesh) { } } } - + offset += vertexSize; idx = offset; } } - - com.badlogic.gdx.graphics.Mesh mesh = new com.badlogic.gdx.graphics.Mesh(false, vertices.length / vertexSize, indices.length, attribs); + + com.badlogic.gdx.graphics.Mesh mesh = new com.badlogic.gdx.graphics.Mesh(false, vertices.length / vertexSize, + indices.length, attribs); mesh.setIndices(indices); mesh.setVertices(vertices); - + Array boneAssignments = new Array(); Array boneWeights = new Array(); - for(int j = 0; j < mesh.getNumVertices(); j++) { + for (int j = 0; j < mesh.getNumVertices(); j++) { boneAssignments.add(new IntArray(4)); boneWeights.add(new FloatArray(4)); } - + List vertexboneassignment = ogreSubmesh.getBoneassignments().getVertexboneassignment(); - for(int j = 0; j < vertexboneassignment.size(); j++) { + for (int j = 0; j < vertexboneassignment.size(); j++) { Vertexboneassignment assignment = vertexboneassignment.get(j); int boneIndex = assignment.boneindex; int vertexIndex = assignment.vertexindex; float weight = assignment.weight; - + boneAssignments.get(vertexIndex).add(boneIndex); boneWeights.get(vertexIndex).add(weight); - } - + } + SkeletonSubMesh subMesh = new SkeletonSubMesh(); // FIXME ? subMesh.materialName = ogreSubmesh.material; subMesh.mesh = mesh; subMesh.vertices = vertices; subMesh.skinnedVertices = new float[vertices.length]; - System.arraycopy(subMesh.vertices, 0, subMesh.skinnedVertices, 0, subMesh.vertices.length); + System.arraycopy(subMesh.vertices, 0, subMesh.skinnedVertices, 0, subMesh.vertices.length); subMesh.indices = indices; - + subMesh.boneAssignments = new int[boneAssignments.size][]; subMesh.boneWeights = new float[boneWeights.size][]; - for(int j = 0; j < boneAssignments.size; j++) { + for (int j = 0; j < boneAssignments.size; j++) { subMesh.boneAssignments[j] = new int[boneAssignments.get(j).size]; subMesh.boneWeights[j] = new float[boneWeights.get(j).size]; - for(int k = 0; k < boneAssignments.get(j).size; k++) { + for (int k = 0; k < boneAssignments.get(j).size; k++) { subMesh.boneAssignments[j][k] = boneAssignments.get(j).get(k); } - for(int k = 0; k < boneWeights.get(j).size; k++) { + for (int k = 0; k < boneWeights.get(j).size; k++) { subMesh.boneWeights[j][k] = boneWeights.get(j).get(k); } } - - if(ogreSubmesh.getOperationtype().equals("triangle_list")) subMesh.primitiveType = GL10.GL_TRIANGLES; - if(ogreSubmesh.getOperationtype().equals("triangle_fan")) subMesh.primitiveType = GL10.GL_TRIANGLE_FAN; - if(ogreSubmesh.getOperationtype().equals("triangle_strip")) subMesh.primitiveType = GL10.GL_TRIANGLE_STRIP; - + + if (ogreSubmesh.getOperationtype().equals("triangle_list")) subMesh.primitiveType = GL10.GL_TRIANGLES; + if (ogreSubmesh.getOperationtype().equals("triangle_fan")) subMesh.primitiveType = GL10.GL_TRIANGLE_FAN; + if (ogreSubmesh.getOperationtype().equals("triangle_strip")) subMesh.primitiveType = GL10.GL_TRIANGLE_STRIP; + submeshes[i] = subMesh; } return submeshes; } - + Color color = new Color(); + private float getColor (ColourDiffuse colourDiffuse) { String[] tokens = colourDiffuse.getValue().split(" "); - if(tokens.length == 3) + if (tokens.length == 3) color.set(Float.valueOf(tokens[0]), Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), 1); else color.set(Float.valueOf(tokens[0]), Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), Float.valueOf(tokens[3])); return color.toFloatBits(); } - private Mesh loadOgreMesh(InputStream in) throws JAXBException { + private Mesh loadOgreMesh (InputStream in) throws JAXBException { JAXBContext context = JAXBContext.newInstance(Mesh.class); Unmarshaller unmarshaller = context.createUnmarshaller(); long start = System.nanoTime(); Mesh mesh = (Mesh)unmarshaller.unmarshal(in); - System.out.println("took: " + (System.nanoTime() - start) / 1000000000.0f ); + System.out.println("took: " + (System.nanoTime() - start) / 1000000000.0f); return mesh; } - - public Skeleton loadSkeleton(FileHandle file) { + + public Skeleton loadSkeleton (FileHandle file) { InputStream in = null; try { in = file.read(); @@ -308,117 +346,125 @@ public Skeleton loadSkeleton(FileHandle file) { } catch (Throwable t) { throw new GdxRuntimeException("Couldn't load file '" + file.name() + "'", t); } finally { - if(in != null) try { in.close(); } catch (Exception e) { } + if (in != null) try { + in.close(); + } catch (Exception e) { + } } } - - public Skeleton loadSkeleton(InputStream in) { + + public Skeleton loadSkeleton (InputStream in) { try { - com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton ogreSkel = loadOgreSkeleton(in); + com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton ogreSkel = loadOgreSkeleton(in); return generateSkeleton(ogreSkel); - } catch(Throwable t) { + } catch (Throwable t) { throw new GdxRuntimeException("Couldn't load model", t); - } + } } private Skeleton generateSkeleton (com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton ogreSkel) { List bones = ogreSkel.getBones().getBone(); List joints = new ArrayList(); Map nameToJoint = new HashMap(); - for(int i = 0; i < bones.size(); i++) { + for (int i = 0; i < bones.size(); i++) { Bone bone = bones.get(i); SkeletonJoint joint = new SkeletonJoint(); - + joint.name = bone.name; joint.position.set(bone.position.x, bone.position.y, bone.position.z); - joint.rotation.setFromAxis(bone.rotation.axis.x, bone.rotation.axis.x, bone.rotation.axis.x, MathUtils.radiansToDegrees * bone.rotation.angle); - if(bone.scale != null) { - if(bone.scale.factor == 0) + joint.rotation.setFromAxis(bone.rotation.axis.x, bone.rotation.axis.x, bone.rotation.axis.x, MathUtils.radiansToDegrees + * bone.rotation.angle); + if (bone.scale != null) { + if (bone.scale.factor == 0) joint.scale.set(bone.scale.x, bone.scale.y, bone.scale.z); else joint.scale.set(bone.scale.factor, bone.scale.factor, bone.scale.factor); - } + } joints.add(joint); nameToJoint.put(joint.name, joint); } - + List hierarchy = ogreSkel.getBonehierarchy().getBoneparent(); - for(int i = 0; i < hierarchy.size(); i++) { + for (int i = 0; i < hierarchy.size(); i++) { Boneparent link = hierarchy.get(i); SkeletonJoint joint = nameToJoint.get(link.getBone()); SkeletonJoint parent = nameToJoint.get(link.getParent()); parent.children.add(joint); joint.parent = parent; } - + Skeleton skel = new Skeleton(); - for(int i = 0; i < joints.size(); i++) { + for (int i = 0; i < joints.size(); i++) { SkeletonJoint joint = joints.get(i); - if(joint.parent == null) - skel.hierarchy.add(joint); + if (joint.parent == null) skel.hierarchy.add(joint); } - + skel.buildFromHierarchy(); List animations = ogreSkel.getAnimations().getAnimation(); - for(int i = 0; i < animations.size(); i++) { - Animation animation = animations.get(i); + for (int i = 0; i < animations.size(); i++) { + Animation animation = animations.get(i); SkeletonKeyframe[][] perJointkeyFrames = new SkeletonKeyframe[skel.bindPoseJoints.size][]; - + List tracks = animation.getTracks().getTrack(); - if(tracks.size() != perJointkeyFrames.length) throw new IllegalArgumentException("Number of tracks does not equal number of joints"); + if (tracks.size() != perJointkeyFrames.length) + throw new IllegalArgumentException("Number of tracks does not equal number of joints"); Matrix4 rotation = new Matrix4(); Matrix4 transform = new Matrix4(); - - for(int j = 0; j < tracks.size(); j++) { + + for (int j = 0; j < tracks.size(); j++) { Track track = tracks.get(j); String jointName = track.getBone(); int jointIndex = skel.namesToIndices.get(jointName); - if(perJointkeyFrames[jointIndex] != null) throw new IllegalArgumentException("Track for bone " + jointName + " in animation " + animation.name + " already defined!"); + if (perJointkeyFrames[jointIndex] != null) + throw new IllegalArgumentException("Track for bone " + jointName + " in animation " + animation.name + + " already defined!"); SkeletonKeyframe[] jointKeyFrames = new SkeletonKeyframe[track.getKeyframes().getKeyframe().size()]; - perJointkeyFrames[jointIndex] = jointKeyFrames; - - for(int k = 0; k < track.getKeyframes().getKeyframe().size(); k++) { + perJointkeyFrames[jointIndex] = jointKeyFrames; + + for (int k = 0; k < track.getKeyframes().getKeyframe().size(); k++) { Keyframe keyFrame = track.getKeyframes().getKeyframe().get(k); SkeletonKeyframe jointKeyframe = new SkeletonKeyframe(); jointKeyframe.timeStamp = keyFrame.time; jointKeyframe.position.set(keyFrame.translate.x, keyFrame.translate.y, keyFrame.translate.z); - if(keyFrame.scale != null) { - if(keyFrame.scale.factor == 0) + if (keyFrame.scale != null) { + if (keyFrame.scale.factor == 0) jointKeyframe.scale.set(keyFrame.scale.x, keyFrame.scale.y, keyFrame.scale.z); else jointKeyframe.scale.set(keyFrame.scale.factor, keyFrame.scale.factor, keyFrame.scale.factor); } - jointKeyframe.rotation.setFromAxis(keyFrame.rotate.axis.x, keyFrame.rotate.axis.y, keyFrame.rotate.axis.z, MathUtils.radiansToDegrees * keyFrame.rotate.angle).mulLeft(skel.bindPoseJoints.get(jointIndex).rotation).nor(); + jointKeyframe.rotation + .setFromAxis(keyFrame.rotate.axis.x, keyFrame.rotate.axis.y, keyFrame.rotate.axis.z, + MathUtils.radiansToDegrees * keyFrame.rotate.angle).mulLeft(skel.bindPoseJoints.get(jointIndex).rotation) + .nor(); jointKeyframe.parentIndex = skel.bindPoseJoints.get(jointIndex).parentIndex; jointKeyFrames[k] = jointKeyframe; - - + rotation.set(jointKeyframe.rotation); rotation.trn(jointKeyframe.position); transform.set(skel.sceneMatrices.get(jointIndex)); - transform.mul(rotation); - if(jointKeyframe.parentIndex != -1) { + transform.mul(rotation); + if (jointKeyframe.parentIndex != -1) { rotation.set(skel.offsetMatrices.get(jointKeyframe.parentIndex)).mul(transform); - transform.set(rotation); + transform.set(rotation); } - - transform.getTranslation(jointKeyframe.position); + + transform.getTranslation(jointKeyframe.position); transform.getRotation(jointKeyframe.rotation); jointKeyframe.rotation.x *= -1; jointKeyframe.rotation.y *= -1; jointKeyframe.rotation.z *= -1; - } - } - - for(int j = 0; j < perJointkeyFrames.length; j++) { - if(perJointkeyFrames[i] == null) throw new IllegalArgumentException("No track for bone " + skel.jointNames.get(j)); + } } - + + for (int j = 0; j < perJointkeyFrames.length; j++) { + if (perJointkeyFrames[i] == null) throw new IllegalArgumentException("No track for bone " + skel.jointNames.get(j)); + } + skel.animations.put(animation.name, new SkeletonAnimation(animation.name, animation.length, perJointkeyFrames)); } - + return skel; } @@ -426,8 +472,9 @@ private com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton loadOgreSke JAXBContext context = JAXBContext.newInstance(com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton.class); Unmarshaller unmarshaller = context.createUnmarshaller(); long start = System.nanoTime(); - com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton skel = (com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton)unmarshaller.unmarshal(in); - System.out.println("took: " + (System.nanoTime() - start) / 1000000000.0f ); + com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton skel = (com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton.Skeleton)unmarshaller + .unmarshal(in); + System.out.println("took: " + (System.nanoTime() - start) / 1000000000.0f); return skel; } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animation.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animation.java index a817e855bd2..42d6d079aaf 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animation.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animation.java @@ -10,96 +10,63 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "tracks" -}) +@XmlType(name = "", propOrder = {"tracks"}) @XmlRootElement(name = "animation") public class Animation { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String name; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String length; - @XmlElement(required = true) - protected Tracks tracks; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String name; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String length; + @XmlElement(required = true) + protected Tracks tracks; - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } + /** Gets the value of the name property. + * + * @return possible object is {@link String } */ + public String getName () { + return name; + } - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } + /** Sets the value of the name property. + * + * @param value allowed object is {@link String } */ + public void setName (String value) { + this.name = value; + } - /** - * Gets the value of the length property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLength() { - return length; - } + /** Gets the value of the length property. + * + * @return possible object is {@link String } */ + public String getLength () { + return length; + } - /** - * Sets the value of the length property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLength(String value) { - this.length = value; - } + /** Sets the value of the length property. + * + * @param value allowed object is {@link String } */ + public void setLength (String value) { + this.length = value; + } - /** - * Gets the value of the tracks property. - * - * @return - * possible object is - * {@link Tracks } - * - */ - public Tracks getTracks() { - return tracks; - } + /** Gets the value of the tracks property. + * + * @return possible object is {@link Tracks } */ + public Tracks getTracks () { + return tracks; + } - /** - * Sets the value of the tracks property. - * - * @param value - * allowed object is - * {@link Tracks } - * - */ - public void setTracks(Tracks value) { - this.tracks = value; - } + /** Sets the value of the tracks property. + * + * @param value allowed object is {@link Tracks } */ + public void setTracks (Tracks value) { + this.tracks = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animations.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animations.java index cbe21634c7a..78c581e6641 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animations.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Animations.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "animation" -}) +@XmlType(name = "", propOrder = {"animation"}) @XmlRootElement(name = "animations") public class Animations { - @XmlElement(required = true) - protected List animation; - - /** - * Gets the value of the animation property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the animation property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getAnimation().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Animation } - * - * - */ - public List getAnimation() { - if (animation == null) { - animation = new ArrayList(); - } - return this.animation; - } + @XmlElement(required = true) + protected List animation; + + /** Gets the value of the animation property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the animation + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getAnimation().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Animation } */ + public List getAnimation () { + if (animation == null) { + animation = new ArrayList(); + } + return this.animation; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Binormal.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Binormal.java index 77ed0a03715..07ad9ad792e 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Binormal.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Binormal.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "binormal") public class Binormal { - @XmlAttribute(required = true) - public float x; - @XmlAttribute(required = true) - public float y; - @XmlAttribute(required = true) - public float z; + @XmlAttribute(required = true) + public float x; + @XmlAttribute(required = true) + public float y; + @XmlAttribute(required = true) + public float z; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Boneassignments.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Boneassignments.java index 84537cb034b..8dfe885d8d8 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Boneassignments.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Boneassignments.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vertexboneassignment" -}) +@XmlType(name = "", propOrder = {"vertexboneassignment"}) @XmlRootElement(name = "boneassignments") public class Boneassignments { - @XmlElement(required = true) - protected List vertexboneassignment; - - /** - * Gets the value of the vertexboneassignment property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the vertexboneassignment property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getVertexboneassignment().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Vertexboneassignment } - * - * - */ - public List getVertexboneassignment() { - if (vertexboneassignment == null) { - vertexboneassignment = new ArrayList(); - } - return this.vertexboneassignment; - } + @XmlElement(required = true) + protected List vertexboneassignment; + + /** Gets the value of the vertexboneassignment property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the + * vertexboneassignment property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getVertexboneassignment().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Vertexboneassignment } */ + public List getVertexboneassignment () { + if (vertexboneassignment == null) { + vertexboneassignment = new ArrayList(); + } + return this.vertexboneassignment; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourDiffuse.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourDiffuse.java index 5ea858f5747..d7e52599899 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourDiffuse.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourDiffuse.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,32 +17,22 @@ @XmlRootElement(name = "colour_diffuse") public class ColourDiffuse { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String value; - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String value; + + /** Gets the value of the value property. + * + * @return possible object is {@link String } */ + public String getValue () { + return value; + } + + /** Sets the value of the value property. + * + * @param value allowed object is {@link String } */ + public void setValue (String value) { + this.value = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourSpecular.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourSpecular.java index c60f870e3d4..949504b40d4 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourSpecular.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ColourSpecular.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,32 +17,22 @@ @XmlRootElement(name = "colour_specular") public class ColourSpecular { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String value; - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String value; + + /** Gets the value of the value property. + * + * @return possible object is {@link String } */ + public String getValue () { + return value; + } + + /** Sets the value of the value property. + * + * @param value allowed object is {@link String } */ + public void setValue (String value) { + this.value = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Extremes.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Extremes.java index a6138ccb56d..1fe3baacd1d 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Extremes.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Extremes.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "submesh" -}) +@XmlType(name = "", propOrder = {"submesh"}) @XmlRootElement(name = "extremes") public class Extremes { - @XmlElement(required = true) - protected List submesh; - - /** - * Gets the value of the submesh property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the submesh property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getSubmesh().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Submesh } - * - * - */ - public List getSubmesh() { - if (submesh == null) { - submesh = new ArrayList(); - } - return this.submesh; - } + @XmlElement(required = true) + protected List submesh; + + /** Gets the value of the submesh property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the submesh + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getSubmesh().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Submesh } */ + public List getSubmesh () { + if (submesh == null) { + submesh = new ArrayList(); + } + return this.submesh; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Face.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Face.java index 90ab2f0ba42..19bf1da3f32 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Face.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Face.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "face") public class Face { - @XmlAttribute(required = true) - public int v1; - @XmlAttribute - public int v2; - @XmlAttribute - public int v3; + @XmlAttribute(required = true) + public int v1; + @XmlAttribute + public int v2; + @XmlAttribute + public int v3; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Faces.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Faces.java index 329d8cbb0b1..0a0f2027beb 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Faces.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Faces.java @@ -11,49 +11,41 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "face" -}) +@XmlType(name = "", propOrder = {"face"}) @XmlRootElement(name = "faces") public class Faces { - @XmlAttribute - public int count; - @XmlElement(required = true) - protected List face; - - /** - * Gets the value of the face property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the face property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getFace().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Face } - * - * - */ - public List getFace() { - if (face == null) { - face = new ArrayList(); - } - return this.face; - } + @XmlAttribute + public int count; + @XmlElement(required = true) + protected List face; + + /** Gets the value of the face property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the face + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getFace().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Face } */ + public List getFace () { + if (face == null) { + face = new ArrayList(); + } + return this.face; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Geometry.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Geometry.java index e85857daac6..3da00b0ccb6 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Geometry.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Geometry.java @@ -11,49 +11,41 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vertexbuffer" -}) +@XmlType(name = "", propOrder = {"vertexbuffer"}) @XmlRootElement(name = "geometry") public class Geometry { - @XmlAttribute - public int vertexcount; - @XmlElement(required = true) - protected List vertexbuffer; - - /** - * Gets the value of the vertexbuffer property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the vertexbuffer property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getVertexbuffer().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Vertexbuffer } - * - * - */ - public List getVertexbuffer() { - if (vertexbuffer == null) { - vertexbuffer = new ArrayList(); - } - return this.vertexbuffer; - } + @XmlAttribute + public int vertexcount; + @XmlElement(required = true) + protected List vertexbuffer; + + /** Gets the value of the vertexbuffer property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the + * vertexbuffer property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getVertexbuffer().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Vertexbuffer } */ + public List getVertexbuffer () { + if (vertexbuffer == null) { + vertexbuffer = new ArrayList(); + } + return this.vertexbuffer; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframe.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframe.java index b4abda49095..f2bfd5c0b93 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframe.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframe.java @@ -14,109 +14,81 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "positionOrNormal", - "poseref" -}) +@XmlType(name = "", propOrder = {"positionOrNormal", "poseref"}) @XmlRootElement(name = "keyframe") public class Keyframe { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String time; - @XmlElements({ - @XmlElement(name = "position", type = Position.class), - @XmlElement(name = "normal", type = Normal.class) - }) - protected List positionOrNormal; - protected List poseref; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String time; + @XmlElements({@XmlElement(name = "position", type = Position.class), @XmlElement(name = "normal", type = Normal.class)}) + protected List positionOrNormal; + protected List poseref; - /** - * Gets the value of the time property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTime() { - return time; - } + /** Gets the value of the time property. + * + * @return possible object is {@link String } */ + public String getTime () { + return time; + } - /** - * Sets the value of the time property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTime(String value) { - this.time = value; - } + /** Sets the value of the time property. + * + * @param value allowed object is {@link String } */ + public void setTime (String value) { + this.time = value; + } - /** - * Gets the value of the positionOrNormal property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the positionOrNormal property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getPositionOrNormal().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Position } - * {@link Normal } - * - * - */ - public List getPositionOrNormal() { - if (positionOrNormal == null) { - positionOrNormal = new ArrayList(); - } - return this.positionOrNormal; - } + /** Gets the value of the positionOrNormal property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the + * positionOrNormal property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getPositionOrNormal().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Position } {@link Normal } */ + public List getPositionOrNormal () { + if (positionOrNormal == null) { + positionOrNormal = new ArrayList(); + } + return this.positionOrNormal; + } - /** - * Gets the value of the poseref property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the poseref property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getPoseref().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Poseref } - * - * - */ - public List getPoseref() { - if (poseref == null) { - poseref = new ArrayList(); - } - return this.poseref; - } + /** Gets the value of the poseref property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the poseref + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getPoseref().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Poseref } */ + public List getPoseref () { + if (poseref == null) { + poseref = new ArrayList(); + } + return this.poseref; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframes.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframes.java index cc50ce61c76..2f9a35f8a17 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframes.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Keyframes.java @@ -9,46 +9,38 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "keyframe" -}) +@XmlType(name = "", propOrder = {"keyframe"}) @XmlRootElement(name = "keyframes") public class Keyframes { - protected List keyframe; - - /** - * Gets the value of the keyframe property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the keyframe property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getKeyframe().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Keyframe } - * - * - */ - public List getKeyframe() { - if (keyframe == null) { - keyframe = new ArrayList(); - } - return this.keyframe; - } + protected List keyframe; + + /** Gets the value of the keyframe property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the keyframe + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getKeyframe().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Keyframe } */ + public List getKeyframe () { + if (keyframe == null) { + keyframe = new ArrayList(); + } + return this.keyframe; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Levelofdetail.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Levelofdetail.java index fd143b0a072..45ef62ed095 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Levelofdetail.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Levelofdetail.java @@ -15,140 +15,99 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "lodmanualOrLodgenerated" -}) +@XmlType(name = "", propOrder = {"lodmanualOrLodgenerated"}) @XmlRootElement(name = "levelofdetail") public class Levelofdetail { - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String strategy; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String numlevels; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String manual; - @XmlElements({ - @XmlElement(name = "lodmanual", required = true, type = Lodmanual.class), - @XmlElement(name = "lodgenerated", required = true, type = Lodgenerated.class) - }) - protected List lodmanualOrLodgenerated; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String strategy; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String numlevels; + @XmlAttribute + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String manual; + @XmlElements({@XmlElement(name = "lodmanual", required = true, type = Lodmanual.class), + @XmlElement(name = "lodgenerated", required = true, type = Lodgenerated.class)}) + protected List lodmanualOrLodgenerated; - /** - * Gets the value of the strategy property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getStrategy() { - if (strategy == null) { - return "Distance"; - } else { - return strategy; - } - } + /** Gets the value of the strategy property. + * + * @return possible object is {@link String } */ + public String getStrategy () { + if (strategy == null) { + return "Distance"; + } else { + return strategy; + } + } - /** - * Sets the value of the strategy property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setStrategy(String value) { - this.strategy = value; - } + /** Sets the value of the strategy property. + * + * @param value allowed object is {@link String } */ + public void setStrategy (String value) { + this.strategy = value; + } - /** - * Gets the value of the numlevels property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNumlevels() { - return numlevels; - } + /** Gets the value of the numlevels property. + * + * @return possible object is {@link String } */ + public String getNumlevels () { + return numlevels; + } - /** - * Sets the value of the numlevels property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setNumlevels(String value) { - this.numlevels = value; - } + /** Sets the value of the numlevels property. + * + * @param value allowed object is {@link String } */ + public void setNumlevels (String value) { + this.numlevels = value; + } - /** - * Gets the value of the manual property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getManual() { - if (manual == null) { - return "false"; - } else { - return manual; - } - } + /** Gets the value of the manual property. + * + * @return possible object is {@link String } */ + public String getManual () { + if (manual == null) { + return "false"; + } else { + return manual; + } + } - /** - * Sets the value of the manual property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setManual(String value) { - this.manual = value; - } + /** Sets the value of the manual property. + * + * @param value allowed object is {@link String } */ + public void setManual (String value) { + this.manual = value; + } - /** - * Gets the value of the lodmanualOrLodgenerated property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the lodmanualOrLodgenerated property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getLodmanualOrLodgenerated().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Lodmanual } - * {@link Lodgenerated } - * - * - */ - public List getLodmanualOrLodgenerated() { - if (lodmanualOrLodgenerated == null) { - lodmanualOrLodgenerated = new ArrayList(); - } - return this.lodmanualOrLodgenerated; - } + /** Gets the value of the lodmanualOrLodgenerated property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the + * lodmanualOrLodgenerated property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getLodmanualOrLodgenerated().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Lodmanual } {@link Lodgenerated } */ + public List getLodmanualOrLodgenerated () { + if (lodmanualOrLodgenerated == null) { + lodmanualOrLodgenerated = new ArrayList(); + } + return this.lodmanualOrLodgenerated; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodfacelist.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodfacelist.java index a0236994abd..f83378da94d 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodfacelist.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodfacelist.java @@ -13,101 +13,73 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "face" -}) +@XmlType(name = "", propOrder = {"face"}) @XmlRootElement(name = "lodfacelist") public class Lodfacelist { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String submeshindex; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String numfaces; - @XmlElement(required = true) - protected List face; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String submeshindex; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String numfaces; + @XmlElement(required = true) + protected List face; - /** - * Gets the value of the submeshindex property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSubmeshindex() { - return submeshindex; - } + /** Gets the value of the submeshindex property. + * + * @return possible object is {@link String } */ + public String getSubmeshindex () { + return submeshindex; + } - /** - * Sets the value of the submeshindex property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSubmeshindex(String value) { - this.submeshindex = value; - } + /** Sets the value of the submeshindex property. + * + * @param value allowed object is {@link String } */ + public void setSubmeshindex (String value) { + this.submeshindex = value; + } - /** - * Gets the value of the numfaces property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNumfaces() { - return numfaces; - } + /** Gets the value of the numfaces property. + * + * @return possible object is {@link String } */ + public String getNumfaces () { + return numfaces; + } - /** - * Sets the value of the numfaces property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setNumfaces(String value) { - this.numfaces = value; - } + /** Sets the value of the numfaces property. + * + * @param value allowed object is {@link String } */ + public void setNumfaces (String value) { + this.numfaces = value; + } - /** - * Gets the value of the face property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the face property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getFace().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Face } - * - * - */ - public List getFace() { - if (face == null) { - face = new ArrayList(); - } - return this.face; - } + /** Gets the value of the face property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the face + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getFace().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Face } */ + public List getFace () { + if (face == null) { + face = new ArrayList(); + } + return this.face; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodgenerated.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodgenerated.java index 21f8dc35f52..c8aa5ef029b 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodgenerated.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodgenerated.java @@ -10,96 +10,63 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "lodfacelist" -}) +@XmlType(name = "", propOrder = {"lodfacelist"}) @XmlRootElement(name = "lodgenerated") public class Lodgenerated { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String value; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String meshname; - @XmlElement(required = true) - protected Lodfacelist lodfacelist; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String value; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String meshname; + @XmlElement(required = true) + protected Lodfacelist lodfacelist; - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } + /** Gets the value of the value property. + * + * @return possible object is {@link String } */ + public String getValue () { + return value; + } - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } + /** Sets the value of the value property. + * + * @param value allowed object is {@link String } */ + public void setValue (String value) { + this.value = value; + } - /** - * Gets the value of the meshname property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMeshname() { - return meshname; - } + /** Gets the value of the meshname property. + * + * @return possible object is {@link String } */ + public String getMeshname () { + return meshname; + } - /** - * Sets the value of the meshname property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMeshname(String value) { - this.meshname = value; - } + /** Sets the value of the meshname property. + * + * @param value allowed object is {@link String } */ + public void setMeshname (String value) { + this.meshname = value; + } - /** - * Gets the value of the lodfacelist property. - * - * @return - * possible object is - * {@link Lodfacelist } - * - */ - public Lodfacelist getLodfacelist() { - return lodfacelist; - } + /** Gets the value of the lodfacelist property. + * + * @return possible object is {@link Lodfacelist } */ + public Lodfacelist getLodfacelist () { + return lodfacelist; + } - /** - * Sets the value of the lodfacelist property. - * - * @param value - * allowed object is - * {@link Lodfacelist } - * - */ - public void setLodfacelist(Lodfacelist value) { - this.lodfacelist = value; - } + /** Sets the value of the lodfacelist property. + * + * @param value allowed object is {@link Lodfacelist } */ + public void setLodfacelist (Lodfacelist value) { + this.lodfacelist = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodmanual.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodmanual.java index 151d95f2e6f..ef39c7d30c4 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodmanual.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Lodmanual.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,59 +17,39 @@ @XmlRootElement(name = "lodmanual") public class Lodmanual { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String value; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String meshname; - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - - /** - * Gets the value of the meshname property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMeshname() { - return meshname; - } - - /** - * Sets the value of the meshname property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMeshname(String value) { - this.meshname = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String value; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String meshname; + + /** Gets the value of the value property. + * + * @return possible object is {@link String } */ + public String getValue () { + return value; + } + + /** Sets the value of the value property. + * + * @param value allowed object is {@link String } */ + public void setValue (String value) { + this.value = value; + } + + /** Gets the value of the meshname property. + * + * @return possible object is {@link String } */ + public String getMeshname () { + return meshname; + } + + /** Sets the value of the meshname property. + * + * @param value allowed object is {@link String } */ + public void setMeshname (String value) { + this.meshname = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Mesh.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Mesh.java index 18b374eafbe..3549d9b38e0 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Mesh.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Mesh.java @@ -7,250 +7,150 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "sharedgeometry", - "submeshes", - "skeletonlink", - "boneassignments", - "levelofdetail", - "submeshnames", - "poses", - "animations", - "extremes" -}) +@XmlType(name = "", propOrder = {"sharedgeometry", "submeshes", "skeletonlink", "boneassignments", "levelofdetail", + "submeshnames", "poses", "animations", "extremes"}) @XmlRootElement(name = "mesh") public class Mesh { - protected Sharedgeometry sharedgeometry; - @XmlElement(required = true) - protected Submeshes submeshes; - protected Skeletonlink skeletonlink; - protected Boneassignments boneassignments; - protected Levelofdetail levelofdetail; - protected Submeshnames submeshnames; - protected Poses poses; - protected Animations animations; - protected Extremes extremes; - - /** - * Gets the value of the sharedgeometry property. - * - * @return - * possible object is - * {@link Sharedgeometry } - * - */ - public Sharedgeometry getSharedgeometry() { - return sharedgeometry; - } - - /** - * Sets the value of the sharedgeometry property. - * - * @param value - * allowed object is - * {@link Sharedgeometry } - * - */ - public void setSharedgeometry(Sharedgeometry value) { - this.sharedgeometry = value; - } - - /** - * Gets the value of the submeshes property. - * - * @return - * possible object is - * {@link Submeshes } - * - */ - public Submeshes getSubmeshes() { - return submeshes; - } - - /** - * Sets the value of the submeshes property. - * - * @param value - * allowed object is - * {@link Submeshes } - * - */ - public void setSubmeshes(Submeshes value) { - this.submeshes = value; - } - - /** - * Gets the value of the skeletonlink property. - * - * @return - * possible object is - * {@link Skeletonlink } - * - */ - public Skeletonlink getSkeletonlink() { - return skeletonlink; - } - - /** - * Sets the value of the skeletonlink property. - * - * @param value - * allowed object is - * {@link Skeletonlink } - * - */ - public void setSkeletonlink(Skeletonlink value) { - this.skeletonlink = value; - } - - /** - * Gets the value of the boneassignments property. - * - * @return - * possible object is - * {@link Boneassignments } - * - */ - public Boneassignments getBoneassignments() { - return boneassignments; - } - - /** - * Sets the value of the boneassignments property. - * - * @param value - * allowed object is - * {@link Boneassignments } - * - */ - public void setBoneassignments(Boneassignments value) { - this.boneassignments = value; - } - - /** - * Gets the value of the levelofdetail property. - * - * @return - * possible object is - * {@link Levelofdetail } - * - */ - public Levelofdetail getLevelofdetail() { - return levelofdetail; - } - - /** - * Sets the value of the levelofdetail property. - * - * @param value - * allowed object is - * {@link Levelofdetail } - * - */ - public void setLevelofdetail(Levelofdetail value) { - this.levelofdetail = value; - } - - /** - * Gets the value of the submeshnames property. - * - * @return - * possible object is - * {@link Submeshnames } - * - */ - public Submeshnames getSubmeshnames() { - return submeshnames; - } - - /** - * Sets the value of the submeshnames property. - * - * @param value - * allowed object is - * {@link Submeshnames } - * - */ - public void setSubmeshnames(Submeshnames value) { - this.submeshnames = value; - } - - /** - * Gets the value of the poses property. - * - * @return - * possible object is - * {@link Poses } - * - */ - public Poses getPoses() { - return poses; - } - - /** - * Sets the value of the poses property. - * - * @param value - * allowed object is - * {@link Poses } - * - */ - public void setPoses(Poses value) { - this.poses = value; - } - - /** - * Gets the value of the animations property. - * - * @return - * possible object is - * {@link Animations } - * - */ - public Animations getAnimations() { - return animations; - } - - /** - * Sets the value of the animations property. - * - * @param value - * allowed object is - * {@link Animations } - * - */ - public void setAnimations(Animations value) { - this.animations = value; - } - - /** - * Gets the value of the extremes property. - * - * @return - * possible object is - * {@link Extremes } - * - */ - public Extremes getExtremes() { - return extremes; - } - - /** - * Sets the value of the extremes property. - * - * @param value - * allowed object is - * {@link Extremes } - * - */ - public void setExtremes(Extremes value) { - this.extremes = value; - } + protected Sharedgeometry sharedgeometry; + @XmlElement(required = true) + protected Submeshes submeshes; + protected Skeletonlink skeletonlink; + protected Boneassignments boneassignments; + protected Levelofdetail levelofdetail; + protected Submeshnames submeshnames; + protected Poses poses; + protected Animations animations; + protected Extremes extremes; + + /** Gets the value of the sharedgeometry property. + * + * @return possible object is {@link Sharedgeometry } */ + public Sharedgeometry getSharedgeometry () { + return sharedgeometry; + } + + /** Sets the value of the sharedgeometry property. + * + * @param value allowed object is {@link Sharedgeometry } */ + public void setSharedgeometry (Sharedgeometry value) { + this.sharedgeometry = value; + } + + /** Gets the value of the submeshes property. + * + * @return possible object is {@link Submeshes } */ + public Submeshes getSubmeshes () { + return submeshes; + } + + /** Sets the value of the submeshes property. + * + * @param value allowed object is {@link Submeshes } */ + public void setSubmeshes (Submeshes value) { + this.submeshes = value; + } + + /** Gets the value of the skeletonlink property. + * + * @return possible object is {@link Skeletonlink } */ + public Skeletonlink getSkeletonlink () { + return skeletonlink; + } + + /** Sets the value of the skeletonlink property. + * + * @param value allowed object is {@link Skeletonlink } */ + public void setSkeletonlink (Skeletonlink value) { + this.skeletonlink = value; + } + + /** Gets the value of the boneassignments property. + * + * @return possible object is {@link Boneassignments } */ + public Boneassignments getBoneassignments () { + return boneassignments; + } + + /** Sets the value of the boneassignments property. + * + * @param value allowed object is {@link Boneassignments } */ + public void setBoneassignments (Boneassignments value) { + this.boneassignments = value; + } + + /** Gets the value of the levelofdetail property. + * + * @return possible object is {@link Levelofdetail } */ + public Levelofdetail getLevelofdetail () { + return levelofdetail; + } + + /** Sets the value of the levelofdetail property. + * + * @param value allowed object is {@link Levelofdetail } */ + public void setLevelofdetail (Levelofdetail value) { + this.levelofdetail = value; + } + + /** Gets the value of the submeshnames property. + * + * @return possible object is {@link Submeshnames } */ + public Submeshnames getSubmeshnames () { + return submeshnames; + } + + /** Sets the value of the submeshnames property. + * + * @param value allowed object is {@link Submeshnames } */ + public void setSubmeshnames (Submeshnames value) { + this.submeshnames = value; + } + + /** Gets the value of the poses property. + * + * @return possible object is {@link Poses } */ + public Poses getPoses () { + return poses; + } + + /** Sets the value of the poses property. + * + * @param value allowed object is {@link Poses } */ + public void setPoses (Poses value) { + this.poses = value; + } + + /** Gets the value of the animations property. + * + * @return possible object is {@link Animations } */ + public Animations getAnimations () { + return animations; + } + + /** Sets the value of the animations property. + * + * @param value allowed object is {@link Animations } */ + public void setAnimations (Animations value) { + this.animations = value; + } + + /** Gets the value of the extremes property. + * + * @return possible object is {@link Extremes } */ + public Extremes getExtremes () { + return extremes; + } + + /** Sets the value of the extremes property. + * + * @param value allowed object is {@link Extremes } */ + public void setExtremes (Extremes value) { + this.extremes = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Normal.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Normal.java index fc559827d9d..b845610ee80 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Normal.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Normal.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "normal") public class Normal { - @XmlAttribute(required = true) - public float x; - @XmlAttribute(required = true) - public float y; - @XmlAttribute(required = true) - public float z; + @XmlAttribute(required = true) + public float x; + @XmlAttribute(required = true) + public float y; + @XmlAttribute(required = true) + public float z; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ObjectFactory.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ObjectFactory.java index 75c8780a816..1b72197dedf 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ObjectFactory.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/ObjectFactory.java @@ -3,342 +3,213 @@ import javax.xml.bind.annotation.XmlRegistry; - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.badlogic.gdx.graphics.g3d.orgrexml.mesh package. - *

        An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ +/** This object contains factory methods for each Java content interface and Java element interface generated in the + * com.badlogic.gdx.graphics.g3d.orgrexml.mesh package. + *

        + * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. The Java + * representation of XML content can consist of schema derived interfaces and classes representing the binding of schema type + * definitions, element declarations and model groups. Factory methods for each of these are provided in this class. */ @XmlRegistry public class ObjectFactory { - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.badlogic.gdx.graphics.g3d.orgrexml.mesh - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Vertexbuffer } - * - */ - public Vertexbuffer createVertexbuffer() { - return new Vertexbuffer(); - } - - /** - * Create an instance of {@link Position } - * - */ - public Position createPosition() { - return new Position(); - } - - /** - * Create an instance of {@link ColourDiffuse } - * - */ - public ColourDiffuse createColourDiffuse() { - return new ColourDiffuse(); - } - - /** - * Create an instance of {@link Texture } - * - */ - public Texture createTexture() { - return new Texture(); - } - - /** - * Create an instance of {@link Binormal } - * - */ - public Binormal createBinormal() { - return new Binormal(); - } - - /** - * Create an instance of {@link Submesh } - * - */ - public Submesh createSubmesh() { - return new Submesh(); - } - - /** - * Create an instance of {@link Pose } - * - */ - public Pose createPose() { - return new Pose(); - } - - /** - * Create an instance of {@link Lodgenerated } - * - */ - public Lodgenerated createLodgenerated() { - return new Lodgenerated(); - } - - /** - * Create an instance of {@link Submeshnames } - * - */ - public Submeshnames createSubmeshnames() { - return new Submeshnames(); - } - - /** - * Create an instance of {@link Mesh } - * - */ - public Mesh createMesh() { - return new Mesh(); - } - - /** - * Create an instance of {@link Texcoord } - * - */ - public Texcoord createTexcoord() { - return new Texcoord(); - } - - /** - * Create an instance of {@link Poseoffset } - * - */ - public Poseoffset createPoseoffset() { - return new Poseoffset(); - } - - /** - * Create an instance of {@link Poseref } - * - */ - public Poseref createPoseref() { - return new Poseref(); - } - - /** - * Create an instance of {@link Submeshes } - * - */ - public Submeshes createSubmeshes() { - return new Submeshes(); - } - - /** - * Create an instance of {@link ColourSpecular } - * - */ - public ColourSpecular createColourSpecular() { - return new ColourSpecular(); - } - - /** - * Create an instance of {@link Animation } - * - */ - public Animation createAnimation() { - return new Animation(); - } - - /** - * Create an instance of {@link Track } - * - */ - public Track createTrack() { - return new Track(); - } - - /** - * Create an instance of {@link Keyframes } - * - */ - public Keyframes createKeyframes() { - return new Keyframes(); - } - - /** - * Create an instance of {@link Vertexboneassignment } - * - */ - public Vertexboneassignment createVertexboneassignment() { - return new Vertexboneassignment(); - } - - /** - * Create an instance of {@link Lodfacelist } - * - */ - public Lodfacelist createLodfacelist() { - return new Lodfacelist(); - } - - /** - * Create an instance of {@link Skeletonlink } - * - */ - public Skeletonlink createSkeletonlink() { - return new Skeletonlink(); - } - - /** - * Create an instance of {@link Extremes } - * - */ - public Extremes createExtremes() { - return new Extremes(); - } - - /** - * Create an instance of {@link Geometry } - * - */ - public Geometry createGeometry() { - return new Geometry(); - } - - /** - * Create an instance of {@link Lodmanual } - * - */ - public Lodmanual createLodmanual() { - return new Lodmanual(); - } - - /** - * Create an instance of {@link Vertex } - * - */ - public Vertex createVertex() { - return new Vertex(); - } - - /** - * Create an instance of {@link Tracks } - * - */ - public Tracks createTracks() { - return new Tracks(); - } - - /** - * Create an instance of {@link Animations } - * - */ - public Animations createAnimations() { - return new Animations(); - } - - /** - * Create an instance of {@link Levelofdetail } - * - */ - public Levelofdetail createLevelofdetail() { - return new Levelofdetail(); - } - - /** - * Create an instance of {@link Normal } - * - */ - public Normal createNormal() { - return new Normal(); - } - - /** - * Create an instance of {@link Textures } - * - */ - public Textures createTextures() { - return new Textures(); - } - - /** - * Create an instance of {@link Tangent } - * - */ - public Tangent createTangent() { - return new Tangent(); - } - - /** - * Create an instance of {@link Face } - * - */ - public Face createFace() { - return new Face(); - } - - /** - * Create an instance of {@link Sharedgeometry } - * - */ - public Sharedgeometry createSharedgeometry() { - return new Sharedgeometry(); - } - - /** - * Create an instance of {@link Keyframe } - * - */ - public Keyframe createKeyframe() { - return new Keyframe(); - } - - /** - * Create an instance of {@link Faces } - * - */ - public Faces createFaces() { - return new Faces(); - } - - /** - * Create an instance of {@link Boneassignments } - * - */ - public Boneassignments createBoneassignments() { - return new Boneassignments(); - } - - /** - * Create an instance of {@link SubmeshExtremes } - * - */ - public SubmeshExtremes createSubmeshExtremes() { - return new SubmeshExtremes(); - } - - /** - * Create an instance of {@link Poses } - * - */ - public Poses createPoses() { - return new Poses(); - } - - /** - * Create an instance of {@link Submeshname } - * - */ - public Submeshname createSubmeshname() { - return new Submeshname(); - } + /** Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: + * com.badlogic.gdx.graphics.g3d.orgrexml.mesh */ + public ObjectFactory () { + } + + /** Create an instance of {@link Vertexbuffer } */ + public Vertexbuffer createVertexbuffer () { + return new Vertexbuffer(); + } + + /** Create an instance of {@link Position } */ + public Position createPosition () { + return new Position(); + } + + /** Create an instance of {@link ColourDiffuse } */ + public ColourDiffuse createColourDiffuse () { + return new ColourDiffuse(); + } + + /** Create an instance of {@link Texture } */ + public Texture createTexture () { + return new Texture(); + } + + /** Create an instance of {@link Binormal } */ + public Binormal createBinormal () { + return new Binormal(); + } + + /** Create an instance of {@link Submesh } */ + public Submesh createSubmesh () { + return new Submesh(); + } + + /** Create an instance of {@link Pose } */ + public Pose createPose () { + return new Pose(); + } + + /** Create an instance of {@link Lodgenerated } */ + public Lodgenerated createLodgenerated () { + return new Lodgenerated(); + } + + /** Create an instance of {@link Submeshnames } */ + public Submeshnames createSubmeshnames () { + return new Submeshnames(); + } + + /** Create an instance of {@link Mesh } */ + public Mesh createMesh () { + return new Mesh(); + } + + /** Create an instance of {@link Texcoord } */ + public Texcoord createTexcoord () { + return new Texcoord(); + } + + /** Create an instance of {@link Poseoffset } */ + public Poseoffset createPoseoffset () { + return new Poseoffset(); + } + + /** Create an instance of {@link Poseref } */ + public Poseref createPoseref () { + return new Poseref(); + } + + /** Create an instance of {@link Submeshes } */ + public Submeshes createSubmeshes () { + return new Submeshes(); + } + + /** Create an instance of {@link ColourSpecular } */ + public ColourSpecular createColourSpecular () { + return new ColourSpecular(); + } + + /** Create an instance of {@link Animation } */ + public Animation createAnimation () { + return new Animation(); + } + + /** Create an instance of {@link Track } */ + public Track createTrack () { + return new Track(); + } + + /** Create an instance of {@link Keyframes } */ + public Keyframes createKeyframes () { + return new Keyframes(); + } + + /** Create an instance of {@link Vertexboneassignment } */ + public Vertexboneassignment createVertexboneassignment () { + return new Vertexboneassignment(); + } + + /** Create an instance of {@link Lodfacelist } */ + public Lodfacelist createLodfacelist () { + return new Lodfacelist(); + } + + /** Create an instance of {@link Skeletonlink } */ + public Skeletonlink createSkeletonlink () { + return new Skeletonlink(); + } + + /** Create an instance of {@link Extremes } */ + public Extremes createExtremes () { + return new Extremes(); + } + + /** Create an instance of {@link Geometry } */ + public Geometry createGeometry () { + return new Geometry(); + } + + /** Create an instance of {@link Lodmanual } */ + public Lodmanual createLodmanual () { + return new Lodmanual(); + } + + /** Create an instance of {@link Vertex } */ + public Vertex createVertex () { + return new Vertex(); + } + + /** Create an instance of {@link Tracks } */ + public Tracks createTracks () { + return new Tracks(); + } + + /** Create an instance of {@link Animations } */ + public Animations createAnimations () { + return new Animations(); + } + + /** Create an instance of {@link Levelofdetail } */ + public Levelofdetail createLevelofdetail () { + return new Levelofdetail(); + } + + /** Create an instance of {@link Normal } */ + public Normal createNormal () { + return new Normal(); + } + + /** Create an instance of {@link Textures } */ + public Textures createTextures () { + return new Textures(); + } + + /** Create an instance of {@link Tangent } */ + public Tangent createTangent () { + return new Tangent(); + } + + /** Create an instance of {@link Face } */ + public Face createFace () { + return new Face(); + } + + /** Create an instance of {@link Sharedgeometry } */ + public Sharedgeometry createSharedgeometry () { + return new Sharedgeometry(); + } + + /** Create an instance of {@link Keyframe } */ + public Keyframe createKeyframe () { + return new Keyframe(); + } + + /** Create an instance of {@link Faces } */ + public Faces createFaces () { + return new Faces(); + } + + /** Create an instance of {@link Boneassignments } */ + public Boneassignments createBoneassignments () { + return new Boneassignments(); + } + + /** Create an instance of {@link SubmeshExtremes } */ + public SubmeshExtremes createSubmeshExtremes () { + return new SubmeshExtremes(); + } + + /** Create an instance of {@link Poses } */ + public Poses createPoses () { + return new Poses(); + } + + /** Create an instance of {@link Submeshname } */ + public Submeshname createSubmeshname () { + return new Submeshname(); + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Pose.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Pose.java index 61c4c6dc30d..a28c0807ef7 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Pose.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Pose.java @@ -14,136 +14,98 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "poseoffset" -}) +@XmlType(name = "", propOrder = {"poseoffset"}) @XmlRootElement(name = "pose") public class Pose { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String target; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String index; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String name; - @XmlElement(required = true) - protected List poseoffset; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String target; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String index; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String name; + @XmlElement(required = true) + protected List poseoffset; - /** - * Gets the value of the target property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTarget() { - return target; - } + /** Gets the value of the target property. + * + * @return possible object is {@link String } */ + public String getTarget () { + return target; + } - /** - * Sets the value of the target property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTarget(String value) { - this.target = value; - } + /** Sets the value of the target property. + * + * @param value allowed object is {@link String } */ + public void setTarget (String value) { + this.target = value; + } - /** - * Gets the value of the index property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getIndex() { - if (index == null) { - return "0"; - } else { - return index; - } - } + /** Gets the value of the index property. + * + * @return possible object is {@link String } */ + public String getIndex () { + if (index == null) { + return "0"; + } else { + return index; + } + } - /** - * Sets the value of the index property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setIndex(String value) { - this.index = value; - } + /** Sets the value of the index property. + * + * @param value allowed object is {@link String } */ + public void setIndex (String value) { + this.index = value; + } - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - if (name == null) { - return ""; - } else { - return name; - } - } + /** Gets the value of the name property. + * + * @return possible object is {@link String } */ + public String getName () { + if (name == null) { + return ""; + } else { + return name; + } + } - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } + /** Sets the value of the name property. + * + * @param value allowed object is {@link String } */ + public void setName (String value) { + this.name = value; + } - /** - * Gets the value of the poseoffset property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the poseoffset property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getPoseoffset().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Poseoffset } - * - * - */ - public List getPoseoffset() { - if (poseoffset == null) { - poseoffset = new ArrayList(); - } - return this.poseoffset; - } + /** Gets the value of the poseoffset property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the poseoffset + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getPoseoffset().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Poseoffset } */ + public List getPoseoffset () { + if (poseoffset == null) { + poseoffset = new ArrayList(); + } + return this.poseoffset; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseoffset.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseoffset.java index 301c3e732df..28ab5bd1b55 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseoffset.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseoffset.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,206 +17,136 @@ @XmlRootElement(name = "poseoffset") public class Poseoffset { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String index; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String x; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String y; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String z; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String nx; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String ny; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String nz; - - /** - * Gets the value of the index property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getIndex() { - return index; - } - - /** - * Sets the value of the index property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setIndex(String value) { - this.index = value; - } - - /** - * Gets the value of the x property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getX() { - return x; - } - - /** - * Sets the value of the x property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setX(String value) { - this.x = value; - } - - /** - * Gets the value of the y property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getY() { - return y; - } - - /** - * Sets the value of the y property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setY(String value) { - this.y = value; - } - - /** - * Gets the value of the z property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getZ() { - return z; - } - - /** - * Sets the value of the z property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setZ(String value) { - this.z = value; - } - - /** - * Gets the value of the nx property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNx() { - if (nx == null) { - return ""; - } else { - return nx; - } - } - - /** - * Sets the value of the nx property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setNx(String value) { - this.nx = value; - } - - /** - * Gets the value of the ny property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNy() { - if (ny == null) { - return ""; - } else { - return ny; - } - } - - /** - * Sets the value of the ny property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setNy(String value) { - this.ny = value; - } - - /** - * Gets the value of the nz property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNz() { - if (nz == null) { - return ""; - } else { - return nz; - } - } - - /** - * Sets the value of the nz property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setNz(String value) { - this.nz = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String index; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String x; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String y; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String z; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String nx; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String ny; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String nz; + + /** Gets the value of the index property. + * + * @return possible object is {@link String } */ + public String getIndex () { + return index; + } + + /** Sets the value of the index property. + * + * @param value allowed object is {@link String } */ + public void setIndex (String value) { + this.index = value; + } + + /** Gets the value of the x property. + * + * @return possible object is {@link String } */ + public String getX () { + return x; + } + + /** Sets the value of the x property. + * + * @param value allowed object is {@link String } */ + public void setX (String value) { + this.x = value; + } + + /** Gets the value of the y property. + * + * @return possible object is {@link String } */ + public String getY () { + return y; + } + + /** Sets the value of the y property. + * + * @param value allowed object is {@link String } */ + public void setY (String value) { + this.y = value; + } + + /** Gets the value of the z property. + * + * @return possible object is {@link String } */ + public String getZ () { + return z; + } + + /** Sets the value of the z property. + * + * @param value allowed object is {@link String } */ + public void setZ (String value) { + this.z = value; + } + + /** Gets the value of the nx property. + * + * @return possible object is {@link String } */ + public String getNx () { + if (nx == null) { + return ""; + } else { + return nx; + } + } + + /** Sets the value of the nx property. + * + * @param value allowed object is {@link String } */ + public void setNx (String value) { + this.nx = value; + } + + /** Gets the value of the ny property. + * + * @return possible object is {@link String } */ + public String getNy () { + if (ny == null) { + return ""; + } else { + return ny; + } + } + + /** Sets the value of the ny property. + * + * @param value allowed object is {@link String } */ + public void setNy (String value) { + this.ny = value; + } + + /** Gets the value of the nz property. + * + * @return possible object is {@link String } */ + public String getNz () { + if (nz == null) { + return ""; + } else { + return nz; + } + } + + /** Sets the value of the nz property. + * + * @param value allowed object is {@link String } */ + public void setNz (String value) { + this.nz = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseref.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseref.java index 9dabb620ebb..70841068c1a 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseref.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poseref.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,63 +17,43 @@ @XmlRootElement(name = "poseref") public class Poseref { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String poseindex; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String influence; - - /** - * Gets the value of the poseindex property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getPoseindex() { - return poseindex; - } - - /** - * Sets the value of the poseindex property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setPoseindex(String value) { - this.poseindex = value; - } - - /** - * Gets the value of the influence property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getInfluence() { - if (influence == null) { - return "1.0"; - } else { - return influence; - } - } - - /** - * Sets the value of the influence property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setInfluence(String value) { - this.influence = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String poseindex; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String influence; + + /** Gets the value of the poseindex property. + * + * @return possible object is {@link String } */ + public String getPoseindex () { + return poseindex; + } + + /** Sets the value of the poseindex property. + * + * @param value allowed object is {@link String } */ + public void setPoseindex (String value) { + this.poseindex = value; + } + + /** Gets the value of the influence property. + * + * @return possible object is {@link String } */ + public String getInfluence () { + if (influence == null) { + return "1.0"; + } else { + return influence; + } + } + + /** Sets the value of the influence property. + * + * @param value allowed object is {@link String } */ + public void setInfluence (String value) { + this.influence = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poses.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poses.java index 09b4d80bb05..7af9e72c444 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poses.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Poses.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "pose" -}) +@XmlType(name = "", propOrder = {"pose"}) @XmlRootElement(name = "poses") public class Poses { - @XmlElement(required = true) - protected List pose; - - /** - * Gets the value of the pose property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the pose property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getPose().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Pose } - * - * - */ - public List getPose() { - if (pose == null) { - pose = new ArrayList(); - } - return this.pose; - } + @XmlElement(required = true) + protected List pose; + + /** Gets the value of the pose property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the pose + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getPose().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Pose } */ + public List getPose () { + if (pose == null) { + pose = new ArrayList(); + } + return this.pose; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Position.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Position.java index 9598b540263..732b10cb0a7 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Position.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Position.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "position") public class Position { - @XmlAttribute(required = true) - public float x; - @XmlAttribute(required = true) - public float y; - @XmlAttribute(required = true) - public float z; + @XmlAttribute(required = true) + public float x; + @XmlAttribute(required = true) + public float y; + @XmlAttribute(required = true) + public float z; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Sharedgeometry.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Sharedgeometry.java index e11dacbcff6..890b1833c50 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Sharedgeometry.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Sharedgeometry.java @@ -13,74 +13,56 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vertexbuffer" -}) +@XmlType(name = "", propOrder = {"vertexbuffer"}) @XmlRootElement(name = "sharedgeometry") public class Sharedgeometry { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String vertexcount; - @XmlElement(required = true) - protected List vertexbuffer; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String vertexcount; + @XmlElement(required = true) + protected List vertexbuffer; - /** - * Gets the value of the vertexcount property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVertexcount() { - return vertexcount; - } + /** Gets the value of the vertexcount property. + * + * @return possible object is {@link String } */ + public String getVertexcount () { + return vertexcount; + } - /** - * Sets the value of the vertexcount property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVertexcount(String value) { - this.vertexcount = value; - } + /** Sets the value of the vertexcount property. + * + * @param value allowed object is {@link String } */ + public void setVertexcount (String value) { + this.vertexcount = value; + } - /** - * Gets the value of the vertexbuffer property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the vertexbuffer property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getVertexbuffer().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Vertexbuffer } - * - * - */ - public List getVertexbuffer() { - if (vertexbuffer == null) { - vertexbuffer = new ArrayList(); - } - return this.vertexbuffer; - } + /** Gets the value of the vertexbuffer property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the + * vertexbuffer property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getVertexbuffer().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Vertexbuffer } */ + public List getVertexbuffer () { + if (vertexbuffer == null) { + vertexbuffer = new ArrayList(); + } + return this.vertexbuffer; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Skeletonlink.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Skeletonlink.java index bfbdc5445a8..9ea5bd5ab67 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Skeletonlink.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Skeletonlink.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,32 +17,22 @@ @XmlRootElement(name = "skeletonlink") public class Skeletonlink { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String name; - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String name; + + /** Gets the value of the name property. + * + * @return possible object is {@link String } */ + public String getName () { + return name; + } + + /** Sets the value of the name property. + * + * @param value allowed object is {@link String } */ + public void setName (String value) { + this.name = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submesh.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submesh.java index cf96cf94df8..b93d30eeb9f 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submesh.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submesh.java @@ -11,182 +11,116 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "textures", - "faces", - "geometry", - "boneassignments" -}) +@XmlType(name = "", propOrder = {"textures", "faces", "geometry", "boneassignments"}) @XmlRootElement(name = "submesh") public class Submesh { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - public String material; - @XmlAttribute(name = "usesharedvertices") - public boolean useSharedVertices; - @XmlAttribute(name = "use32bitindexes") - public boolean use32Bitindexes; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String operationtype; - protected Textures textures; - @XmlElement(required = true) - protected Faces faces; - protected Geometry geometry; - protected Boneassignments boneassignments; - - /** - * Gets the value of the material property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMaterial() { - return material; - } - - /** - * Sets the value of the material property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMaterial(String value) { - this.material = value; - } - - /** - * Gets the value of the operationtype property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getOperationtype() { - if (operationtype == null) { - return "triangle_list"; - } else { - return operationtype; - } - } - - /** - * Sets the value of the operationtype property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setOperationtype(String value) { - this.operationtype = value; - } - - /** - * Gets the value of the textures property. - * - * @return - * possible object is - * {@link Textures } - * - */ - public Textures getTextures() { - return textures; - } - - /** - * Sets the value of the textures property. - * - * @param value - * allowed object is - * {@link Textures } - * - */ - public void setTextures(Textures value) { - this.textures = value; - } - - /** - * Gets the value of the faces property. - * - * @return - * possible object is - * {@link Faces } - * - */ - public Faces getFaces() { - return faces; - } - - /** - * Sets the value of the faces property. - * - * @param value - * allowed object is - * {@link Faces } - * - */ - public void setFaces(Faces value) { - this.faces = value; - } - - /** - * Gets the value of the geometry property. - * - * @return - * possible object is - * {@link Geometry } - * - */ - public Geometry getGeometry() { - return geometry; - } - - /** - * Sets the value of the geometry property. - * - * @param value - * allowed object is - * {@link Geometry } - * - */ - public void setGeometry(Geometry value) { - this.geometry = value; - } - - /** - * Gets the value of the boneassignments property. - * - * @return - * possible object is - * {@link Boneassignments } - * - */ - public Boneassignments getBoneassignments() { - return boneassignments; - } - - /** - * Sets the value of the boneassignments property. - * - * @param value - * allowed object is - * {@link Boneassignments } - * - */ - public void setBoneassignments(Boneassignments value) { - this.boneassignments = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + public String material; + @XmlAttribute(name = "usesharedvertices") + public boolean useSharedVertices; + @XmlAttribute(name = "use32bitindexes") + public boolean use32Bitindexes; + @XmlAttribute + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String operationtype; + protected Textures textures; + @XmlElement(required = true) + protected Faces faces; + protected Geometry geometry; + protected Boneassignments boneassignments; + + /** Gets the value of the material property. + * + * @return possible object is {@link String } */ + public String getMaterial () { + return material; + } + + /** Sets the value of the material property. + * + * @param value allowed object is {@link String } */ + public void setMaterial (String value) { + this.material = value; + } + + /** Gets the value of the operationtype property. + * + * @return possible object is {@link String } */ + public String getOperationtype () { + if (operationtype == null) { + return "triangle_list"; + } else { + return operationtype; + } + } + + /** Sets the value of the operationtype property. + * + * @param value allowed object is {@link String } */ + public void setOperationtype (String value) { + this.operationtype = value; + } + + /** Gets the value of the textures property. + * + * @return possible object is {@link Textures } */ + public Textures getTextures () { + return textures; + } + + /** Sets the value of the textures property. + * + * @param value allowed object is {@link Textures } */ + public void setTextures (Textures value) { + this.textures = value; + } + + /** Gets the value of the faces property. + * + * @return possible object is {@link Faces } */ + public Faces getFaces () { + return faces; + } + + /** Sets the value of the faces property. + * + * @param value allowed object is {@link Faces } */ + public void setFaces (Faces value) { + this.faces = value; + } + + /** Gets the value of the geometry property. + * + * @return possible object is {@link Geometry } */ + public Geometry getGeometry () { + return geometry; + } + + /** Sets the value of the geometry property. + * + * @param value allowed object is {@link Geometry } */ + public void setGeometry (Geometry value) { + this.geometry = value; + } + + /** Gets the value of the boneassignments property. + * + * @return possible object is {@link Boneassignments } */ + public Boneassignments getBoneassignments () { + return boneassignments; + } + + /** Sets the value of the boneassignments property. + * + * @param value allowed object is {@link Boneassignments } */ + public void setBoneassignments (Boneassignments value) { + this.boneassignments = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/SubmeshExtremes.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/SubmeshExtremes.java index 7bf4e877c36..457dc45ffe0 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/SubmeshExtremes.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/SubmeshExtremes.java @@ -13,74 +13,56 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "position" -}) +@XmlType(name = "", propOrder = {"position"}) @XmlRootElement(name = "submesh_extremes") public class SubmeshExtremes { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String index; - @XmlElement(required = true) - protected List position; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String index; + @XmlElement(required = true) + protected List position; - /** - * Gets the value of the index property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getIndex() { - return index; - } + /** Gets the value of the index property. + * + * @return possible object is {@link String } */ + public String getIndex () { + return index; + } - /** - * Sets the value of the index property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setIndex(String value) { - this.index = value; - } + /** Sets the value of the index property. + * + * @param value allowed object is {@link String } */ + public void setIndex (String value) { + this.index = value; + } - /** - * Gets the value of the position property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the position property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getPosition().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Position } - * - * - */ - public List getPosition() { - if (position == null) { - position = new ArrayList(); - } - return this.position; - } + /** Gets the value of the position property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the position + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getPosition().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Position } */ + public List getPosition () { + if (position == null) { + position = new ArrayList(); + } + return this.position; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshes.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshes.java index 0895ed17480..7680be024fd 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshes.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshes.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "submesh" -}) +@XmlType(name = "", propOrder = {"submesh"}) @XmlRootElement(name = "submeshes") public class Submeshes { - @XmlElement(required = true) - protected List submesh; - - /** - * Gets the value of the submesh property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the submesh property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getSubmesh().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Submesh } - * - * - */ - public List getSubmesh() { - if (submesh == null) { - submesh = new ArrayList(); - } - return this.submesh; - } + @XmlElement(required = true) + protected List submesh; + + /** Gets the value of the submesh property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the submesh + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getSubmesh().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Submesh } */ + public List getSubmesh () { + if (submesh == null) { + submesh = new ArrayList(); + } + return this.submesh; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshname.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshname.java index 6c7880d97dc..53db2cb35a6 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshname.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshname.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,59 +17,39 @@ @XmlRootElement(name = "submeshname") public class Submeshname { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String name; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String index; - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - - /** - * Gets the value of the index property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getIndex() { - return index; - } - - /** - * Sets the value of the index property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setIndex(String value) { - this.index = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String name; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String index; + + /** Gets the value of the name property. + * + * @return possible object is {@link String } */ + public String getName () { + return name; + } + + /** Sets the value of the name property. + * + * @param value allowed object is {@link String } */ + public void setName (String value) { + this.name = value; + } + + /** Gets the value of the index property. + * + * @return possible object is {@link String } */ + public String getIndex () { + return index; + } + + /** Sets the value of the index property. + * + * @param value allowed object is {@link String } */ + public void setIndex (String value) { + this.index = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshnames.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshnames.java index 15394789941..9252adace66 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshnames.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Submeshnames.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "submeshname" -}) +@XmlType(name = "", propOrder = {"submeshname"}) @XmlRootElement(name = "submeshnames") public class Submeshnames { - @XmlElement(required = true) - protected List submeshname; - - /** - * Gets the value of the submeshname property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the submeshname property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getSubmeshname().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Submeshname } - * - * - */ - public List getSubmeshname() { - if (submeshname == null) { - submeshname = new ArrayList(); - } - return this.submeshname; - } + @XmlElement(required = true) + protected List submeshname; + + /** Gets the value of the submeshname property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the submeshname + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getSubmeshname().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Submeshname } */ + public List getSubmeshname () { + if (submeshname == null) { + submeshname = new ArrayList(); + } + return this.submeshname; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tangent.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tangent.java index 332fe984a51..6442ca3a882 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tangent.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tangent.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,12 +15,12 @@ @XmlRootElement(name = "tangent") public class Tangent { - @XmlAttribute(required = true) - public float x; - @XmlAttribute(required = true) - public float y; - @XmlAttribute(required = true) - public float z; - @XmlAttribute - public float w; + @XmlAttribute(required = true) + public float x; + @XmlAttribute(required = true) + public float y; + @XmlAttribute(required = true) + public float z; + @XmlAttribute + public float w; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texcoord.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texcoord.java index cd0a82291e9..f5158ba0bac 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texcoord.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texcoord.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -15,12 +14,12 @@ @XmlType(name = "") @XmlRootElement(name = "texcoord") public class Texcoord { - @XmlAttribute(required = true) - public float u; - @XmlAttribute - public float v; - @XmlAttribute - public float w; - @XmlAttribute - public float x; + @XmlAttribute(required = true) + public float u; + @XmlAttribute + public float v; + @XmlAttribute + public float w; + @XmlAttribute + public float x; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texture.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texture.java index 692d659c174..4748d70fbf3 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texture.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Texture.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,59 +17,39 @@ @XmlRootElement(name = "texture") public class Texture { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String alias; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String name; - - /** - * Gets the value of the alias property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAlias() { - return alias; - } - - /** - * Sets the value of the alias property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAlias(String value) { - this.alias = value; - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String alias; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String name; + + /** Gets the value of the alias property. + * + * @return possible object is {@link String } */ + public String getAlias () { + return alias; + } + + /** Sets the value of the alias property. + * + * @param value allowed object is {@link String } */ + public void setAlias (String value) { + this.alias = value; + } + + /** Gets the value of the name property. + * + * @return possible object is {@link String } */ + public String getName () { + return name; + } + + /** Sets the value of the name property. + * + * @param value allowed object is {@link String } */ + public void setName (String value) { + this.name = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Textures.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Textures.java index aacf4303122..e2430b937bb 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Textures.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Textures.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "texture" -}) +@XmlType(name = "", propOrder = {"texture"}) @XmlRootElement(name = "textures") public class Textures { - @XmlElement(required = true) - protected List texture; - - /** - * Gets the value of the texture property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the texture property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getTexture().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Texture } - * - * - */ - public List getTexture() { - if (texture == null) { - texture = new ArrayList(); - } - return this.texture; - } + @XmlElement(required = true) + protected List texture; + + /** Gets the value of the texture property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the texture + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getTexture().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Texture } */ + public List getTexture () { + if (texture == null) { + texture = new ArrayList(); + } + return this.texture; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Track.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Track.java index 3fd1668080d..cc1d674bf7c 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Track.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Track.java @@ -11,127 +11,84 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "keyframes" -}) +@XmlType(name = "", propOrder = {"keyframes"}) @XmlRootElement(name = "track") public class Track { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String target; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String index; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String type; - @XmlElement(required = true) - protected Keyframes keyframes; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String target; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String index; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String type; + @XmlElement(required = true) + protected Keyframes keyframes; - /** - * Gets the value of the target property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTarget() { - return target; - } + /** Gets the value of the target property. + * + * @return possible object is {@link String } */ + public String getTarget () { + return target; + } - /** - * Sets the value of the target property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTarget(String value) { - this.target = value; - } + /** Sets the value of the target property. + * + * @param value allowed object is {@link String } */ + public void setTarget (String value) { + this.target = value; + } - /** - * Gets the value of the index property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getIndex() { - if (index == null) { - return "0"; - } else { - return index; - } - } + /** Gets the value of the index property. + * + * @return possible object is {@link String } */ + public String getIndex () { + if (index == null) { + return "0"; + } else { + return index; + } + } - /** - * Sets the value of the index property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setIndex(String value) { - this.index = value; - } + /** Sets the value of the index property. + * + * @param value allowed object is {@link String } */ + public void setIndex (String value) { + this.index = value; + } - /** - * Gets the value of the type property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getType() { - return type; - } + /** Gets the value of the type property. + * + * @return possible object is {@link String } */ + public String getType () { + return type; + } - /** - * Sets the value of the type property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setType(String value) { - this.type = value; - } + /** Sets the value of the type property. + * + * @param value allowed object is {@link String } */ + public void setType (String value) { + this.type = value; + } - /** - * Gets the value of the keyframes property. - * - * @return - * possible object is - * {@link Keyframes } - * - */ - public Keyframes getKeyframes() { - return keyframes; - } + /** Gets the value of the keyframes property. + * + * @return possible object is {@link Keyframes } */ + public Keyframes getKeyframes () { + return keyframes; + } - /** - * Sets the value of the keyframes property. - * - * @param value - * allowed object is - * {@link Keyframes } - * - */ - public void setKeyframes(Keyframes value) { - this.keyframes = value; - } + /** Sets the value of the keyframes property. + * + * @param value allowed object is {@link Keyframes } */ + public void setKeyframes (Keyframes value) { + this.keyframes = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tracks.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tracks.java index 94fd7597917..1b801e719db 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tracks.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Tracks.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "track" -}) +@XmlType(name = "", propOrder = {"track"}) @XmlRootElement(name = "tracks") public class Tracks { - @XmlElement(required = true) - protected List track; - - /** - * Gets the value of the track property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the track property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getTrack().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Track } - * - * - */ - public List getTrack() { - if (track == null) { - track = new ArrayList(); - } - return this.track; - } + @XmlElement(required = true) + protected List track; + + /** Gets the value of the track property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the track + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getTrack().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Track } */ + public List getTrack () { + if (track == null) { + track = new ArrayList(); + } + return this.track; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertex.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertex.java index 4938997e3e1..8885e535d9e 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertex.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertex.java @@ -10,205 +10,131 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "position", - "normal", - "tangent", - "binormal", - "colourDiffuse", - "colourSpecular", - "texcoord" -}) +@XmlType(name = "", propOrder = {"position", "normal", "tangent", "binormal", "colourDiffuse", "colourSpecular", "texcoord"}) @XmlRootElement(name = "vertex") public class Vertex { - @XmlElement(required = true) - protected Position position; - protected Normal normal; - protected Tangent tangent; - protected Binormal binormal; - @XmlElement(name = "colour_diffuse") - protected ColourDiffuse colourDiffuse; - @XmlElement(name = "colour_specular") - protected ColourSpecular colourSpecular; - protected List texcoord; - - /** - * Gets the value of the position property. - * - * @return - * possible object is - * {@link Position } - * - */ - public Position getPosition() { - return position; - } - - /** - * Sets the value of the position property. - * - * @param value - * allowed object is - * {@link Position } - * - */ - public void setPosition(Position value) { - this.position = value; - } - - /** - * Gets the value of the normal property. - * - * @return - * possible object is - * {@link Normal } - * - */ - public Normal getNormal() { - return normal; - } - - /** - * Sets the value of the normal property. - * - * @param value - * allowed object is - * {@link Normal } - * - */ - public void setNormal(Normal value) { - this.normal = value; - } - - /** - * Gets the value of the tangent property. - * - * @return - * possible object is - * {@link Tangent } - * - */ - public Tangent getTangent() { - return tangent; - } - - /** - * Sets the value of the tangent property. - * - * @param value - * allowed object is - * {@link Tangent } - * - */ - public void setTangent(Tangent value) { - this.tangent = value; - } - - /** - * Gets the value of the binormal property. - * - * @return - * possible object is - * {@link Binormal } - * - */ - public Binormal getBinormal() { - return binormal; - } - - /** - * Sets the value of the binormal property. - * - * @param value - * allowed object is - * {@link Binormal } - * - */ - public void setBinormal(Binormal value) { - this.binormal = value; - } - - /** - * Gets the value of the colourDiffuse property. - * - * @return - * possible object is - * {@link ColourDiffuse } - * - */ - public ColourDiffuse getColourDiffuse() { - return colourDiffuse; - } - - /** - * Sets the value of the colourDiffuse property. - * - * @param value - * allowed object is - * {@link ColourDiffuse } - * - */ - public void setColourDiffuse(ColourDiffuse value) { - this.colourDiffuse = value; - } - - /** - * Gets the value of the colourSpecular property. - * - * @return - * possible object is - * {@link ColourSpecular } - * - */ - public ColourSpecular getColourSpecular() { - return colourSpecular; - } - - /** - * Sets the value of the colourSpecular property. - * - * @param value - * allowed object is - * {@link ColourSpecular } - * - */ - public void setColourSpecular(ColourSpecular value) { - this.colourSpecular = value; - } - - /** - * Gets the value of the texcoord property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the texcoord property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getTexcoord().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Texcoord } - * - * - */ - public List getTexcoord() { - if (texcoord == null) { - texcoord = new ArrayList(); - } - return this.texcoord; - } + @XmlElement(required = true) + protected Position position; + protected Normal normal; + protected Tangent tangent; + protected Binormal binormal; + @XmlElement(name = "colour_diffuse") + protected ColourDiffuse colourDiffuse; + @XmlElement(name = "colour_specular") + protected ColourSpecular colourSpecular; + protected List texcoord; + + /** Gets the value of the position property. + * + * @return possible object is {@link Position } */ + public Position getPosition () { + return position; + } + + /** Sets the value of the position property. + * + * @param value allowed object is {@link Position } */ + public void setPosition (Position value) { + this.position = value; + } + + /** Gets the value of the normal property. + * + * @return possible object is {@link Normal } */ + public Normal getNormal () { + return normal; + } + + /** Sets the value of the normal property. + * + * @param value allowed object is {@link Normal } */ + public void setNormal (Normal value) { + this.normal = value; + } + + /** Gets the value of the tangent property. + * + * @return possible object is {@link Tangent } */ + public Tangent getTangent () { + return tangent; + } + + /** Sets the value of the tangent property. + * + * @param value allowed object is {@link Tangent } */ + public void setTangent (Tangent value) { + this.tangent = value; + } + + /** Gets the value of the binormal property. + * + * @return possible object is {@link Binormal } */ + public Binormal getBinormal () { + return binormal; + } + + /** Sets the value of the binormal property. + * + * @param value allowed object is {@link Binormal } */ + public void setBinormal (Binormal value) { + this.binormal = value; + } + + /** Gets the value of the colourDiffuse property. + * + * @return possible object is {@link ColourDiffuse } */ + public ColourDiffuse getColourDiffuse () { + return colourDiffuse; + } + + /** Sets the value of the colourDiffuse property. + * + * @param value allowed object is {@link ColourDiffuse } */ + public void setColourDiffuse (ColourDiffuse value) { + this.colourDiffuse = value; + } + + /** Gets the value of the colourSpecular property. + * + * @return possible object is {@link ColourSpecular } */ + public ColourSpecular getColourSpecular () { + return colourSpecular; + } + + /** Sets the value of the colourSpecular property. + * + * @param value allowed object is {@link ColourSpecular } */ + public void setColourSpecular (ColourSpecular value) { + this.colourSpecular = value; + } + + /** Gets the value of the texcoord property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the texcoord + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getTexcoord().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Texcoord } */ + public List getTexcoord () { + if (texcoord == null) { + texcoord = new ArrayList(); + } + return this.texcoord; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexboneassignment.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexboneassignment.java index 091212cb366..e3b4fd470c2 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexboneassignment.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexboneassignment.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "vertexboneassignment") public class Vertexboneassignment { - @XmlAttribute(required = true) - public int vertexindex; - @XmlAttribute(required = true) - public int boneindex; - @XmlAttribute - public float weight; + @XmlAttribute(required = true) + public int vertexindex; + @XmlAttribute(required = true) + public int boneindex; + @XmlAttribute + public float weight; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexbuffer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexbuffer.java index 1c23ea246ee..f5d3ca3cd5e 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexbuffer.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/mesh/Vertexbuffer.java @@ -13,289 +13,206 @@ import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vertex" -}) +@XmlType(name = "", propOrder = {"vertex"}) @XmlRootElement(name = "vertexbuffer") public class Vertexbuffer { - @XmlAttribute - public boolean positions; - @XmlAttribute - public boolean normals; - @XmlAttribute(name = "colours_diffuse") - public boolean coloursDiffuse; - @XmlAttribute(name = "colours_specular") - public boolean coloursSpecular; - @XmlAttribute(name = "texture_coords") - public int textureCoords; - @XmlAttribute(name = "texture_coord_dimensions_0") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions0; - @XmlAttribute(name = "texture_coord_dimensions_1") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions1; - @XmlAttribute(name = "texture_coord_dimensions_2") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions2; - @XmlAttribute(name = "texture_coord_dimensions_3") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions3; - @XmlAttribute(name = "texture_coord_dimensions_4") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions4; - @XmlAttribute(name = "texture_coord_dimensions_5") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions5; - @XmlAttribute(name = "texture_coord_dimensions_6") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions6; - @XmlAttribute(name = "texture_coord_dimensions_7") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String textureCoordDimensions7; - @XmlAttribute - public boolean tangents; - @XmlAttribute(name = "tangent_dimensions") - public int tangentDimensions; - @XmlAttribute - public boolean binormals; - @XmlElement(required = true) - protected List vertex; - - /** - * Gets the value of the textureCoordDimensions0 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions0() { - if (textureCoordDimensions0 == null) { - return "2"; - } else { - return textureCoordDimensions0; - } - } - - /** - * Sets the value of the textureCoordDimensions0 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions0(String value) { - this.textureCoordDimensions0 = value; - } - - /** - * Gets the value of the textureCoordDimensions1 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions1() { - if (textureCoordDimensions1 == null) { - return "2"; - } else { - return textureCoordDimensions1; - } - } - - /** - * Sets the value of the textureCoordDimensions1 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions1(String value) { - this.textureCoordDimensions1 = value; - } - - /** - * Gets the value of the textureCoordDimensions2 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions2() { - if (textureCoordDimensions2 == null) { - return "2"; - } else { - return textureCoordDimensions2; - } - } - - /** - * Sets the value of the textureCoordDimensions2 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions2(String value) { - this.textureCoordDimensions2 = value; - } - - /** - * Gets the value of the textureCoordDimensions3 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions3() { - if (textureCoordDimensions3 == null) { - return "2"; - } else { - return textureCoordDimensions3; - } - } - - /** - * Sets the value of the textureCoordDimensions3 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions3(String value) { - this.textureCoordDimensions3 = value; - } - - /** - * Gets the value of the textureCoordDimensions4 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions4() { - if (textureCoordDimensions4 == null) { - return "2"; - } else { - return textureCoordDimensions4; - } - } - - /** - * Sets the value of the textureCoordDimensions4 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions4(String value) { - this.textureCoordDimensions4 = value; - } - - /** - * Gets the value of the textureCoordDimensions5 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions5() { - if (textureCoordDimensions5 == null) { - return "2"; - } else { - return textureCoordDimensions5; - } - } - - /** - * Sets the value of the textureCoordDimensions5 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions5(String value) { - this.textureCoordDimensions5 = value; - } - - /** - * Gets the value of the textureCoordDimensions6 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions6() { - if (textureCoordDimensions6 == null) { - return "2"; - } else { - return textureCoordDimensions6; - } - } - - /** - * Sets the value of the textureCoordDimensions6 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions6(String value) { - this.textureCoordDimensions6 = value; - } - - /** - * Gets the value of the textureCoordDimensions7 property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTextureCoordDimensions7() { - if (textureCoordDimensions7 == null) { - return "2"; - } else { - return textureCoordDimensions7; - } - } - - /** - * Sets the value of the textureCoordDimensions7 property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTextureCoordDimensions7(String value) { - this.textureCoordDimensions7 = value; - } - - public List getVertex() { - if (vertex == null) { - vertex = new ArrayList(); - } - return this.vertex; - } + @XmlAttribute + public boolean positions; + @XmlAttribute + public boolean normals; + @XmlAttribute(name = "colours_diffuse") + public boolean coloursDiffuse; + @XmlAttribute(name = "colours_specular") + public boolean coloursSpecular; + @XmlAttribute(name = "texture_coords") + public int textureCoords; + @XmlAttribute(name = "texture_coord_dimensions_0") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions0; + @XmlAttribute(name = "texture_coord_dimensions_1") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions1; + @XmlAttribute(name = "texture_coord_dimensions_2") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions2; + @XmlAttribute(name = "texture_coord_dimensions_3") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions3; + @XmlAttribute(name = "texture_coord_dimensions_4") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions4; + @XmlAttribute(name = "texture_coord_dimensions_5") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions5; + @XmlAttribute(name = "texture_coord_dimensions_6") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions6; + @XmlAttribute(name = "texture_coord_dimensions_7") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + protected String textureCoordDimensions7; + @XmlAttribute + public boolean tangents; + @XmlAttribute(name = "tangent_dimensions") + public int tangentDimensions; + @XmlAttribute + public boolean binormals; + @XmlElement(required = true) + protected List vertex; + + /** Gets the value of the textureCoordDimensions0 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions0 () { + if (textureCoordDimensions0 == null) { + return "2"; + } else { + return textureCoordDimensions0; + } + } + + /** Sets the value of the textureCoordDimensions0 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions0 (String value) { + this.textureCoordDimensions0 = value; + } + + /** Gets the value of the textureCoordDimensions1 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions1 () { + if (textureCoordDimensions1 == null) { + return "2"; + } else { + return textureCoordDimensions1; + } + } + + /** Sets the value of the textureCoordDimensions1 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions1 (String value) { + this.textureCoordDimensions1 = value; + } + + /** Gets the value of the textureCoordDimensions2 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions2 () { + if (textureCoordDimensions2 == null) { + return "2"; + } else { + return textureCoordDimensions2; + } + } + + /** Sets the value of the textureCoordDimensions2 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions2 (String value) { + this.textureCoordDimensions2 = value; + } + + /** Gets the value of the textureCoordDimensions3 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions3 () { + if (textureCoordDimensions3 == null) { + return "2"; + } else { + return textureCoordDimensions3; + } + } + + /** Sets the value of the textureCoordDimensions3 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions3 (String value) { + this.textureCoordDimensions3 = value; + } + + /** Gets the value of the textureCoordDimensions4 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions4 () { + if (textureCoordDimensions4 == null) { + return "2"; + } else { + return textureCoordDimensions4; + } + } + + /** Sets the value of the textureCoordDimensions4 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions4 (String value) { + this.textureCoordDimensions4 = value; + } + + /** Gets the value of the textureCoordDimensions5 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions5 () { + if (textureCoordDimensions5 == null) { + return "2"; + } else { + return textureCoordDimensions5; + } + } + + /** Sets the value of the textureCoordDimensions5 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions5 (String value) { + this.textureCoordDimensions5 = value; + } + + /** Gets the value of the textureCoordDimensions6 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions6 () { + if (textureCoordDimensions6 == null) { + return "2"; + } else { + return textureCoordDimensions6; + } + } + + /** Sets the value of the textureCoordDimensions6 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions6 (String value) { + this.textureCoordDimensions6 = value; + } + + /** Gets the value of the textureCoordDimensions7 property. + * + * @return possible object is {@link String } */ + public String getTextureCoordDimensions7 () { + if (textureCoordDimensions7 == null) { + return "2"; + } else { + return textureCoordDimensions7; + } + } + + /** Sets the value of the textureCoordDimensions7 property. + * + * @param value allowed object is {@link String } */ + public void setTextureCoordDimensions7 (String value) { + this.textureCoordDimensions7 = value; + } + + public List getVertex () { + if (vertex == null) { + vertex = new ArrayList(); + } + return this.vertex; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animation.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animation.java index 8c1bd0ee9d4..f0de2c08afa 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animation.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animation.java @@ -10,47 +10,34 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "tracks" -}) +@XmlType(name = "", propOrder = {"tracks"}) @XmlRootElement(name = "animation") public class Animation { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - public String name; - @XmlAttribute(required = true) - public float length; - @XmlElement(required = true) - protected Tracks tracks; - - /** - * Gets the value of the tracks property. - * - * @return - * possible object is - * {@link Tracks } - * - */ - public Tracks getTracks() { - return tracks; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + public String name; + @XmlAttribute(required = true) + public float length; + @XmlElement(required = true) + protected Tracks tracks; + + /** Gets the value of the tracks property. + * + * @return possible object is {@link Tracks } */ + public Tracks getTracks () { + return tracks; + } - /** - * Sets the value of the tracks property. - * - * @param value - * allowed object is - * {@link Tracks } - * - */ - public void setTracks(Tracks value) { - this.tracks = value; - } + /** Sets the value of the tracks property. + * + * @param value allowed object is {@link Tracks } */ + public void setTracks (Tracks value) { + this.tracks = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlink.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlink.java index cba26eff31f..f757356ab39 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlink.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlink.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,63 +17,43 @@ @XmlRootElement(name = "animationlink") public class Animationlink { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String skeletonName; - @XmlAttribute - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String scale; - - /** - * Gets the value of the skeletonName property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSkeletonName() { - return skeletonName; - } - - /** - * Sets the value of the skeletonName property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSkeletonName(String value) { - this.skeletonName = value; - } - - /** - * Gets the value of the scale property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getScale() { - if (scale == null) { - return "1.0"; - } else { - return scale; - } - } - - /** - * Sets the value of the scale property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setScale(String value) { - this.scale = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String skeletonName; + @XmlAttribute + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String scale; + + /** Gets the value of the skeletonName property. + * + * @return possible object is {@link String } */ + public String getSkeletonName () { + return skeletonName; + } + + /** Sets the value of the skeletonName property. + * + * @param value allowed object is {@link String } */ + public void setSkeletonName (String value) { + this.skeletonName = value; + } + + /** Gets the value of the scale property. + * + * @return possible object is {@link String } */ + public String getScale () { + if (scale == null) { + return "1.0"; + } else { + return scale; + } + } + + /** Sets the value of the scale property. + * + * @param value allowed object is {@link String } */ + public void setScale (String value) { + this.scale = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlinks.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlinks.java index 33f5f11422f..1afc98d09ae 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlinks.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animationlinks.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "animationlink" -}) +@XmlType(name = "", propOrder = {"animationlink"}) @XmlRootElement(name = "animationlinks") public class Animationlinks { - @XmlElement(required = true) - protected List animationlink; - - /** - * Gets the value of the animationlink property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the animationlink property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getAnimationlink().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Animationlink } - * - * - */ - public List getAnimationlink() { - if (animationlink == null) { - animationlink = new ArrayList(); - } - return this.animationlink; - } + @XmlElement(required = true) + protected List animationlink; + + /** Gets the value of the animationlink property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the + * animationlink property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getAnimationlink().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Animationlink } */ + public List getAnimationlink () { + if (animationlink == null) { + animationlink = new ArrayList(); + } + return this.animationlink; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animations.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animations.java index 3cc6bd600e5..e3038066c1d 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animations.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Animations.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "animation" -}) +@XmlType(name = "", propOrder = {"animation"}) @XmlRootElement(name = "animations") public class Animations { - @XmlElement(required = true) - protected List animation; - - /** - * Gets the value of the animation property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the animation property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getAnimation().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Animation } - * - * - */ - public List getAnimation() { - if (animation == null) { - animation = new ArrayList(); - } - return this.animation; - } + @XmlElement(required = true) + protected List animation; + + /** Gets the value of the animation property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the animation + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getAnimation().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Animation } */ + public List getAnimation () { + if (animation == null) { + animation = new ArrayList(); + } + return this.animation; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Axis.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Axis.java index 92f0956c18d..ad896d4196f 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Axis.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Axis.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "axis") public class Axis { - @XmlAttribute(required = true) - public float x; - @XmlAttribute(required = true) - public float y; - @XmlAttribute(required = true) - public float z; + @XmlAttribute(required = true) + public float x; + @XmlAttribute(required = true) + public float y; + @XmlAttribute(required = true) + public float z; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bone.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bone.java index 0fa505ddf44..71d3995b4e5 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bone.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bone.java @@ -10,28 +10,23 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "position", - "rotation", - "scale" -}) +@XmlType(name = "", propOrder = {"position", "rotation", "scale"}) @XmlRootElement(name = "bone") public class Bone { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - public String id; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - public String name; - @XmlElement(required = true) - public Position position; - @XmlElement(required = true) - public Rotation rotation; - public Scale scale; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + public String id; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + public String name; + @XmlElement(required = true) + public Position position; + @XmlElement(required = true) + public Rotation rotation; + public Scale scale; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bonehierarchy.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bonehierarchy.java index 49b69f74679..b9a8995c0bc 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bonehierarchy.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bonehierarchy.java @@ -9,46 +9,38 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "boneparent" -}) +@XmlType(name = "", propOrder = {"boneparent"}) @XmlRootElement(name = "bonehierarchy") public class Bonehierarchy { - protected List boneparent; - - /** - * Gets the value of the boneparent property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the boneparent property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getBoneparent().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Boneparent } - * - * - */ - public List getBoneparent() { - if (boneparent == null) { - boneparent = new ArrayList(); - } - return this.boneparent; - } + protected List boneparent; + + /** Gets the value of the boneparent property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the boneparent + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getBoneparent().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Boneparent } */ + public List getBoneparent () { + if (boneparent == null) { + boneparent = new ArrayList(); + } + return this.boneparent; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Boneparent.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Boneparent.java index 47d2330bca4..7f261c3ca98 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Boneparent.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Boneparent.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @@ -18,59 +17,39 @@ @XmlRootElement(name = "boneparent") public class Boneparent { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String bone; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String parent; - - /** - * Gets the value of the bone property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBone() { - return bone; - } - - /** - * Sets the value of the bone property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBone(String value) { - this.bone = value; - } - - /** - * Gets the value of the parent property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getParent() { - return parent; - } - - /** - * Sets the value of the parent property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setParent(String value) { - this.parent = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String bone; + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String parent; + + /** Gets the value of the bone property. + * + * @return possible object is {@link String } */ + public String getBone () { + return bone; + } + + /** Sets the value of the bone property. + * + * @param value allowed object is {@link String } */ + public void setBone (String value) { + this.bone = value; + } + + /** Gets the value of the parent property. + * + * @return possible object is {@link String } */ + public String getParent () { + return parent; + } + + /** Sets the value of the parent property. + * + * @param value allowed object is {@link String } */ + public void setParent (String value) { + this.parent = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bones.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bones.java index 9e630ca69cb..719a3ee75dc 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bones.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Bones.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "bone" -}) +@XmlType(name = "", propOrder = {"bone"}) @XmlRootElement(name = "bones") public class Bones { - @XmlElement(required = true) - protected List bone; - - /** - * Gets the value of the bone property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the bone property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getBone().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Bone } - * - * - */ - public List getBone() { - if (bone == null) { - bone = new ArrayList(); - } - return this.bone; - } + @XmlElement(required = true) + protected List bone; + + /** Gets the value of the bone property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the bone + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getBone().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Bone } */ + public List getBone () { + if (bone == null) { + bone = new ArrayList(); + } + return this.bone; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframe.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframe.java index c9dd9ea6797..bd649125ed4 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframe.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframe.java @@ -7,22 +7,17 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "translate", - "rotate", - "scale" -}) +@XmlType(name = "", propOrder = {"translate", "rotate", "scale"}) @XmlRootElement(name = "keyframe") public class Keyframe { - @XmlAttribute(required = true) - public float time; - public Translate translate; - public Rotate rotate; - public Scale scale; + @XmlAttribute(required = true) + public float time; + public Translate translate; + public Rotate rotate; + public Scale scale; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframes.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframes.java index 24858042759..2904177f86e 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframes.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Keyframes.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "keyframe" -}) +@XmlType(name = "", propOrder = {"keyframe"}) @XmlRootElement(name = "keyframes") public class Keyframes { - @XmlElement(required = true) - protected List keyframe; - - /** - * Gets the value of the keyframe property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the keyframe property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getKeyframe().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Keyframe } - * - * - */ - public List getKeyframe() { - if (keyframe == null) { - keyframe = new ArrayList(); - } - return this.keyframe; - } + @XmlElement(required = true) + protected List keyframe; + + /** Gets the value of the keyframe property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the keyframe + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getKeyframe().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Keyframe } */ + public List getKeyframe () { + if (keyframe == null) { + keyframe = new ArrayList(); + } + return this.keyframe; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/ObjectFactory.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/ObjectFactory.java index 2cff7331b27..bed2b57ee18 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/ObjectFactory.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/ObjectFactory.java @@ -3,182 +3,113 @@ import javax.xml.bind.annotation.XmlRegistry; - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.badlogic.gdx.graphics.g3d.orgrexml.skeleton package. - *

        An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ +/** This object contains factory methods for each Java content interface and Java element interface generated in the + * com.badlogic.gdx.graphics.g3d.orgrexml.skeleton package. + *

        + * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. The Java + * representation of XML content can consist of schema derived interfaces and classes representing the binding of schema type + * definitions, element declarations and model groups. Factory methods for each of these are provided in this class. */ @XmlRegistry public class ObjectFactory { - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.badlogic.gdx.graphics.g3d.orgrexml.skeleton - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Position } - * - */ - public Position createPosition() { - return new Position(); - } - - /** - * Create an instance of {@link Animationlinks } - * - */ - public Animationlinks createAnimationlinks() { - return new Animationlinks(); - } - - /** - * Create an instance of {@link Boneparent } - * - */ - public Boneparent createBoneparent() { - return new Boneparent(); - } - - /** - * Create an instance of {@link Track } - * - */ - public Track createTrack() { - return new Track(); - } - - /** - * Create an instance of {@link Scale } - * - */ - public Scale createScale() { - return new Scale(); - } - - /** - * Create an instance of {@link Animationlink } - * - */ - public Animationlink createAnimationlink() { - return new Animationlink(); - } - - /** - * Create an instance of {@link Bonehierarchy } - * - */ - public Bonehierarchy createBonehierarchy() { - return new Bonehierarchy(); - } - - /** - * Create an instance of {@link Keyframe } - * - */ - public Keyframe createKeyframe() { - return new Keyframe(); - } - - /** - * Create an instance of {@link Axis } - * - */ - public Axis createAxis() { - return new Axis(); - } - - /** - * Create an instance of {@link Animations } - * - */ - public Animations createAnimations() { - return new Animations(); - } - - /** - * Create an instance of {@link Rotation } - * - */ - public Rotation createRotation() { - return new Rotation(); - } - - /** - * Create an instance of {@link Bone } - * - */ - public Bone createBone() { - return new Bone(); - } - - /** - * Create an instance of {@link Bones } - * - */ - public Bones createBones() { - return new Bones(); - } - - /** - * Create an instance of {@link Translate } - * - */ - public Translate createTranslate() { - return new Translate(); - } - - /** - * Create an instance of {@link Tracks } - * - */ - public Tracks createTracks() { - return new Tracks(); - } - - /** - * Create an instance of {@link Animation } - * - */ - public Animation createAnimation() { - return new Animation(); - } - - /** - * Create an instance of {@link Skeleton } - * - */ - public Skeleton createSkeleton() { - return new Skeleton(); - } - - /** - * Create an instance of {@link Keyframes } - * - */ - public Keyframes createKeyframes() { - return new Keyframes(); - } - - /** - * Create an instance of {@link Rotate } - * - */ - public Rotate createRotate() { - return new Rotate(); - } + /** Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: + * com.badlogic.gdx.graphics.g3d.orgrexml.skeleton */ + public ObjectFactory () { + } + + /** Create an instance of {@link Position } */ + public Position createPosition () { + return new Position(); + } + + /** Create an instance of {@link Animationlinks } */ + public Animationlinks createAnimationlinks () { + return new Animationlinks(); + } + + /** Create an instance of {@link Boneparent } */ + public Boneparent createBoneparent () { + return new Boneparent(); + } + + /** Create an instance of {@link Track } */ + public Track createTrack () { + return new Track(); + } + + /** Create an instance of {@link Scale } */ + public Scale createScale () { + return new Scale(); + } + + /** Create an instance of {@link Animationlink } */ + public Animationlink createAnimationlink () { + return new Animationlink(); + } + + /** Create an instance of {@link Bonehierarchy } */ + public Bonehierarchy createBonehierarchy () { + return new Bonehierarchy(); + } + + /** Create an instance of {@link Keyframe } */ + public Keyframe createKeyframe () { + return new Keyframe(); + } + + /** Create an instance of {@link Axis } */ + public Axis createAxis () { + return new Axis(); + } + + /** Create an instance of {@link Animations } */ + public Animations createAnimations () { + return new Animations(); + } + + /** Create an instance of {@link Rotation } */ + public Rotation createRotation () { + return new Rotation(); + } + + /** Create an instance of {@link Bone } */ + public Bone createBone () { + return new Bone(); + } + + /** Create an instance of {@link Bones } */ + public Bones createBones () { + return new Bones(); + } + + /** Create an instance of {@link Translate } */ + public Translate createTranslate () { + return new Translate(); + } + + /** Create an instance of {@link Tracks } */ + public Tracks createTracks () { + return new Tracks(); + } + + /** Create an instance of {@link Animation } */ + public Animation createAnimation () { + return new Animation(); + } + + /** Create an instance of {@link Skeleton } */ + public Skeleton createSkeleton () { + return new Skeleton(); + } + + /** Create an instance of {@link Keyframes } */ + public Keyframes createKeyframes () { + return new Keyframes(); + } + + /** Create an instance of {@link Rotate } */ + public Rotate createRotate () { + return new Rotate(); + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Position.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Position.java index 455d4e0bee4..dddc626963c 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Position.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Position.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "position") public class Position { - @XmlAttribute(required = true) - public float x; - @XmlAttribute(required = true) - public float y; - @XmlAttribute(required = true) - public float z; + @XmlAttribute(required = true) + public float x; + @XmlAttribute(required = true) + public float y; + @XmlAttribute(required = true) + public float z; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotate.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotate.java index 9d3617686dd..c6f1977722e 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotate.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotate.java @@ -8,19 +8,16 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "axis" -}) +@XmlType(name = "", propOrder = {"axis"}) @XmlRootElement(name = "rotate") public class Rotate { - @XmlAttribute(required = true) - public float angle; - @XmlElement(required = true) - public Axis axis; + @XmlAttribute(required = true) + public float angle; + @XmlElement(required = true) + public Axis axis; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotation.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotation.java index ef7c7747a49..cdeeda821dc 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotation.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Rotation.java @@ -8,19 +8,16 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "axis" -}) +@XmlType(name = "", propOrder = {"axis"}) @XmlRootElement(name = "rotation") public class Rotation { - @XmlAttribute(required = true) - public float angle; - @XmlElement(required = true) - public Axis axis; + @XmlAttribute(required = true) + public float angle; + @XmlElement(required = true) + public Axis axis; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Scale.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Scale.java index ad3709dc3b4..31309119c03 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Scale.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Scale.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,12 +15,12 @@ @XmlRootElement(name = "scale") public class Scale { - @XmlAttribute - public float factor; - @XmlAttribute - public float x; - @XmlAttribute - public float y; - @XmlAttribute - public float z; + @XmlAttribute + public float factor; + @XmlAttribute + public float x; + @XmlAttribute + public float y; + @XmlAttribute + public float z; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Skeleton.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Skeleton.java index 8dcdbddb2bb..68debeb3a88 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Skeleton.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Skeleton.java @@ -7,121 +7,75 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "bones", - "bonehierarchy", - "animations", - "animationlinks" -}) +@XmlType(name = "", propOrder = {"bones", "bonehierarchy", "animations", "animationlinks"}) @XmlRootElement(name = "skeleton") public class Skeleton { - @XmlElement(required = true) - protected Bones bones; - @XmlElement(required = true) - protected Bonehierarchy bonehierarchy; - protected Animations animations; - protected Animationlinks animationlinks; + @XmlElement(required = true) + protected Bones bones; + @XmlElement(required = true) + protected Bonehierarchy bonehierarchy; + protected Animations animations; + protected Animationlinks animationlinks; - /** - * Gets the value of the bones property. - * - * @return - * possible object is - * {@link Bones } - * - */ - public Bones getBones() { - return bones; - } + /** Gets the value of the bones property. + * + * @return possible object is {@link Bones } */ + public Bones getBones () { + return bones; + } - /** - * Sets the value of the bones property. - * - * @param value - * allowed object is - * {@link Bones } - * - */ - public void setBones(Bones value) { - this.bones = value; - } + /** Sets the value of the bones property. + * + * @param value allowed object is {@link Bones } */ + public void setBones (Bones value) { + this.bones = value; + } - /** - * Gets the value of the bonehierarchy property. - * - * @return - * possible object is - * {@link Bonehierarchy } - * - */ - public Bonehierarchy getBonehierarchy() { - return bonehierarchy; - } + /** Gets the value of the bonehierarchy property. + * + * @return possible object is {@link Bonehierarchy } */ + public Bonehierarchy getBonehierarchy () { + return bonehierarchy; + } - /** - * Sets the value of the bonehierarchy property. - * - * @param value - * allowed object is - * {@link Bonehierarchy } - * - */ - public void setBonehierarchy(Bonehierarchy value) { - this.bonehierarchy = value; - } + /** Sets the value of the bonehierarchy property. + * + * @param value allowed object is {@link Bonehierarchy } */ + public void setBonehierarchy (Bonehierarchy value) { + this.bonehierarchy = value; + } - /** - * Gets the value of the animations property. - * - * @return - * possible object is - * {@link Animations } - * - */ - public Animations getAnimations() { - return animations; - } + /** Gets the value of the animations property. + * + * @return possible object is {@link Animations } */ + public Animations getAnimations () { + return animations; + } - /** - * Sets the value of the animations property. - * - * @param value - * allowed object is - * {@link Animations } - * - */ - public void setAnimations(Animations value) { - this.animations = value; - } + /** Sets the value of the animations property. + * + * @param value allowed object is {@link Animations } */ + public void setAnimations (Animations value) { + this.animations = value; + } - /** - * Gets the value of the animationlinks property. - * - * @return - * possible object is - * {@link Animationlinks } - * - */ - public Animationlinks getAnimationlinks() { - return animationlinks; - } + /** Gets the value of the animationlinks property. + * + * @return possible object is {@link Animationlinks } */ + public Animationlinks getAnimationlinks () { + return animationlinks; + } - /** - * Sets the value of the animationlinks property. - * - * @param value - * allowed object is - * {@link Animationlinks } - * - */ - public void setAnimationlinks(Animationlinks value) { - this.animationlinks = value; - } + /** Sets the value of the animationlinks property. + * + * @param value allowed object is {@link Animationlinks } */ + public void setAnimationlinks (Animationlinks value) { + this.animationlinks = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Track.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Track.java index fd0d2a1b5e1..af9339f473d 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Track.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Track.java @@ -10,69 +10,46 @@ import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "keyframes" -}) +@XmlType(name = "", propOrder = {"keyframes"}) @XmlRootElement(name = "track") public class Track { - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - protected String bone; - @XmlElement(required = true) - protected Keyframes keyframes; - - /** - * Gets the value of the bone property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBone() { - return bone; - } - - /** - * Sets the value of the bone property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBone(String value) { - this.bone = value; - } - - /** - * Gets the value of the keyframes property. - * - * @return - * possible object is - * {@link Keyframes } - * - */ - public Keyframes getKeyframes() { - return keyframes; - } - - /** - * Sets the value of the keyframes property. - * - * @param value - * allowed object is - * {@link Keyframes } - * - */ - public void setKeyframes(Keyframes value) { - this.keyframes = value; - } + @XmlAttribute(required = true) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + protected String bone; + @XmlElement(required = true) + protected Keyframes keyframes; + + /** Gets the value of the bone property. + * + * @return possible object is {@link String } */ + public String getBone () { + return bone; + } + + /** Sets the value of the bone property. + * + * @param value allowed object is {@link String } */ + public void setBone (String value) { + this.bone = value; + } + + /** Gets the value of the keyframes property. + * + * @return possible object is {@link Keyframes } */ + public Keyframes getKeyframes () { + return keyframes; + } + + /** Sets the value of the keyframes property. + * + * @param value allowed object is {@link Keyframes } */ + public void setKeyframes (Keyframes value) { + this.keyframes = value; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Tracks.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Tracks.java index 51ab36c9acb..f2a075cecb3 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Tracks.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Tracks.java @@ -10,47 +10,39 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "track" -}) +@XmlType(name = "", propOrder = {"track"}) @XmlRootElement(name = "tracks") public class Tracks { - @XmlElement(required = true) - protected List track; - - /** - * Gets the value of the track property. - * - *

        - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the track property. - * - *

        - * For example, to add a new item, do as follows: - *

        -     *    getTrack().add(newItem);
        -     * 
        - * - * - *

        - * Objects of the following type(s) are allowed in the list - * {@link Track } - * - * - */ - public List getTrack() { - if (track == null) { - track = new ArrayList(); - } - return this.track; - } + @XmlElement(required = true) + protected List track; + + /** Gets the value of the track property. + * + *

        + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. This is why there is not a set method for the track + * property. + * + *

        + * For example, to add a new item, do as follows: + * + *

        +	 * getTrack().add(newItem);
        +	 * 
        + * + * + *

        + * Objects of the following type(s) are allowed in the list {@link Track } */ + public List getTrack () { + if (track == null) { + track = new ArrayList(); + } + return this.track; + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Translate.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Translate.java index d5359dcc1ca..06b6be8a2da 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Translate.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/ogre/skeleton/Translate.java @@ -7,7 +7,6 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; - /** * */ @@ -16,10 +15,10 @@ @XmlRootElement(name = "translate") public class Translate { - @XmlAttribute(required = true) - public float x; - @XmlAttribute(required = true) - public float y; - @XmlAttribute(required = true) - public float z; + @XmlAttribute(required = true) + public float x; + @XmlAttribute(required = true) + public float y; + @XmlAttribute(required = true) + public float z; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/wavefront/ObjLoader.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/wavefront/ObjLoader.java index 432c5b7136a..8284d84fcc8 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/wavefront/ObjLoader.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/loaders/wavefront/ObjLoader.java @@ -34,47 +34,34 @@ import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.FloatArray; -/** - * Loads Wavefront OBJ files. +/** Loads Wavefront OBJ files. * - * @author mzechner, espitz - * - */ + * @author mzechner, espitz */ public class ObjLoader implements StillModelLoader { final FloatArray verts; final FloatArray norms; final FloatArray uvs; final ArrayList groups; - public ObjLoader() { + public ObjLoader () { verts = new FloatArray(300); norms = new FloatArray(300); uvs = new FloatArray(200); groups = new ArrayList(10); } - /** - * Loads a Wavefront OBJ file from a given file handle. - * - * @param file - * the FileHandle + /** Loads a Wavefront OBJ file from a given file handle. * - */ - public StillModel loadObj(FileHandle file) { + * @param file the FileHandle */ + public StillModel loadObj (FileHandle file) { return loadObj(file, false); } - /** - * Loads a Wavefront OBJ file from a given file handle. + /** Loads a Wavefront OBJ file from a given file handle. * - * @param file - * the FileHandle - * @param flipV - * whether to flip the v texture coordinate (Blender, Wings3D, et - * al) - * - */ - public StillModel loadObj(FileHandle file, boolean flipV) { + * @param file the FileHandle + * @param flipV whether to flip the v texture coordinate (Blender, Wings3D, et al) */ + public StillModel loadObj (FileHandle file, boolean flipV) { String line; String[] tokens; char firstChar; @@ -84,8 +71,7 @@ public StillModel loadObj(FileHandle file, boolean flipV) { Group activeGroup = new Group("default"); groups.add(activeGroup); - BufferedReader reader = new BufferedReader(new InputStreamReader( - file.read()), 4096); + BufferedReader reader = new BufferedReader(new InputStreamReader(file.read()), 4096); try { while ((line = reader.readLine()) != null) { @@ -106,8 +92,7 @@ public StillModel loadObj(FileHandle file, boolean flipV) { norms.add(Float.parseFloat(tokens[3])); } else if (tokens[0].charAt(1) == 't') { uvs.add(Float.parseFloat(tokens[1])); - uvs.add((flipV ? 1 - Float.parseFloat(tokens[2]) - : Float.parseFloat(tokens[2]))); + uvs.add((flipV ? 1 - Float.parseFloat(tokens[2]) : Float.parseFloat(tokens[2]))); } } else if (firstChar == 'f') { String[] parts; @@ -116,27 +101,21 @@ public StillModel loadObj(FileHandle file, boolean flipV) { parts = tokens[1].split("/"); faces.add(getIndex(parts[0], verts.size)); if (parts.length > 2) { - if (i == 1) - activeGroup.hasNorms = true; + if (i == 1) activeGroup.hasNorms = true; faces.add(getIndex(parts[2], norms.size)); } if (parts.length > 1 && parts[1].length() > 0) { - if (i == 1) - activeGroup.hasUVs = true; + if (i == 1) activeGroup.hasUVs = true; faces.add(getIndex(parts[1], uvs.size)); } parts = tokens[++i].split("/"); faces.add(getIndex(parts[0], verts.size)); - if (parts.length > 2) - faces.add(getIndex(parts[2], norms.size)); - if (parts.length > 1 && parts[1].length() > 0) - faces.add(getIndex(parts[1], uvs.size)); + if (parts.length > 2) faces.add(getIndex(parts[2], norms.size)); + if (parts.length > 1 && parts[1].length() > 0) faces.add(getIndex(parts[1], uvs.size)); parts = tokens[++i].split("/"); faces.add(getIndex(parts[0], verts.size)); - if (parts.length > 2) - faces.add(getIndex(parts[2], norms.size)); - if (parts.length > 1 && parts[1].length() > 0) - faces.add(getIndex(parts[1], uvs.size)); + if (parts.length > 2) faces.add(getIndex(parts[2], norms.size)); + if (parts.length > 1 && parts[1].length() > 0) faces.add(getIndex(parts[1], uvs.size)); activeGroup.numFaces++; } } else if (firstChar == 'o' || firstChar == 'g') { @@ -164,8 +143,7 @@ public StillModel loadObj(FileHandle file, boolean flipV) { } // If there are no groups left, there is no valid Model to return - if (groups.size() < 1) - return null; + if (groups.size() < 1) return null; // Get number of objects/groups remaining after removing empty ones final int numGroups = groups.size(); @@ -180,8 +158,7 @@ public StillModel loadObj(FileHandle file, boolean flipV) { boolean hasNorms = group.hasNorms; boolean hasUVs = group.hasUVs; - float[] finalVerts = new float[(numFaces * 3) - * (3 + (hasNorms ? 3 : 0) + (hasUVs ? 2 : 0))]; + float[] finalVerts = new float[(numFaces * 3) * (3 + (hasNorms ? 3 : 0) + (hasUVs ? 2 : 0))]; for (int i = 0, vi = 0; i < numElements;) { int vertIndex = faces.get(i++) * 3; @@ -204,21 +181,14 @@ public StillModel loadObj(FileHandle file, boolean flipV) { final Mesh mesh; ArrayList attributes = new ArrayList(); - attributes - .add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); - if (hasNorms) - attributes - .add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); - if (hasUVs) - attributes.add(new VertexAttribute(Usage.TextureCoordinates, 2, - ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); + attributes.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); + if (hasNorms) attributes.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); + if (hasUVs) attributes.add(new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); - mesh = new Mesh(true, numFaces * 3, 0, - attributes.toArray(new VertexAttribute[attributes.size()])); + mesh = new Mesh(true, numFaces * 3, 0, attributes.toArray(new VertexAttribute[attributes.size()])); mesh.setVertices(finalVerts); - StillSubMesh subMesh = new StillSubMesh(group.name, mesh, - GL10.GL_TRIANGLES); + StillSubMesh subMesh = new StillSubMesh(group.name, mesh, GL10.GL_TRIANGLES); subMesh.material = new Material("default"); model.subMeshes[g] = subMesh; @@ -228,33 +198,27 @@ public StillModel loadObj(FileHandle file, boolean flipV) { // Clearing the ArrayList cache instead of instantiating new // ArrayLists should result in slightly faster load times for // subsequent calls to loadObj - if (verts.size > 0) - verts.clear(); - if (norms.size > 0) - norms.clear(); - if (uvs.size > 0) - uvs.clear(); - if (groups.size() > 0) - groups.clear(); + if (verts.size > 0) verts.clear(); + if (norms.size > 0) norms.clear(); + if (uvs.size > 0) uvs.clear(); + if (groups.size() > 0) groups.clear(); return model; } - private Group setActiveGroup(String name) { + private Group setActiveGroup (String name) { // TODO: Check if a HashMap.get calls are faster than iterating // through an ArrayList for (Group group : groups) { - if (group.name.equals(name)) - return group; + if (group.name.equals(name)) return group; } Group group = new Group(name); groups.add(group); return group; } - private int getIndex(String index, int size) { - if (index == null || index.length() == 0) - return 0; + private int getIndex (String index, int size) { + if (index == null || index.length() == 0) return 0; final int idx = Integer.parseInt(index); if (idx < 0) return size + idx; @@ -270,7 +234,7 @@ private class Group { boolean hasUVs; Material mat; - Group(String name) { + Group (String name) { this.name = name; this.faces = new ArrayList(200); this.numFaces = 0; @@ -278,7 +242,8 @@ private class Group { } } - @Override public StillModel load (FileHandle handle, ModelLoaderHints hints) { + @Override + public StillModel load (FileHandle handle, ModelLoaderHints hints) { return loadObj(handle, hints.flipV); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/ColorAttribute.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/ColorAttribute.java index e3160f18a1a..1c9d904421f 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/ColorAttribute.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/ColorAttribute.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.materials; import com.badlogic.gdx.Gdx; @@ -6,22 +7,25 @@ public class ColorAttribute extends MaterialAttribute { Color color; - - public ColorAttribute(Color color, String name) { + + public ColorAttribute (Color color, String name) { super(name); this.color = new Color(color); } - - @Override public void bind () { - if(Gdx.gl10 == null) throw new RuntimeException("Can't call ColorAttribute.bind() in a GL20 context"); + + @Override + public void bind () { + if (Gdx.gl10 == null) throw new RuntimeException("Can't call ColorAttribute.bind() in a GL20 context"); Gdx.gl10.glColor4f(color.r, color.g, color.b, color.a); } - @Override public void bind (ShaderProgram program) { + @Override + public void bind (ShaderProgram program) { program.setUniformf(name, color.r, color.g, color.b, color.a); } - @Override public MaterialAttribute copy () { + @Override + public MaterialAttribute copy () { return new ColorAttribute(color, name); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/Material.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/Material.java index 7343488bb3a..43db905ef4f 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/Material.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/Material.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.materials; import java.util.Arrays; @@ -7,33 +8,34 @@ public class Material { public String name; public MaterialAttribute[] attributes; - - public Material(String name, MaterialAttribute ... attributes) { + + public Material (String name, MaterialAttribute... attributes) { this.name = name; this.attributes = attributes; } - public void bind() { - for(int i = 0; i < attributes.length; i++) { + public void bind () { + for (int i = 0; i < attributes.length; i++) { attributes[i].bind(); } } - - public void bind(ShaderProgram program) { - for(int i = 0; i < attributes.length; i++) { + + public void bind (ShaderProgram program) { + for (int i = 0; i < attributes.length; i++) { attributes[i].bind(program); } } - - public Material copy() { + + public Material copy () { MaterialAttribute[] attributes = new MaterialAttribute[this.attributes.length]; - for(int i = 0; i < attributes.length; i++) { + for (int i = 0; i < attributes.length; i++) { attributes[i] = this.attributes[i].copy(); } return new Material(name, attributes); } - - @Override public int hashCode () { + + @Override + public int hashCode () { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(attributes); @@ -41,14 +43,15 @@ public Material copy() { return result; } - @Override public boolean equals (Object obj) { + @Override + public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Material other = (Material)obj; - if(other.attributes.length != attributes.length) return false; - for(int i = 0; i < attributes.length; i++) { - if(!attributes[i].equals(other.attributes[i])) return false; + if (other.attributes.length != attributes.length) return false; + for (int i = 0; i < attributes.length; i++) { + if (!attributes[i].equals(other.attributes[i])) return false; } if (name == null) { if (other.name != null) return false; diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/MaterialAttribute.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/MaterialAttribute.java index 5443d19b1aa..028021185d5 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/MaterialAttribute.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/MaterialAttribute.java @@ -1,15 +1,18 @@ + package com.badlogic.gdx.graphics.g3d.materials; import com.badlogic.gdx.graphics.glutils.ShaderProgram; public abstract class MaterialAttribute { String name; - - public MaterialAttribute(String name) { + + public MaterialAttribute (String name) { this.name = name; } - - public abstract void bind(); - public abstract void bind(ShaderProgram program); - public abstract MaterialAttribute copy(); + + public abstract void bind (); + + public abstract void bind (ShaderProgram program); + + public abstract MaterialAttribute copy (); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/TextureAttribute.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/TextureAttribute.java index 2db1e75ccb4..e36a195bfeb 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/TextureAttribute.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/materials/TextureAttribute.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.materials; import com.badlogic.gdx.Gdx; @@ -14,8 +15,9 @@ public class TextureAttribute extends MaterialAttribute { public int magFilter; public int uWrap; public int vWrap; - - public TextureAttribute (Texture texture, int unit, String name, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { + + public TextureAttribute (Texture texture, int unit, String name, TextureFilter minFilter, TextureFilter magFilter, + TextureWrap uWrap, TextureWrap vWrap) { this(texture, unit, name, minFilter.getGLEnum(), magFilter.getGLEnum(), uWrap.getGLEnum(), vWrap.getGLEnum()); } @@ -28,29 +30,32 @@ public TextureAttribute (Texture texture, int unit, String name, int minFilter, this.minFilter = minFilter; this.magFilter = magFilter; } - + public TextureAttribute (Texture texture, int unit, String name) { - this(texture, unit, name, texture.getMinFilter(), texture.getMagFilter(), texture.getUWrap(), texture.getVWrap()); + this(texture, unit, name, texture.getMinFilter(), texture.getMagFilter(), texture.getUWrap(), texture.getVWrap()); } - @Override public void bind () { + @Override + public void bind () { texture.bind(unit); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, uWrap); - Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, vWrap); + Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, vWrap); } - @Override public void bind (ShaderProgram program) { + @Override + public void bind (ShaderProgram program) { texture.bind(unit); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, uWrap); - Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, vWrap); + Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, vWrap); program.setUniformi(name, unit); } - @Override public MaterialAttribute copy () { + @Override + public MaterialAttribute copy () { return new TextureAttribute(texture, unit, name, minFilter, magFilter, uWrap, vWrap); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/AnimatedModel.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/AnimatedModel.java index 5d94714deab..1dde154e242 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/AnimatedModel.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/AnimatedModel.java @@ -1,7 +1,10 @@ + package com.badlogic.gdx.graphics.g3d.model; public interface AnimatedModel extends Model { - public void setAnimation(String animation, float time, boolean loop); - public Animation getAnimation(String name); - public Animation[] getAnimations(); + public void setAnimation (String animation, float time, boolean loop); + + public Animation getAnimation (String name); + + public Animation[] getAnimations (); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Animation.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Animation.java index 3bf12d2f6a5..4c2c2476565 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Animation.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Animation.java @@ -1,10 +1,11 @@ + package com.badlogic.gdx.graphics.g3d.model; public class Animation { - public final String name; + public final String name; public final float totalDuration; - - public Animation(String name, float totalDuration) { + + public Animation (String name, float totalDuration) { this.name = name; this.totalDuration = totalDuration; } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Model.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Model.java index a9c7ecb4e89..a336806ddf1 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Model.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/Model.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model; import com.badlogic.gdx.graphics.g3d.materials.Material; @@ -5,13 +6,21 @@ import com.badlogic.gdx.math.collision.BoundingBox; public interface Model { - public void render(); - public void render(ShaderProgram program); - public Model getSubModel(String... subMeshNames); - public SubMesh getSubMesh(String name); - public SubMesh[] getSubMeshes(); - public void getBoundingBox(BoundingBox bbox); - public void setMaterials(Material... materials); - public void setMaterial(Material material); - public void dispose (); + public void render (); + + public void render (ShaderProgram program); + + public Model getSubModel (String... subMeshNames); + + public SubMesh getSubMesh (String name); + + public SubMesh[] getSubMeshes (); + + public void getBoundingBox (BoundingBox bbox); + + public void setMaterials (Material... materials); + + public void setMaterial (Material material); + + public void dispose (); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/SubMesh.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/SubMesh.java index 7ca285ce1cb..583f12968fb 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/SubMesh.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/SubMesh.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model; import com.badlogic.gdx.graphics.g3d.materials.Material; @@ -6,6 +7,6 @@ public abstract class SubMesh { public String name; public Material material; - - public abstract void getBoundingBox(BoundingBox bbox); + + public abstract void getBoundingBox (BoundingBox bbox); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/Keyframe.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/Keyframe.java index 7e678ff87b2..de647d15662 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/Keyframe.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/Keyframe.java @@ -1,11 +1,12 @@ + package com.badlogic.gdx.graphics.g3d.model.keyframe; public class Keyframe { - public final float timeStamp; + public final float timeStamp; public final float[] vertices; - - public Keyframe(float timeStamp, float[] vertices) { - this.timeStamp = timeStamp; + + public Keyframe (float timeStamp, float[] vertices) { + this.timeStamp = timeStamp; this.vertices = vertices; } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedAnimation.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedAnimation.java index d78054a6a4f..40649fe1ea1 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedAnimation.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedAnimation.java @@ -1,12 +1,13 @@ + package com.badlogic.gdx.graphics.g3d.model.keyframe; import com.badlogic.gdx.graphics.g3d.model.Animation; -public class KeyframedAnimation extends Animation { +public class KeyframedAnimation extends Animation { public final float frameDuration; public final Keyframe[] keyframes; - - public KeyframedAnimation(String name, float frameDuration, Keyframe[] keyframes) { + + public KeyframedAnimation (String name, float frameDuration, Keyframe[] keyframes) { super(name, frameDuration * keyframes.length); this.frameDuration = frameDuration; this.keyframes = keyframes; diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedModel.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedModel.java index 7fc8efc4433..ed7d4f0a269 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedModel.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedModel.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.keyframe; import com.badlogic.gdx.graphics.g3d.materials.Material; @@ -10,149 +11,169 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; - public class KeyframedModel implements AnimatedModel, Disposable { public final KeyframedSubMesh[] subMeshes; protected final KeyframedAnimation[] animations; - public KeyframedModel(KeyframedSubMesh[] subMeshes) { + public KeyframedModel (KeyframedSubMesh[] subMeshes) { this.subMeshes = subMeshes; Array meshAnims = subMeshes[0].animations.values().toArray(); animations = new KeyframedAnimation[meshAnims.size]; - for(int i = 0; i < animations.length; i++) { + for (int i = 0; i < animations.length; i++) { animations[i] = meshAnims.get(i); } - + checkValidity(); } - - private void checkValidity() { - for(int i = 0; i < subMeshes.length; i++) { - if(subMeshes[i].animations.size != animations.length) throw new GdxRuntimeException("number of animations in subMesh[0] is not the same in subMesh[" + i + "]. All sub-meshes must have the same animations and number of frames"); + + private void checkValidity () { + for (int i = 0; i < subMeshes.length; i++) { + if (subMeshes[i].animations.size != animations.length) + throw new GdxRuntimeException("number of animations in subMesh[0] is not the same in subMesh[" + i + + "]. All sub-meshes must have the same animations and number of frames"); } - - for(int i = 0; i < animations.length; i++) { + + for (int i = 0; i < animations.length; i++) { KeyframedAnimation anim = animations[i]; - for(int j = 0; j < subMeshes.length; j++) { + for (int j = 0; j < subMeshes.length; j++) { KeyframedAnimation otherAnim = subMeshes[j].animations.get(anim.name); - if(otherAnim == null) throw new GdxRuntimeException("animation '" + anim.name + "' missing in subMesh[" + j + "]"); - if(otherAnim.frameDuration != anim.frameDuration) throw new GdxRuntimeException("animation '" + anim.name + "' in subMesh[" + j + "] has different frame duration than the same animation in subMesh[0]"); - if(otherAnim.keyframes.length != anim.keyframes.length) throw new GdxRuntimeException("animation '" + anim.name + "' in subMesh[" + j + "] has different number of keyframes than the same animation in subMesh[0]"); + if (otherAnim == null) throw new GdxRuntimeException("animation '" + anim.name + "' missing in subMesh[" + j + "]"); + if (otherAnim.frameDuration != anim.frameDuration) + throw new GdxRuntimeException("animation '" + anim.name + "' in subMesh[" + j + + "] has different frame duration than the same animation in subMesh[0]"); + if (otherAnim.keyframes.length != anim.keyframes.length) + throw new GdxRuntimeException("animation '" + anim.name + "' in subMesh[" + j + + "] has different number of keyframes than the same animation in subMesh[0]"); } } } - - @Override public void render() { + + @Override + public void render () { int len = subMeshes.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { KeyframedSubMesh subMesh = subMeshes[i]; - if(i == 0 ) { + if (i == 0) { subMesh.material.bind(); - } else if (!subMeshes[i-1].material.equals(subMesh.material)) { + } else if (!subMeshes[i - 1].material.equals(subMesh.material)) { subMesh.material.bind(); } subMesh.mesh.render(subMesh.primitiveType); - } - } - - @Override public void render (ShaderProgram program) { + } + } + + @Override + public void render (ShaderProgram program) { // FIXME } - - @Override public void setMaterials(Material ... materials) { - if(materials.length != subMeshes.length) throw new UnsupportedOperationException("number of materials must equal number of sub-meshes"); + + @Override + public void setMaterials (Material... materials) { + if (materials.length != subMeshes.length) + throw new UnsupportedOperationException("number of materials must equal number of sub-meshes"); int len = materials.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { subMeshes[i].material = materials[i]; } } - - @Override public void setMaterial(Material material) { + + @Override + public void setMaterial (Material material) { int len = subMeshes.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { subMeshes[i].material = material; } } - - @Override public KeyframedSubMesh getSubMesh(String name) { + + @Override + public KeyframedSubMesh getSubMesh (String name) { int len = subMeshes.length; - for(int i = 0; i < len; i++) { - if(subMeshes[i].name.equals(name)) return subMeshes[i]; - } + for (int i = 0; i < len; i++) { + if (subMeshes[i].name.equals(name)) return subMeshes[i]; + } return null; } - @Override public SubMesh[] getSubMeshes () { + @Override + public SubMesh[] getSubMeshes () { return subMeshes; } - @Override public void setAnimation (String animation, float time, boolean loop) { + @Override + public void setAnimation (String animation, float time, boolean loop) { int len = subMeshes.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { final KeyframedSubMesh subMesh = subMeshes[i]; final KeyframedAnimation anim = subMesh.animations.get(animation); - if(anim == null) throw new IllegalArgumentException("No animation with name '" + animation + "' in submesh #" + i); - if(time < 0 || time > anim.totalDuration) throw new IllegalArgumentException("time must be 0 <= time <= animation duration"); - + if (anim == null) throw new IllegalArgumentException("No animation with name '" + animation + "' in submesh #" + i); + if (time < 0 || time > anim.totalDuration) + throw new IllegalArgumentException("time must be 0 <= time <= animation duration"); + final int startIndex = (int)Math.floor((time / anim.frameDuration)); final Keyframe startFrame = anim.keyframes[startIndex]; - final Keyframe endFrame = anim.keyframes[anim.keyframes.length-1==startIndex?loop?0:startIndex:startIndex + 1]; - + final Keyframe endFrame = anim.keyframes[anim.keyframes.length - 1 == startIndex ? loop ? 0 : startIndex + : startIndex + 1]; + final int numComponents = subMesh.animatedComponents; - final float[] src = startFrame.vertices; + final float[] src = startFrame.vertices; final int srcLen = numComponents * subMesh.mesh.getNumVertices(); - - final float[] dst = subMesh.blendedVertices; - final int dstInc = subMesh.mesh.getVertexSize() / 4 - numComponents; - - if(startFrame == endFrame) { - for(int srcIdx = 0, dstIdx = 0; srcIdx < srcLen; dstIdx += dstInc) { - for(int j = 0; j < numComponents; j++) { + + final float[] dst = subMesh.blendedVertices; + final int dstInc = subMesh.mesh.getVertexSize() / 4 - numComponents; + + if (startFrame == endFrame) { + for (int srcIdx = 0, dstIdx = 0; srcIdx < srcLen; dstIdx += dstInc) { + for (int j = 0; j < numComponents; j++) { dst[dstIdx++] = src[srcIdx++]; } } - } else { + } else { float[] src2 = endFrame.vertices; float alpha = (time - (startIndex * anim.frameDuration)) / anim.frameDuration; - for(int srcIdx = 0, dstIdx = 0; srcIdx < srcLen; dstIdx += dstInc) { - for(int j = 0; j < numComponents; j++) { + for (int srcIdx = 0, dstIdx = 0; srcIdx < srcLen; dstIdx += dstInc) { + for (int j = 0; j < numComponents; j++) { final float valSrc = src[srcIdx]; final float valSrc2 = src2[srcIdx++]; dst[dstIdx++] = valSrc + (valSrc2 - valSrc) * alpha; } } } - + subMesh.mesh.setVertices(dst); } } - - @Override public KeyframedAnimation getAnimation (String name) { - return subMeshes[0].animations.get(name); + + @Override + public KeyframedAnimation getAnimation (String name) { + return subMeshes[0].animations.get(name); } - - @Override public KeyframedAnimation[] getAnimations () { + + @Override + public KeyframedAnimation[] getAnimations () { return animations; } @Override - public Model getSubModel(String... subMeshNames) { + public Model getSubModel (String... subMeshNames) { // FIXME return null; } private final static BoundingBox tmpBox = new BoundingBox(); - @Override public void getBoundingBox (BoundingBox bbox) { + + @Override + public void getBoundingBox (BoundingBox bbox) { bbox.inf(); - for(int i = 0; i < subMeshes.length; i++) { + for (int i = 0; i < subMeshes.length; i++) { subMeshes[i].mesh.calculateBoundingBox(tmpBox); bbox.ext(tmpBox); } } - @Override public void dispose () { - for(int i = 0; i < subMeshes.length; i++) { + @Override + public void dispose () { + for (int i = 0; i < subMeshes.length; i++) { subMeshes[i].mesh.dispose(); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedSubMesh.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedSubMesh.java index 358223d022b..4fc4bc7ab11 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedSubMesh.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/keyframe/KeyframedSubMesh.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.keyframe; import com.badlogic.gdx.graphics.Mesh; @@ -5,15 +6,16 @@ import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.utils.ObjectMap; -public class KeyframedSubMesh extends SubMesh { +public class KeyframedSubMesh extends SubMesh { public final String name; - public final Mesh mesh; + public final Mesh mesh; public final float[] blendedVertices; public final int animatedComponents; public final ObjectMap animations; public final int primitiveType; - - public KeyframedSubMesh(String name, Mesh mesh, float[] blendedVertices, ObjectMap animations, int animatedComponents, int primitiveType) { + + public KeyframedSubMesh (String name, Mesh mesh, float[] blendedVertices, ObjectMap animations, + int animatedComponents, int primitiveType) { this.name = name; this.mesh = mesh; this.blendedVertices = blendedVertices; @@ -21,8 +23,9 @@ public KeyframedSubMesh(String name, Mesh mesh, float[] blendedVertices, ObjectM this.primitiveType = primitiveType; this.animatedComponents = animatedComponents; } - - @Override public void getBoundingBox (BoundingBox bbox) { + + @Override + public void getBoundingBox (BoundingBox bbox) { mesh.calculateBoundingBox(bbox); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/Skeleton.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/Skeleton.java index a2a04bccada..f72b814cd35 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/Skeleton.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/Skeleton.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.skeleton; import java.util.HashMap; @@ -26,16 +27,13 @@ public class Skeleton { public final Array combinedMatrices = new Array(); /** map of animations, indexed by name **/ public final ObjectMap animations = new ObjectMap(); - + private static final Matrix4 IDENTITY = new Matrix4(); private final Matrix4 rotMatrix = new Matrix4(); - - /** - * Fills the baseJoints, offsetMatrices and sceneMatrices Array instances - * with joints and Matrix4 instances in an breadth first order. This allows - * one to iterate over the joint arrays instead of recursing over the hierarchy - * when calculating the scene matrices. - */ + + /** Fills the baseJoints, offsetMatrices and sceneMatrices Array instances with joints and Matrix4 instances in an breadth first + * order. This allows one to iterate over the joint arrays instead of recursing over the hierarchy when calculating the scene + * matrices. */ public void buildFromHierarchy () { jointNames.clear(); namesToIndices.clear(); @@ -43,25 +41,25 @@ public void buildFromHierarchy () { animPoseJoints.clear(); offsetMatrices.clear(); sceneMatrices.clear(); - - for(int i = 0; i < hierarchy.size; i++) { + + for (int i = 0; i < hierarchy.size; i++) { recursiveFill(hierarchy.get(i)); } - + calculateMatrices(bindPoseJoints); calculateOffsetMatrices(); } - - private void recursiveFill(SkeletonJoint joint) { + + private void recursiveFill (SkeletonJoint joint) { joint.index = bindPoseJoints.size; - joint.parentIndex = joint.parent != null? joint.parent.index: -1; - + joint.parentIndex = joint.parent != null ? joint.parent.index : -1; + SkeletonKeyframe keyFrame = new SkeletonKeyframe(); keyFrame.position.set(joint.position); keyFrame.scale.set(joint.scale); keyFrame.rotation.set(joint.rotation); keyFrame.parentIndex = joint.parentIndex; - + jointNames.add(joint.name); namesToIndices.put(joint.name, joint.index); bindPoseJoints.add(keyFrame); @@ -71,72 +69,73 @@ private void recursiveFill(SkeletonJoint joint) { offsetMatrices.add(new Matrix4()); sceneMatrices.add(new Matrix4()); combinedMatrices.add(new Matrix4()); - + int len = joint.children.size; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { recursiveFill(joint.children.get(i)); } } - - protected void calculateOffsetMatrices() { - for(int i = 0; i < offsetMatrices.size; i++) { + + protected void calculateOffsetMatrices () { + for (int i = 0; i < offsetMatrices.size; i++) { offsetMatrices.get(i).set(sceneMatrices.get(i)).inv(); } } - - protected void calculateMatrices(Array joints) { - for(int i = 0; i < joints.size; i++) { + + protected void calculateMatrices (Array joints) { + for (int i = 0; i < joints.size; i++) { SkeletonKeyframe joint = joints.get(i); Matrix4 sceneMatrix = sceneMatrices.get(i); - Matrix4 parentMatrix = joint.parentIndex != -1? sceneMatrices.get(joint.parentIndex): IDENTITY; + Matrix4 parentMatrix = joint.parentIndex != -1 ? sceneMatrices.get(joint.parentIndex) : IDENTITY; Matrix4 combinedMatrix = combinedMatrices.get(i); - - joint.rotation.toMatrix(rotMatrix.val); + + joint.rotation.toMatrix(rotMatrix.val); rotMatrix.trn(joint.position); rotMatrix.scl(joint.scale); - sceneMatrix.set(parentMatrix); + sceneMatrix.set(parentMatrix); sceneMatrix.mul(rotMatrix); - + combinedMatrix.set(sceneMatrix); combinedMatrix.mul(offsetMatrices.get(i)); } } - - public void setAnimation(String name, float time) { + + public void setAnimation (String name, float time) { SkeletonAnimation anim = animations.get(name); - if(anim == null) throw new IllegalArgumentException("Animation with name '" + name + "' does not exist"); - if(time < 0 || time > anim.totalDuration) throw new IllegalArgumentException("time must be 0 <= time <= animation duration"); - + if (anim == null) throw new IllegalArgumentException("Animation with name '" + name + "' does not exist"); + if (time < 0 || time > anim.totalDuration) + throw new IllegalArgumentException("time must be 0 <= time <= animation duration"); + int len = anim.perJointkeyFrames.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { SkeletonKeyframe[] jointTrack = anim.perJointkeyFrames[i]; - int idx = 0; + int idx = 0; int len2 = jointTrack.length; - for(int j = 0; j < len2; j++) { + for (int j = 0; j < len2; j++) { SkeletonKeyframe jointFrame = jointTrack[j]; - if(jointFrame.timeStamp >= time) { + if (jointFrame.timeStamp >= time) { idx = Math.max(0, j - 1); break; } } - + SkeletonKeyframe startFrame = jointTrack[idx]; - SkeletonKeyframe endFrame = idx + 1 == len2? startFrame: jointTrack[idx+1]; - float alpha = 0; - - if(startFrame != endFrame) { + SkeletonKeyframe endFrame = idx + 1 == len2 ? startFrame : jointTrack[idx + 1]; + float alpha = 0; + + if (startFrame != endFrame) { alpha = Math.min(1, (time - startFrame.timeStamp) / (endFrame.timeStamp - startFrame.timeStamp)); } - SkeletonKeyframe animFrame = animPoseJoints.get(i); + SkeletonKeyframe animFrame = animPoseJoints.get(i); animFrame.position.set(startFrame.position).lerp(endFrame.position, alpha); animFrame.scale.set(startFrame.scale).lerp(endFrame.scale, alpha); - animFrame.rotation.set(startFrame.rotation).slerp(endFrame.rotation, alpha); + animFrame.rotation.set(startFrame.rotation).slerp(endFrame.rotation, alpha); } - + calculateMatrices(animPoseJoints); } - - public void setBindPose() { + + public void setBindPose () { calculateMatrices(bindPoseJoints); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonAnimation.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonAnimation.java index 2037c43ef8d..46d211a7ffd 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonAnimation.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonAnimation.java @@ -1,12 +1,13 @@ + package com.badlogic.gdx.graphics.g3d.model.skeleton; import com.badlogic.gdx.graphics.g3d.model.Animation; public class SkeletonAnimation extends Animation { public final SkeletonKeyframe[][] perJointkeyFrames; - - public SkeletonAnimation(String name, float totalDuration, SkeletonKeyframe[][] perJointKeyFrames) { + + public SkeletonAnimation (String name, float totalDuration, SkeletonKeyframe[][] perJointKeyFrames) { super(name, totalDuration); this.perJointkeyFrames = perJointKeyFrames; - } + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonJoint.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonJoint.java index 6335d8c50cf..a604f8c2933 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonJoint.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonJoint.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.skeleton; import com.badlogic.gdx.math.Quaternion; @@ -6,13 +7,13 @@ public class SkeletonJoint { public String name; - + public int index; public int parentIndex; public SkeletonJoint parent; public final Array children = new Array(1); - - public final Vector3 position = new Vector3(); - public final Quaternion rotation = new Quaternion(new Vector3(0, 1, 0), 0); - public final Vector3 scale = new Vector3(1, 1, 1); -} \ No newline at end of file + + public final Vector3 position = new Vector3(); + public final Quaternion rotation = new Quaternion(new Vector3(0, 1, 0), 0); + public final Vector3 scale = new Vector3(1, 1, 1); +} diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonKeyframe.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonKeyframe.java index 9e1371e62f8..91a027416e0 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonKeyframe.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonKeyframe.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.skeleton; import com.badlogic.gdx.math.Quaternion; @@ -8,13 +9,10 @@ public class SkeletonKeyframe { public int parentIndex = -1; public final Vector3 position = new Vector3(); public final Vector3 scale = new Vector3(1, 1, 1); - public final Quaternion rotation = new Quaternion(0, 0, 0, 1); - - public String toString() { - return "time: " + timeStamp + ", " + - "parent: " + parentIndex + ", " + - "position: " + position + ", " + - "scale: " + scale + ", " + - "rotation: " + rotation; + public final Quaternion rotation = new Quaternion(0, 0, 0, 1); + + public String toString () { + return "time: " + timeStamp + ", " + "parent: " + parentIndex + ", " + "position: " + position + ", " + "scale: " + scale + + ", " + "rotation: " + rotation; } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonModel.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonModel.java index bc6fd8c37f7..77d7e7ba652 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonModel.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonModel.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.skeleton; import com.badlogic.gdx.graphics.VertexAttributes.Usage; @@ -14,54 +15,57 @@ public class SkeletonModel implements AnimatedModel { public final Skeleton skeleton; public final SkeletonSubMesh[] subMeshes; - - public SkeletonModel(Skeleton skeleton, SkeletonSubMesh[] subMeshes) { + + public SkeletonModel (Skeleton skeleton, SkeletonSubMesh[] subMeshes) { this.skeleton = skeleton; this.subMeshes = subMeshes; setMaterial(new Material("default")); } - - public void setBindPose() { + + public void setBindPose () { skeleton.setBindPose(); - for(int i = 0; i < subMeshes.length; i++) { + for (int i = 0; i < subMeshes.length; i++) { skin(subMeshes[i], skeleton.combinedMatrices); } } - - @Override public void setAnimation(String animation, float time, boolean loop) { + + @Override + public void setAnimation (String animation, float time, boolean loop) { skeleton.setAnimation(animation, time); - for(int i = 0; i < subMeshes.length; i++) { + for (int i = 0; i < subMeshes.length; i++) { skin(subMeshes[i], skeleton.combinedMatrices); } } - + final Vector3 v = new Vector3(); - public void skin(SkeletonSubMesh subMesh, Array boneMatrices) { + + public void skin (SkeletonSubMesh subMesh, Array boneMatrices) { final int stride = subMesh.mesh.getVertexSize() / 4; final int numVertices = subMesh.mesh.getNumVertices(); int idx = 0; - int nidx = subMesh.mesh.getVertexAttribute(Usage.Normal) == null? -1: subMesh.mesh.getVertexAttribute(Usage.Normal).offset / 4; + int nidx = subMesh.mesh.getVertexAttribute(Usage.Normal) == null ? -1 + : subMesh.mesh.getVertexAttribute(Usage.Normal).offset / 4; final float[] vertices = subMesh.vertices; final float[] skinnedVertices = subMesh.skinnedVertices; - + System.arraycopy(subMesh.vertices, 0, skinnedVertices, 0, subMesh.vertices.length); - - for(int i = 0; i < numVertices; i++, idx += stride, nidx += stride) { + + for (int i = 0; i < numVertices; i++, idx += stride, nidx += stride) { final int[] boneIndices = subMesh.boneAssignments[i]; final float[] boneWeights = subMesh.boneWeights[i]; - - final float ox = vertices[idx], oy = vertices[idx+1], oz = vertices[idx+2]; + + final float ox = vertices[idx], oy = vertices[idx + 1], oz = vertices[idx + 2]; float x = 0, y = 0, z = 0; final float onx = 0, ony = 0, onz = 0; float nx = 0, ny = 0, nz = 0; - - if(nidx != -1) { + + if (nidx != -1) { nx = vertices[nidx]; - ny = vertices[nidx+1]; - nz = vertices[nidx+2]; + ny = vertices[nidx + 1]; + nz = vertices[nidx + 2]; } - - for(int j = 0; j < boneIndices.length; j++) { + + for (int j = 0; j < boneIndices.length; j++) { int boneIndex = boneIndices[j]; float weight = boneWeights[j]; v.set(ox, oy, oz); @@ -69,85 +73,95 @@ public void skin(SkeletonSubMesh subMesh, Array boneMatrices) { x += v.x * weight; y += v.y * weight; z += v.z * weight; - - if(nidx != -1) { + + if (nidx != -1) { v.set(onx, ony, onz); v.rot(boneMatrices.get(boneIndex)); nx += v.x * weight; ny += v.y * weight; nz += v.z * weight; } - } - + } + skinnedVertices[idx] = x; - skinnedVertices[idx+1] = y; - skinnedVertices[idx+2] = z; - - if(nidx != -1) { + skinnedVertices[idx + 1] = y; + skinnedVertices[idx + 2] = z; + + if (nidx != -1) { skinnedVertices[nidx] = nx; - skinnedVertices[nidx+1] = ny; - skinnedVertices[nidx+2] = nz; + skinnedVertices[nidx + 1] = ny; + skinnedVertices[nidx + 2] = nz; } } - + subMesh.mesh.setVertices(skinnedVertices); } - - @Override public void render() { + + @Override + public void render () { int len = subMeshes.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { SkeletonSubMesh subMesh = subMeshes[i]; - if(i == 0 ) { + if (i == 0) { subMesh.material.bind(); - } else if (!subMeshes[i-1].material.equals(subMesh.material)) { + } else if (!subMeshes[i - 1].material.equals(subMesh.material)) { subMesh.material.bind(); } subMesh.mesh.render(subMesh.primitiveType); - } + } } - - @Override public void render (ShaderProgram program) { + + @Override + public void render (ShaderProgram program) { // FIXME } - - @Override public void setMaterials(Material ... materials) { - if(materials.length != subMeshes.length) throw new UnsupportedOperationException("number of materials must equal number of sub-meshes"); + + @Override + public void setMaterials (Material... materials) { + if (materials.length != subMeshes.length) + throw new UnsupportedOperationException("number of materials must equal number of sub-meshes"); int len = materials.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { subMeshes[i].material = materials[i]; } } - - @Override public void setMaterial(Material material) { + + @Override + public void setMaterial (Material material) { int len = subMeshes.length; - for(int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { subMeshes[i].material = material; } } - - @Override public SubMesh getSubMesh(String name) { + + @Override + public SubMesh getSubMesh (String name) { int len = subMeshes.length; - for(int i = 0; i < len; i++) { - if(subMeshes[i].name.equals(name)) return subMeshes[i]; - } + for (int i = 0; i < len; i++) { + if (subMeshes[i].name.equals(name)) return subMeshes[i]; + } return null; } - @Override public SubMesh[] getSubMeshes () { + @Override + public SubMesh[] getSubMeshes () { return subMeshes; } - @Override public SkeletonAnimation getAnimation (String name) { + @Override + public SkeletonAnimation getAnimation (String name) { return skeleton.animations.get(name); } // FIXME, ugh... protected SkeletonAnimation[] animations; - @Override public SkeletonAnimation[] getAnimations () { - if(animations == null || animations.length != skeleton.animations.size) { + + @Override + public SkeletonAnimation[] getAnimations () { + if (animations == null || animations.length != skeleton.animations.size) { animations = new SkeletonAnimation[skeleton.animations.size]; int i = 0; - for(SkeletonAnimation anim: skeleton.animations.values()) { + for (SkeletonAnimation anim : skeleton.animations.values()) { animations[i] = anim; } } @@ -155,22 +169,25 @@ public void skin(SkeletonSubMesh subMesh, Array boneMatrices) { } @Override - public Model getSubModel(String... subMeshNames) { + public Model getSubModel (String... subMeshNames) { // FIXME return null; } - + private final static BoundingBox tmpBox = new BoundingBox(); - @Override public void getBoundingBox (BoundingBox bbox) { + + @Override + public void getBoundingBox (BoundingBox bbox) { bbox.inf(); - for(int i = 0; i < subMeshes.length; i++) { + for (int i = 0; i < subMeshes.length; i++) { subMeshes[i].mesh.calculateBoundingBox(tmpBox); bbox.ext(tmpBox); } } - - @Override public void dispose () { - for(int i = 0; i < subMeshes.length; i++) { + + @Override + public void dispose () { + for (int i = 0; i < subMeshes.length; i++) { subMeshes[i].mesh.dispose(); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonSubMesh.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonSubMesh.java index e30cf6a329c..25da9ec9620 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonSubMesh.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/skeleton/SkeletonSubMesh.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.skeleton; import com.badlogic.gdx.graphics.Mesh; @@ -5,16 +6,17 @@ import com.badlogic.gdx.math.collision.BoundingBox; public class SkeletonSubMesh extends SubMesh { - public String name; + public String name; public Mesh mesh; public short[] indices; public float[] vertices; public float[] skinnedVertices; public int primitiveType; public int[][] boneAssignments; - public float[][] boneWeights; - - @Override public void getBoundingBox (BoundingBox bbox) { + public float[][] boneWeights; + + @Override + public void getBoundingBox (BoundingBox bbox) { mesh.calculateBoundingBox(bbox); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillModel.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillModel.java index 215634414f3..d9f43b8c9e0 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillModel.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillModel.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.still; import java.util.ArrayList; @@ -11,16 +12,16 @@ public class StillModel implements Model { final public StillSubMesh[] subMeshes; - public StillModel(StillSubMesh[] subMeshes) { + public StillModel (StillSubMesh[] subMeshes) { this.subMeshes = subMeshes; } @Override - public void render() { + public void render () { int len = subMeshes.length; for (int i = 0; i < len; i++) { StillSubMesh subMesh = subMeshes[i]; - if (i == 0) { + if (i == 0) { subMesh.material.bind(); } else if (!subMeshes[i - 1].material.equals(subMesh.material)) { subMesh.material.bind(); @@ -30,43 +31,38 @@ public void render() { } @Override - public void render(ShaderProgram program) { + public void render (ShaderProgram program) { // TODO Auto-generated method stub } @Override - public Model getSubModel(String... subMeshNames) { + public Model getSubModel (String... subMeshNames) { ArrayList subMeshes = new ArrayList(); for (String name : subMeshNames) for (StillSubMesh subMesh : this.subMeshes) - if (name.equals(subMesh.name)) - subMeshes.add(subMesh); - if (subMeshes.size() > 0) - return new StillModel(subMeshes.toArray(new StillSubMesh[subMeshes - .size()])); + if (name.equals(subMesh.name)) subMeshes.add(subMesh); + if (subMeshes.size() > 0) return new StillModel(subMeshes.toArray(new StillSubMesh[subMeshes.size()])); return null; } @Override - public StillSubMesh getSubMesh(String name) { + public StillSubMesh getSubMesh (String name) { for (StillSubMesh subMesh : subMeshes) { - if (subMesh.name.equals(name)) - return subMesh; + if (subMesh.name.equals(name)) return subMesh; } return null; } @Override - public SubMesh[] getSubMeshes() { + public SubMesh[] getSubMeshes () { return subMeshes; } @Override - public void setMaterials(Material... materials) { + public void setMaterials (Material... materials) { if (materials.length != subMeshes.length) - throw new UnsupportedOperationException( - "number of materials must equal number of sub-meshes"); + throw new UnsupportedOperationException("number of materials must equal number of sub-meshes"); int len = materials.length; for (int i = 0; i < len; i++) { subMeshes[i].material = materials[i]; @@ -74,7 +70,7 @@ public void setMaterials(Material... materials) { } @Override - public void setMaterial(Material material) { + public void setMaterial (Material material) { int len = subMeshes.length; for (int i = 0; i < len; i++) { subMeshes[i].material = material; @@ -84,16 +80,17 @@ public void setMaterial(Material material) { private final static BoundingBox tmpBox = new BoundingBox(); @Override - public void getBoundingBox(BoundingBox bbox) { + public void getBoundingBox (BoundingBox bbox) { bbox.inf(); for (int i = 0; i < subMeshes.length; i++) { subMeshes[i].mesh.calculateBoundingBox(tmpBox); bbox.ext(tmpBox); } } - - @Override public void dispose () { - for(int i = 0; i < subMeshes.length; i++) { + + @Override + public void dispose () { + for (int i = 0; i < subMeshes.length; i++) { subMeshes[i].mesh.dispose(); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillSubMesh.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillSubMesh.java index 0f35bdeb1e2..1d661c6562f 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillSubMesh.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/model/still/StillSubMesh.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.model.still; import com.badlogic.gdx.graphics.Mesh; @@ -7,14 +8,15 @@ public class StillSubMesh extends SubMesh { final public Mesh mesh; final public int primitiveType; - + public StillSubMesh (String name, Mesh mesh, int primitiveType) { this.name = name; this.mesh = mesh; this.primitiveType = primitiveType; } - - @Override public void getBoundingBox (BoundingBox bbox) { + + @Override + public void getBoundingBox (BoundingBox bbox) { mesh.calculateBoundingBox(bbox); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/ChunkTest.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/ChunkTest.java index 2e65638784d..1717a437127 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/ChunkTest.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/ChunkTest.java @@ -1,14 +1,5 @@ -package com.badlogic.gdx.graphics.g3d.test; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.INDEX_LIST; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.MAJOR_VERSION; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.MINOR_VERSION; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.STILL_MODEL; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.STILL_SUBMESH; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERSION_INFO; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERTEX_ATTRIBUTE; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERTEX_ATTRIBUTES; -import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.VERTEX_LIST; +package com.badlogic.gdx.graphics.g3d.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -19,43 +10,45 @@ import com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks.ChunkReader.Chunk; import com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks.ChunkWriter; +import static com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dConstants.*; + public class ChunkTest { - public static void main(String[] argv) throws IOException { - ChunkWriter writer = new ChunkWriter(); + public static void main (String[] argv) throws IOException { + ChunkWriter writer = new ChunkWriter(); writer.newChunk(VERSION_INFO); - writer.writeByte(MAJOR_VERSION); - writer.writeByte(MINOR_VERSION); - writer.endChunk(); - writer.newChunk(STILL_MODEL); + writer.writeByte(MAJOR_VERSION); + writer.writeByte(MINOR_VERSION); + writer.endChunk(); + writer.newChunk(STILL_MODEL); + writer.writeInt(2); + for (int i = 0; i < 2; i++) { + writer.newChunk(STILL_SUBMESH); + writer.writeString("triangle" + i); + writer.newChunk(VERTEX_ATTRIBUTES); + writer.writeInt(1); + writer.newChunk(VERTEX_ATTRIBUTE); + writer.writeInt(Usage.Position); writer.writeInt(2); - for(int i = 0; i < 2; i++) { - writer.newChunk(STILL_SUBMESH); - writer.writeString("triangle" + i); - writer.newChunk(VERTEX_ATTRIBUTES); - writer.writeInt(1); - writer.newChunk(VERTEX_ATTRIBUTE); - writer.writeInt(Usage.Position); - writer.writeInt(2); - writer.writeString("a_pos"); - writer.endChunk(); - writer.endChunk(); - writer.newChunk(VERTEX_LIST); - writer.writeFloats(new float[] { -1, -1, 0, 1, 1, -1 } ); - writer.endChunk(); - writer.newChunk(INDEX_LIST); - writer.writeShorts(new short[] { 0, 1, 2 } ); - writer.endChunk(); - writer.endChunk(); - } - writer.endChunk(); - + writer.writeString("a_pos"); + writer.endChunk(); + writer.endChunk(); + writer.newChunk(VERTEX_LIST); + writer.writeFloats(new float[] {-1, -1, 0, 1, 1, -1}); + writer.endChunk(); + writer.newChunk(INDEX_LIST); + writer.writeShorts(new short[] {0, 1, 2}); + writer.endChunk(); + writer.endChunk(); + } + writer.endChunk(); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); writer.writeToStream(bytes); System.out.println("bytes: " + bytes.toByteArray().length); - + Chunk root = ChunkReader.readChunks(new ByteArrayInputStream(bytes.toByteArray())); ChunkReader.printChunks(root); - + Chunk version = root.getChild(VERSION_INFO); Chunk stillModel = root.getChild(STILL_MODEL); } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/KeyframedModelViewer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/KeyframedModelViewer.java index a2b0eceb983..ed887a6a132 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/KeyframedModelViewer.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/KeyframedModelViewer.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.test; import com.badlogic.gdx.ApplicationListener; @@ -6,14 +7,12 @@ import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.PerspectiveCamera; -import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Pixmap.Format; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g3d.loaders.ModelLoaderRegistry; -import com.badlogic.gdx.graphics.g3d.materials.Material; -import com.badlogic.gdx.graphics.g3d.materials.TextureAttribute; import com.badlogic.gdx.graphics.g3d.model.keyframe.KeyframedAnimation; import com.badlogic.gdx.graphics.g3d.model.keyframe.KeyframedModel; import com.badlogic.gdx.graphics.g3d.model.keyframe.KeyframedSubMesh; @@ -22,7 +21,7 @@ public class KeyframedModelViewer implements ApplicationListener { PerspectiveCamera cam; - KeyframedModel model; + KeyframedModel model; Texture texture = null; boolean hasNormals = false; BoundingBox bounds = new BoundingBox(); @@ -31,106 +30,110 @@ public class KeyframedModelViewer implements ApplicationListener { String fileName; String textureFileName; KeyframedAnimation anim; - float animTime = 0; + float animTime = 0; SpriteBatch batch; BitmapFont font; - - public KeyframedModelViewer(String fileName, String textureFileName) { + + public KeyframedModelViewer (String fileName, String textureFileName) { this.fileName = fileName; this.textureFileName = textureFileName; } - - @Override public void create () { - model = ModelLoaderRegistry.loadKeyframedModel(Gdx.files.internal(fileName)); - if(textureFileName != null) texture = new Texture(Gdx.files.internal(textureFileName), Format.RGB565, true); + + @Override + public void create () { + model = ModelLoaderRegistry.loadKeyframedModel(Gdx.files.internal(fileName)); + if (textureFileName != null) texture = new Texture(Gdx.files.internal(textureFileName), Format.RGB565, true); hasNormals = hasNormals(); -// Material material = new Material("material", new TextureAttribute(texture, 0, "s_tex")); -// model.setMaterial(material); - anim = (KeyframedAnimation)model.getAnimations()[0]; - +// Material material = new Material("material", new TextureAttribute(texture, 0, "s_tex")); +// model.setMaterial(material); + anim = (KeyframedAnimation)model.getAnimations()[0]; + model.getBoundingBox(bounds); float len = bounds.getDimensions().len(); - System.out.println("bounds: " + bounds); - + System.out.println("bounds: " + bounds); + cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(bounds.getCenter().cpy().add(len, len, len)); cam.lookAt(bounds.getCenter().x, bounds.getCenter().y, bounds.getCenter().z); cam.near = 1f; cam.far = 1000; - + renderer = new ImmediateModeRenderer10(); batch = new SpriteBatch(); font = new BitmapFont(); } - - private boolean hasNormals() { - for(KeyframedSubMesh mesh: model.subMeshes) { - if(mesh.mesh.getVertexAttribute(Usage.Normal) == null) return false; + + private boolean hasNormals () { + for (KeyframedSubMesh mesh : model.subMeshes) { + if (mesh.mesh.getVertexAttribute(Usage.Normal) == null) return false; } return true; } - @Override public void resume () { - + @Override + public void resume () { + } float[] lightColor = {1, 1, 1, 0}; float[] lightPosition = {2, 5, 10, 0}; - @Override public void render () { + + @Override + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); - Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); - + Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); + cam.update(); - cam.apply(Gdx.gl10); - + cam.apply(Gdx.gl10); + drawAxes(); - - if(hasNormals) { + + if (hasNormals) { Gdx.gl.glEnable(GL10.GL_LIGHTING); Gdx.gl.glEnable(GL10.GL_COLOR_MATERIAL); Gdx.gl.glEnable(GL10.GL_LIGHT0); Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0); - Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); + Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); } - - if(texture != null) { + + if (texture != null) { Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); texture.bind(); -// Gdx.gl.glEnable(GL10.GL_BLEND); -// Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); +// Gdx.gl.glEnable(GL10.GL_BLEND); +// Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); } - + angle += 45 * Gdx.graphics.getDeltaTime(); -// Gdx.gl10.glRotatef(angle, 0, 1, 0); +// Gdx.gl10.glRotatef(angle, 0, 1, 0); animTime += Gdx.graphics.getDeltaTime(); - if(animTime > anim.totalDuration - anim.frameDuration) { + if (animTime > anim.totalDuration - anim.frameDuration) { animTime = 0; } - + model.setAnimation(anim.name, animTime, false); - for(int i = 0; i < 20; i++) { + for (int i = 0; i < 20; i++) { Gdx.gl10.glPushMatrix(); - Gdx.gl10.glTranslatef(0, 0, -100 + i * 10); - model.render(); + Gdx.gl10.glTranslatef(0, 0, -100 + i * 10); + model.render(); Gdx.gl10.glPopMatrix(); } - - if(texture != null) { + + if (texture != null) { Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); } - - if(hasNormals) { + + if (hasNormals) { Gdx.gl.glDisable(GL10.GL_LIGHTING); } - + batch.begin(); font.setColor(Color.RED); font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 20, 30); batch.end(); } - - private void drawAxes() { + + private void drawAxes () { float len = bounds.getDimensions().len(); renderer.begin(GL10.GL_LINES); renderer.color(1, 0, 0, 1); @@ -149,26 +152,29 @@ private void drawAxes() { Gdx.gl10.glColor4f(1, 1, 1, 1); } - @Override public void resize (int width, int height) { - + @Override + public void resize (int width, int height) { + + } + + @Override + public void pause () { + } - @Override public void pause () { - + @Override + public void dispose () { } - @Override public void dispose () { - } - - public static void main(String[] argv) { -// if(argv.length != 1 && argv.length != 2) { -// System.out.println("KeyframedModelViewer ?"); -// System.exit(-1); -// } -// new JoglApplication(new KeyframedModelViewer("data/knight.md2", "data/knight.jpg"), "KeframedModel Viewer", 800, 480, false); -// new JoglApplication(new KeyframedModelViewer("data/boy.g3dt", "data/boy.png"), "KeframedModel Viewer", 800, 480, false); - + public static void main (String[] argv) { +// if(argv.length != 1 && argv.length != 2) { +// System.out.println("KeyframedModelViewer ?"); +// System.exit(-1); +// } +// new JoglApplication(new KeyframedModelViewer("data/knight.md2", "data/knight.jpg"), "KeframedModel Viewer", 800, 480, false); +// new JoglApplication(new KeyframedModelViewer("data/boy.g3dt", "data/boy.png"), "KeframedModel Viewer", 800, 480, false); + new JoglApplication(new KeyframedModelViewer("data/knight.g3d", "data/knight.jpg"), "KeframedModel Viewer", 800, 480, false); -// new JoglApplication(new KeyframedModelViewer("data/boy.g3d", "data/boy.png"), "KeframedModel Viewer", 800, 480, false); +// new JoglApplication(new KeyframedModelViewer("data/boy.g3d", "data/boy.png"), "KeframedModel Viewer", 800, 480, false); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java index f8c5f5d27d3..2f4058534e8 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/QbobViewer.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.test; import com.badlogic.gdx.ApplicationListener; @@ -25,22 +26,24 @@ public class QbobViewer implements ApplicationListener { PerspectiveCamera cam; KeyframedModel animModel; KeyframedAnimation anim; - float animTime = 0; - + float animTime = 0; + StillModel model[] = new StillModel[4]; Texture diffuse; Texture[] lightMaps = new Texture[4]; - FPSLogger fps = new FPSLogger(); + FPSLogger fps = new FPSLogger(); PerspectiveCamController controller; SpriteBatch batch; - BitmapFont font; - - @Override public void create () { + BitmapFont font; + + @Override + public void create () { animModel = G3dtLoader.loadKeyframedModel(Gdx.files.internal("data/boy.g3dt"), true); anim = animModel.getAnimations()[0]; - Material material = new Material("default", new TextureAttribute(new Texture(Gdx.files.internal("data/boy.png")), 0, "tex0")); + Material material = new Material("default", + new TextureAttribute(new Texture(Gdx.files.internal("data/boy.png")), 0, "tex0")); animModel.setMaterial(material); - + model[0] = G3dLoader.loadStillModel(Gdx.files.internal("data/qbob/test_section_01.dae.g3d")); lightMaps[0] = new Texture(Gdx.files.internal("data/qbob/world_blobbie_lm_01.jpg"), Format.RGB565, true); model[1] = G3dLoader.loadStillModel(Gdx.files.internal("data/qbob/test_section_02.dae.g3d")); @@ -49,110 +52,114 @@ public class QbobViewer implements ApplicationListener { lightMaps[2] = new Texture(Gdx.files.internal("data/qbob/world_blobbie_lm_03.jpg"), Format.RGB565, true); model[3] = G3dLoader.loadStillModel(Gdx.files.internal("data/qbob/test_section_04.dae.g3d")); lightMaps[3] = new Texture(Gdx.files.internal("data/qbob/world_blobbie_lm_04.jpg"), Format.RGB565, true); - + diffuse = new Texture(Gdx.files.internal("data/qbob/world_blobbie_blocks.png"), Format.RGB565, true); - + cam = new PerspectiveCamera(60, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(30, 10, 85f); - cam.direction.set(0,0,-1); - cam.up.set(0,1,0); + cam.direction.set(0, 0, -1); + cam.up.set(0, 1, 0); cam.near = 10f; - cam.far = 1000; - + cam.far = 1000; + controller = new PerspectiveCamController(cam); Gdx.input.setInputProcessor(controller); - + batch = new SpriteBatch(); font = new BitmapFont(); - } + } + + @Override + public void resume () { - @Override public void resume () { - } - - @Override public void render () { + + @Override + public void render () { Gdx.gl.glClearColor(0, 0, 0, 1); - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); - + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + cam.update(); - cam.apply(Gdx.gl10); - + cam.apply(Gdx.gl10); + Gdx.gl.glEnable(GL10.GL_CULL_FACE); Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); - + Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0); Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); diffuse.bind(); - diffuse.setFilter(TextureFilter.MipMap, TextureFilter.Linear); - + diffuse.setFilter(TextureFilter.MipMap, TextureFilter.Linear); + Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1); Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); - + lightMaps[0].bind(); - lightMaps[0].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear); + lightMaps[0].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear); setCombiners(); - + model[0].render(); lightMaps[1].bind(); lightMaps[1].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear); setCombiners(); - + model[1].render(); lightMaps[2].bind(); - lightMaps[2].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear); + lightMaps[2].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear); setCombiners(); - + model[2].render(); lightMaps[3].bind(); - lightMaps[3].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear); + lightMaps[3].setFilter(TextureFilter.MipMapNearestNearest, TextureFilter.Linear); setCombiners(); model[3].render(); - + Gdx.gl.glActiveTexture(GL10.GL_TEXTURE1); Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0); Gdx.gl.glDisable(GL10.GL_CULL_FACE); Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE); - + Gdx.gl.glDisable(GL10.GL_BLEND); - - + animTime += Gdx.graphics.getDeltaTime(); - if(animTime > anim.totalDuration - anim.frameDuration) animTime = 0; + if (animTime > anim.totalDuration - anim.frameDuration) animTime = 0; animModel.setAnimation(anim.name, animTime, true); - + Gdx.gl10.glPushMatrix(); Gdx.gl10.glTranslatef(cam.position.x, cam.position.y, 6); - animModel.render(); - Gdx.gl10.glPopMatrix(); - + animModel.render(); + Gdx.gl10.glPopMatrix(); + Gdx.gl.glDisable(GL10.GL_DEPTH_TEST); batch.begin(); font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 20); - batch.end(); - - fps.log(); + batch.end(); + + fps.log(); } - - private void setCombiners() { + + private void setCombiners () { Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_COMBINE); Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB, GL11.GL_ADD_SIGNED); Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC0_RGB, GL11.GL_PREVIOUS); - Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB, GL11.GL_TEXTURE); + Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB, GL11.GL_TEXTURE); } - - @Override public void resize (int width, int height) { - + + @Override + public void resize (int width, int height) { + + } + + @Override + public void pause () { + } - @Override public void pause () { - + @Override + public void dispose () { } - @Override public void dispose () { - } - - public static void main(String[] argv) { + public static void main (String[] argv) { new JoglApplication(new QbobViewer(), "Qbob Viewer", 800, 480, false); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java index 04b8948e8ac..2652eaf63e7 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/SkeletonModelViewer.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.test; import com.badlogic.gdx.ApplicationListener; @@ -21,7 +22,7 @@ public class SkeletonModelViewer implements ApplicationListener { PerspectiveCamera cam; - SkeletonModel model; + SkeletonModel model; Texture texture = null; boolean hasNormals = false; BoundingBox bounds = new BoundingBox(); @@ -30,101 +31,106 @@ public class SkeletonModelViewer implements ApplicationListener { String fileName; String textureFileName; SkeletonAnimation anim; - float animTime = 0; + float animTime = 0; SpriteBatch batch; BitmapFont font; - - public SkeletonModelViewer(String fileName, String textureFileName) { + + public SkeletonModelViewer (String fileName, String textureFileName) { this.fileName = fileName; this.textureFileName = textureFileName; } - - @Override public void create () { - if(fileName.endsWith(".xml")) { - model = new OgreXmlLoader().load(Gdx.files.internal(fileName), Gdx.files.internal(fileName.replace("mesh.xml", "skeleton.xml"))); - } - else throw new GdxRuntimeException("Unknown file format '" + fileName + "'"); - if(textureFileName != null) texture = new Texture(Gdx.files.internal(textureFileName)); + + @Override + public void create () { + if (fileName.endsWith(".xml")) { + model = new OgreXmlLoader().load(Gdx.files.internal(fileName), + Gdx.files.internal(fileName.replace("mesh.xml", "skeleton.xml"))); + } else + throw new GdxRuntimeException("Unknown file format '" + fileName + "'"); + if (textureFileName != null) texture = new Texture(Gdx.files.internal(textureFileName)); hasNormals = hasNormals(); Material material = new Material("material", new TextureAttribute(texture, 0, "s_tex")); - model.setMaterial(material); - anim = (SkeletonAnimation)model.getAnimations()[0]; - + model.setMaterial(material); + anim = (SkeletonAnimation)model.getAnimations()[0]; + model.getBoundingBox(bounds); float len = bounds.getDimensions().len(); - System.out.println("bounds: " + bounds); - + System.out.println("bounds: " + bounds); + cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(bounds.getCenter().cpy().add(len, len, len)); cam.lookAt(bounds.getCenter().x, bounds.getCenter().y, bounds.getCenter().z); cam.near = 0.1f; cam.far = 1000; - + renderer = new ImmediateModeRenderer10(); batch = new SpriteBatch(); font = new BitmapFont(); } - - private boolean hasNormals() { - for(SkeletonSubMesh mesh: model.subMeshes) { - if(mesh.mesh.getVertexAttribute(Usage.Normal) == null) return false; + + private boolean hasNormals () { + for (SkeletonSubMesh mesh : model.subMeshes) { + if (mesh.mesh.getVertexAttribute(Usage.Normal) == null) return false; } return true; } - @Override public void resume () { - + @Override + public void resume () { + } float[] lightColor = {1, 1, 1, 0}; float[] lightPosition = {2, 5, 10, 0}; - @Override public void render () { + + @Override + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); - Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); - + Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); + cam.update(); - cam.apply(Gdx.gl10); - + cam.apply(Gdx.gl10); + drawAxes(); - - if(hasNormals) { + + if (hasNormals) { Gdx.gl.glEnable(GL10.GL_LIGHTING); Gdx.gl.glEnable(GL10.GL_COLOR_MATERIAL); Gdx.gl.glEnable(GL10.GL_LIGHT0); Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0); - Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); + Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); } - - if(texture != null) { + + if (texture != null) { Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); Gdx.gl.glEnable(GL10.GL_BLEND); - Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); } - + angle += 45 * Gdx.graphics.getDeltaTime(); - Gdx.gl10.glRotatef(angle, 0, 1, 0); + Gdx.gl10.glRotatef(angle, 0, 1, 0); animTime += Gdx.graphics.getDeltaTime(); - if(animTime > anim.totalDuration) { + if (animTime > anim.totalDuration) { animTime = 0; } model.setAnimation(anim.name, animTime, false); - model.render(); - - if(texture != null) { + model.render(); + + if (texture != null) { Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); } - - if(hasNormals) { + + if (hasNormals) { Gdx.gl.glDisable(GL10.GL_LIGHTING); } - + batch.begin(); font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 20, 30); batch.end(); } - - private void drawAxes() { + + private void drawAxes () { float len = bounds.getDimensions().len(); renderer.begin(GL10.GL_LINES); renderer.color(1, 0, 0, 1); @@ -143,22 +149,26 @@ private void drawAxes() { Gdx.gl10.glColor4f(1, 1, 1, 1); } - @Override public void resize (int width, int height) { - + @Override + public void resize (int width, int height) { + + } + + @Override + public void pause () { + } - @Override public void pause () { - + @Override + public void dispose () { } - @Override public void dispose () { - } - - public static void main(String[] argv) { -// if(argv.length != 1 && argv.length != 2) { -// System.out.println("KeyframedModelViewer ?"); -// System.exit(-1); -// } - new JoglApplication(new SkeletonModelViewer("data/robot-mesh.xml", "data/robot.jpg"), "SkeletonModel Viewer", 800, 480, false); + public static void main (String[] argv) { +// if(argv.length != 1 && argv.length != 2) { +// System.out.println("KeyframedModelViewer ?"); +// System.exit(-1); +// } + new JoglApplication(new SkeletonModelViewer("data/robot-mesh.xml", "data/robot.jpg"), "SkeletonModel Viewer", 800, 480, + false); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/StillModelViewer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/StillModelViewer.java index 22aa154054b..de6fd896541 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/StillModelViewer.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/StillModelViewer.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.test; import com.badlogic.gdx.ApplicationListener; @@ -33,132 +34,136 @@ public class StillModelViewer implements ApplicationListener { FPSLogger fps = new FPSLogger(); SpriteBatch batch; BitmapFont font; - - public StillModelViewer(String fileName, String ... textureFileNames) { + + public StillModelViewer (String fileName, String... textureFileNames) { this.fileName = fileName; this.textureFileNames = textureFileNames; } - - @Override public void create () { + + @Override + public void create () { long start = System.nanoTime(); - model = ModelLoaderRegistry.loadStillModel(Gdx.files.internal(fileName)); - Gdx.app.log("StillModelViewer", "loading took: " + (System.nanoTime() - start)/ 1000000000.0f); - - for(StillSubMesh mesh: model.subMeshes) { + model = ModelLoaderRegistry.loadStillModel(Gdx.files.internal(fileName)); + Gdx.app.log("StillModelViewer", "loading took: " + (System.nanoTime() - start) / 1000000000.0f); + + for (StillSubMesh mesh : model.subMeshes) { mesh.mesh.scale(0.1f, 0.1f, 0.1f); } - - if(!fileName.endsWith(".g3d")) { - G3dExporter.export(model, Gdx.files.absolute(fileName + ".g3d")); + + if (!fileName.endsWith(".g3d")) { + G3dExporter.export(model, Gdx.files.absolute(fileName + ".g3d")); start = System.nanoTime(); model = G3dLoader.loadStillModel(Gdx.files.absolute(fileName + ".g3d")); - Gdx.app.log("StillModelViewer", "loading binary took: " + (System.nanoTime() - start)/ 1000000000.0f); + Gdx.app.log("StillModelViewer", "loading binary took: " + (System.nanoTime() - start) / 1000000000.0f); } - - if(textureFileNames.length != 0) { + + if (textureFileNames.length != 0) { textures = new Texture[textureFileNames.length]; - for(int i = 0; i < textureFileNames.length; i++) { - textures[i] = new Texture(Gdx.files.internal(textureFileNames[i]), i>0?false:true); + for (int i = 0; i < textureFileNames.length; i++) { + textures[i] = new Texture(Gdx.files.internal(textureFileNames[i]), i > 0 ? false : true); } } hasNormals = hasNormals(); - + model.getBoundingBox(bounds); float len = bounds.getDimensions().len(); - System.out.println("bounds: " + bounds); - + System.out.println("bounds: " + bounds); + cam = new PerspectiveCamera(60, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(bounds.getCenter().cpy().add(len / 2, len / 2, len / 2)); cam.lookAt(bounds.getCenter().x, bounds.getCenter().y, bounds.getCenter().z); cam.near = 0.1f; cam.far = 1000; - + renderer = new ImmediateModeRenderer10(); batch = new SpriteBatch(); - font = new BitmapFont(); + font = new BitmapFont(); } - - private boolean hasNormals() { - for(StillSubMesh mesh: model.subMeshes) { - if(mesh.mesh.getVertexAttribute(Usage.Normal) == null) return false; + + private boolean hasNormals () { + for (StillSubMesh mesh : model.subMeshes) { + if (mesh.mesh.getVertexAttribute(Usage.Normal) == null) return false; } return true; } - @Override public void resume () { - + @Override + public void resume () { + } float[] lightColor = {1, 1, 1, 0}; float[] lightPosition = {2, 5, 10, 0}; - @Override public void render () { + + @Override + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1.0f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); - Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); - + Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); + cam.update(); - cam.apply(Gdx.gl10); - - drawAxes(); - - if(hasNormals) { + cam.apply(Gdx.gl10); + + drawAxes(); + + if (hasNormals) { Gdx.gl.glEnable(GL10.GL_LIGHTING); Gdx.gl.glEnable(GL10.GL_COLOR_MATERIAL); Gdx.gl.glEnable(GL10.GL_LIGHT0); Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0); - Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); + Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); } - - if(textures != null) { - for(int i = 0; i < textures.length; i++) { + + if (textures != null) { + for (int i = 0; i < textures.length; i++) { Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0 + i); - Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); + Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); textures[i].bind(); - if(i > 0) { - switch(i) { - case 1: - setCombiners(GL11.GL_ADD_SIGNED); - break; - case 2: - setCombiners(GL10.GL_MODULATE); - break; - default: - setCombiners(GL10.GL_MODULATE); + if (i > 0) { + switch (i) { + case 1: + setCombiners(GL11.GL_ADD_SIGNED); + break; + case 2: + setCombiners(GL10.GL_MODULATE); + break; + default: + setCombiners(GL10.GL_MODULATE); } } } } - + angle += 45 * Gdx.graphics.getDeltaTime(); Gdx.gl10.glRotatef(angle, 0, 1, 0); model.render(); - - if(textures != null) { - for(int i = 0; i < textures.length; i++) { + + if (textures != null) { + for (int i = 0; i < textures.length; i++) { Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0 + i); - Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); + Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); } } - - if(hasNormals) { + + if (hasNormals) { Gdx.gl.glDisable(GL10.GL_LIGHTING); } - + batch.begin(); font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 20, 30); batch.end(); - + fps.log(); } - - private void setCombiners(int mod) { + + private void setCombiners (int mod) { Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_COMBINE); Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB, mod); Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC0_RGB, GL11.GL_PREVIOUS); - Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB, GL11.GL_TEXTURE); + Gdx.gl11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_SRC1_RGB, GL11.GL_TEXTURE); } - - private void drawAxes() { + + private void drawAxes () { float len = bounds.getDimensions().len(); renderer.begin(GL10.GL_LINES); renderer.color(1, 0, 0, 1); @@ -177,25 +182,30 @@ private void drawAxes() { Gdx.gl10.glColor4f(1, 1, 1, 1); } - @Override public void resize (int width, int height) { - + @Override + public void resize (int width, int height) { + + } + + @Override + public void pause () { + } - @Override public void pause () { - + @Override + public void dispose () { } - @Override public void dispose () { - } - - public static void main(String[] argv) { -// if(argv.length != 1 && argv.length != 2) { -// System.out.println("StillModelViewer ?"); -// System.exit(-1); -// } -// new JoglApplication(new StillModelViewer(argv[0], argv.length==2?argv[1]:null), "StillModel Viewer", 800, 480, false); -// new JoglApplication(new StillModelViewer("data/qbob/world_blobbie_brushes.g3dt", "data/qbob/world_blobbie_blocks.png"), "StillModel Viewer", 800, 480, false); - new JoglApplication(new StillModelViewer("data/multipleuvs.g3dt", "data/multipleuvs_1.png", "data/multipleuvs_2.png"), "StillModel Viewer", 800, 480, false); -// new JoglApplication(new StillModelViewer("data/head.obj"), "StillModel Viewer", 800, 480, false); + public static void main (String[] argv) { +// if(argv.length != 1 && argv.length != 2) { +// System.out.println("StillModelViewer ?"); +// System.exit(-1); +// } +// new JoglApplication(new StillModelViewer(argv[0], argv.length==2?argv[1]:null), "StillModel Viewer", 800, 480, false); +// new JoglApplication(new StillModelViewer("data/qbob/world_blobbie_brushes.g3dt", "data/qbob/world_blobbie_blocks.png"), +// "StillModel Viewer", 800, 480, false); + new JoglApplication(new StillModelViewer("data/multipleuvs.g3dt", "data/multipleuvs_1.png", "data/multipleuvs_2.png"), + "StillModel Viewer", 800, 480, false); +// new JoglApplication(new StillModelViewer("data/head.obj"), "StillModel Viewer", 800, 480, false); } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/Viewer.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/Viewer.java index 2a4eb67f7ed..37b6c6c79fd 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/Viewer.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/Viewer.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.test; import java.util.ArrayList; @@ -22,115 +23,120 @@ public class Viewer implements ApplicationListener { - public static void main(String[] argv) { + public static void main (String[] argv) { new JoglApplication(new Viewer(), "Viewer", 480, 320, false); } - static final int NUM_INSTANCES = 1; - SkeletonModel model; + static final int NUM_INSTANCES = 1; + SkeletonModel model; PerspectiveCamera cam; ImmediateModeRenderer10 renderer; float angle = 0; SpriteBatch batch; BitmapFont font; List animNames = new ArrayList(); - String animation; - float time = 0; + String animation; + float time = 0; int currAnimIdx = 0; - - @Override public void create () { - + + @Override + public void create () { + Texture texture = new Texture(Gdx.files.internal("data/ninja.jpg")); Material mat = new Material("mat", new TextureAttribute(texture, 0, "s_tex")); - model = new OgreXmlLoader().load(Gdx.files.internal("data/ninja.mesh.xml"), - Gdx.files.internal("data/ninja.skeleton.xml")); - model.setMaterial(mat); - + model = new OgreXmlLoader().load(Gdx.files.internal("data/ninja.mesh.xml"), Gdx.files.internal("data/ninja.skeleton.xml")); + model.setMaterial(mat); + cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); BoundingBox bounds = model.subMeshes[0].mesh.calculateBoundingBox(); cam.position.set(bounds.getCenter().cpy().add(100, 100, 100)); cam.lookAt(bounds.getCenter().x, bounds.getCenter().y, bounds.getCenter().z); cam.near = 0.1f; cam.far = 1000; - + renderer = new ImmediateModeRenderer10(); batch = new SpriteBatch(); font = new BitmapFont(); - - for(String name: model.skeleton.animations.keys()) + + for (String name : model.skeleton.animations.keys()) animNames.add(name); animation = animNames.get(0); - + } - @Override public void resume () { - + @Override + public void resume () { + } float[] lightColor = {1, 1, 1, 0}; float[] lightPosition = {2, 5, 10, 0}; - @Override public void render () { + + @Override + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); Gdx.gl.glEnable(GL10.GL_LIGHTING); Gdx.gl.glEnable(GL10.GL_COLOR_MATERIAL); - + cam.update(); cam.apply(Gdx.gl10); - + Gdx.gl.glEnable(GL10.GL_LIGHT0); Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightColor, 0); - Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); - - angle += 45 * Gdx.graphics.getDeltaTime(); + Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPosition, 0); + + angle += 45 * Gdx.graphics.getDeltaTime(); long processingTime = 0; - for(int i = 0; i < NUM_INSTANCES; i++) { -// Gdx.gl10.glPushMatrix(); -// Gdx.gl10.glTranslatef(0, 0, i * -50); -// Gdx.gl10.glRotatef(angle, 0, 1, 0); - model.setAnimation(animation, time, true); - model.render(); - -// Gdx.gl10.glPopMatrix(); + for (int i = 0; i < NUM_INSTANCES; i++) { +// Gdx.gl10.glPushMatrix(); +// Gdx.gl10.glTranslatef(0, 0, i * -50); +// Gdx.gl10.glRotatef(angle, 0, 1, 0); + model.setAnimation(animation, time, true); + model.render(); + +// Gdx.gl10.glPopMatrix(); } - + Gdx.gl.glDisable(GL10.GL_LIGHTING); Gdx.gl.glDisable(GL10.GL_DEPTH_TEST); - Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); + Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); renderSkeleton(); - + Gdx.app.log("Skinning", "took: " + processingTime / 1000000000.0f + " secs"); - + batch.begin(); - font.draw(batch, "Touch to switch Animation, Animation: " + animation +", FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 30); + font.draw(batch, "Touch to switch Animation, Animation: " + animation + ", FPS: " + Gdx.graphics.getFramesPerSecond(), 10, + 30); batch.end(); - - if(Gdx.input.justTouched()) { + + if (Gdx.input.justTouched()) { currAnimIdx++; - if(currAnimIdx == animNames.size()) currAnimIdx = 0; + if (currAnimIdx == animNames.size()) currAnimIdx = 0; animation = animNames.get(currAnimIdx); time = 0; } - + time += Gdx.graphics.getDeltaTime() / 10; - if(time > model.skeleton.animations.get(animation).totalDuration) { + if (time > model.skeleton.animations.get(animation).totalDuration) { time = 0; - } + } } - + Vector3 point1 = new Vector3(); Vector3 point2 = new Vector3(); + private void renderSkeleton () { renderer.begin(GL10.GL_LINES); for (int i = 0; i < model.skeleton.sceneMatrices.size; i++) { - SkeletonKeyframe joint = model.skeleton.bindPoseJoints.get(i); + SkeletonKeyframe joint = model.skeleton.bindPoseJoints.get(i); if (joint.parentIndex == -1) continue; point1.set(0, 0, 0).mul(model.skeleton.sceneMatrices.get(i)); point2.set(0, 0, 0).mul(model.skeleton.sceneMatrices.get(joint.parentIndex)); - + renderer.color(1, 1, 1, 1); renderer.vertex(point1); renderer.color(1, 1, 1, 1); @@ -138,17 +144,20 @@ private void renderSkeleton () { } renderer.end(); } - - @Override public void resize (int width, int height) { + + @Override + public void resize (int width, int height) { } - @Override public void pause () { + @Override + public void pause () { // TODO Auto-generated method stub - + } - @Override public void dispose () { + @Override + public void dispose () { // TODO Auto-generated method stub - + } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/WolfensteinTest.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/WolfensteinTest.java index 2db5aa37ff8..a05100d928f 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/WolfensteinTest.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/WolfensteinTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.test; import com.badlogic.gdx.ApplicationListener; @@ -18,7 +19,7 @@ import com.badlogic.gdx.math.collision.Ray; public class WolfensteinTest implements ApplicationListener { - public static void main(String[] argv) { + public static void main (String[] argv) { new JoglApplication(new WolfensteinTest(), "Wolfenstein", 480, 320, false); } @@ -28,69 +29,70 @@ public static void main(String[] argv) { Texture texture; float[] triangles; short[] indices; - + @Override - public void create() { + public void create () { model = ModelLoaderRegistry.loadStillModel(Gdx.files.internal("data/level.g3dt")); texture = new Texture(Gdx.files.internal("data/wall.png"), true); texture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat); model.setMaterial(new Material("mat", new TextureAttribute(texture, 0, "a_texCoord"))); - + triangles = new float[model.subMeshes[0].mesh.getNumVertices() * model.subMeshes[0].mesh.getVertexSize() / 4]; indices = new short[model.subMeshes[0].mesh.getNumIndices()]; - + model.subMeshes[0].mesh.getVertices(triangles); model.subMeshes[0].mesh.getIndices(indices); - - camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + + camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.position.y = 1; - + renderer = new ImmediateModeRenderer10(); } - + Vector3 movement = new Vector3(); Vector3 intersection = new Vector3(); Ray ray = new Ray(new Vector3(), new Vector3()); - private void processInput() { movement.set(0, 0, 0); - - if(Gdx.input.isKeyPressed(Keys.W)) { + + private void processInput () { + movement.set(0, 0, 0); + + if (Gdx.input.isKeyPressed(Keys.W)) { movement.add(camera.direction.tmp().mul(Gdx.graphics.getDeltaTime())); } - - if(Gdx.input.isKeyPressed(Keys.S)) { + + if (Gdx.input.isKeyPressed(Keys.S)) { movement.add(camera.direction.tmp().mul(-Gdx.graphics.getDeltaTime())); } - - if(Gdx.input.isKeyPressed(Keys.A)) { + + if (Gdx.input.isKeyPressed(Keys.A)) { camera.rotate(20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); } - - if(Gdx.input.isKeyPressed(Keys.D)) { + + if (Gdx.input.isKeyPressed(Keys.D)) { camera.rotate(-20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); } - + movement.mul(2); camera.position.add(movement); - + ray.origin.set(camera.position); ray.direction.set(camera.direction); - - if(Intersector.intersectRayTriangles(ray, triangles, indices, model.subMeshes[0].mesh.getVertexSize() / 4, intersection)) { + + if (Intersector.intersectRayTriangles(ray, triangles, indices, model.subMeshes[0].mesh.getVertexSize() / 4, intersection)) { Gdx.app.log("wolf", "intersected wall: " + intersection); } } - @Override - public void render() { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); - + camera.update(); camera.apply(Gdx.gl10); model.render(); - + Gdx.gl.glDisable(GL10.GL_DEPTH_TEST); Gdx.gl10.glPointSize(5); renderer.begin(GL10.GL_POINTS); @@ -99,26 +101,26 @@ public void render() { renderer.end(); Gdx.gl10.glPointSize(1); Gdx.gl10.glColor4f(1, 1, 1, 1); - + processInput(); } - + @Override - public void resume() { - + public void resume () { + } @Override - public void resize(int width, int height) { - + public void resize (int width, int height) { + } @Override - public void pause() { - + public void pause () { + } @Override - public void dispose() { + public void dispose () { } } diff --git a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/utils/PerspectiveCamController.java b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/utils/PerspectiveCamController.java index 575c42ce3f3..72676e72528 100644 --- a/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/utils/PerspectiveCamController.java +++ b/extensions/model-loaders/model-loaders/src/com/badlogic/gdx/graphics/g3d/test/utils/PerspectiveCamController.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.test.utils; import com.badlogic.gdx.InputAdapter; @@ -10,19 +11,20 @@ public class PerspectiveCamController extends InputAdapter { final PerspectiveCamera camera; final Vector3 curr = new Vector3(); - final Vector3 last = new Vector3(-1, -1, -1); + final Vector3 last = new Vector3(-1, -1, -1); final Vector3 delta = new Vector3(); - final Plane plane = new Plane(new Vector3(0,0,1), 0); - - public PerspectiveCamController(PerspectiveCamera camera) { + final Plane plane = new Plane(new Vector3(0, 0, 1), 0); + + public PerspectiveCamController (PerspectiveCamera camera) { this.camera = camera; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { Ray ray = camera.getPickRay(x, y); Intersector.intersectRayPlane(ray, plane, curr); - - if(!(last.x == -1 && last.y == -1 && last.z == -1)) { + + if (!(last.x == -1 && last.y == -1 && last.z == -1)) { ray = camera.getPickRay(last.x, last.y); Intersector.intersectRayPlane(ray, plane, delta); delta.sub(curr); @@ -31,8 +33,9 @@ public PerspectiveCamController(PerspectiveCamera camera) { last.set(x, y, 0); return false; } - - @Override public boolean touchUp(int x, int y, int pointer, int button) { + + @Override + public boolean touchUp (int x, int y, int pointer, int button) { last.set(-1, -1, -1); return false; } diff --git a/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TileSetLayout.java b/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TileSetLayout.java index 526e6d7ce49..08b52c634f3 100644 --- a/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TileSetLayout.java +++ b/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TileSetLayout.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tiledmappacker; import java.awt.image.BufferedImage; @@ -25,10 +26,8 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.IntMap; -/** - * Contains extra information that can only be calculated after a Tiled Map's tile set images are loaded. - * @author David Fraska - * */ +/** Contains extra information that can only be calculated after a Tiled Map's tile set images are loaded. + * @author David Fraska */ public class TileSetLayout extends TileSet { public final BufferedImage image; @@ -37,12 +36,10 @@ public class TileSetLayout extends TileSet { private int numCols; public final int numTiles; - /** - * Constructs a Tile Set layout. The tile set image contained in the baseDir should be the original tile set images before + /** Constructs a Tile Set layout. The tile set image contained in the baseDir should be the original tile set images before * being processed by {@link TiledMapPacker} (the ones actually read by Tiled). * @param tileSet the tile set to process - * @param baseDir the directory in which the tile set image is stored - * */ + * @param baseDir the directory in which the tile set image is stored */ protected TileSetLayout (TileSet tileSet, FileHandle baseDir) throws IOException { super(tileSet); diff --git a/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TiledMapPacker.java b/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TiledMapPacker.java index 3b076bef194..7f0c2ef0583 100644 --- a/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TiledMapPacker.java +++ b/extensions/tiled-preprocessor/src/com/badlogic/gdx/tiledmappacker/TiledMapPacker.java @@ -45,19 +45,14 @@ import com.badlogic.gdx.graphics.g2d.tiled.TileAtlas; import com.badlogic.gdx.graphics.g2d.tiled.TileMapRenderer; import com.badlogic.gdx.graphics.g2d.tiled.TileSet; -import com.badlogic.gdx.graphics.g2d.tiled.TiledLayer; import com.badlogic.gdx.graphics.g2d.tiled.TiledLoader; import com.badlogic.gdx.graphics.g2d.tiled.TiledMap; -import com.badlogic.gdx.imagepacker.TexturePacker; -import com.badlogic.gdx.imagepacker.TexturePacker.Settings; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Packs a Tiled Map, adding some properties to improve the speed of the {@link TileMapRenderer}. Also runs the texture packer on +/** Packs a Tiled Map, adding some properties to improve the speed of the {@link TileMapRenderer}. Also runs the texture packer on * the tiles for use with a {@link TileAtlas} - * @author David Fraska - */ + * @author David Fraska */ public class TiledMapPacker { private TexturePacker packer; @@ -73,7 +68,8 @@ static private class TmxFilter implements FilenameFilter { public TmxFilter () { } - @Override public boolean accept (File dir, String name) { + @Override + public boolean accept (File dir, String name) { if (name.endsWith(".tmx")) return true; return false; @@ -81,8 +77,7 @@ public TmxFilter () { } - /** - * Typically, you should run the {@link TiledMapPacker#main(String[])} method instead of this method. Packs a directory of + /** Typically, you should run the {@link TiledMapPacker#main(String[])} method instead of this method. Packs a directory of * Tiled Maps, adding properties to improve the speed of the {@link TileMapRenderer}. Also runs the texture packer on the tile * sets for use with a {@link TileAtlas} * @param inputDir the input directory containing the tmx files (and tile sets, relative to the path listed in the tmx file) @@ -90,8 +85,7 @@ public TmxFilter () { * "../" in the path of your tile sets! The output for these tile sets will be relative to the output directory. For * example, if your output directory is "C:\mydir\maps" and you have a tileset with the path "../tileset.png", the * tileset will be output to "C:\mydir\" and the maps will be in "C:\mydir\maps". - * @param settings the settings used in the TexturePacker - * */ + * @param settings the settings used in the TexturePacker */ public void processMap (File inputDir, File outputDir, Settings settings) throws IOException { FileHandle inputDirHandle = Gdx.files.absolute(inputDir.getAbsolutePath()); File[] files = inputDir.listFiles(new TmxFilter()); @@ -261,10 +255,8 @@ private static Node getFirstChildNodeByName (Node parent, String child) { return parent.appendChild(newNode); } - /** - * If the child node or attribute doesn't exist, it is created. Usage example: Node property = - * getFirstChildByAttrValue(properties, "property", "name", "blended tiles"); - */ + /** If the child node or attribute doesn't exist, it is created. Usage example: Node property = + * getFirstChildByAttrValue(properties, "property", "name", "blended tiles"); */ private static Node getFirstChildByNameAttrValue (Node node, String childName, String attr, String value) { NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { @@ -316,14 +308,12 @@ private TileSetLayout getTileSetLayout (int tileNum, FileHandle inputDirHandle) return null; } - /** - * Processes a directory of Tile Maps, compressing each tile set contained in any map once. + /** Processes a directory of Tile Maps, compressing each tile set contained in any map once. * @param args args[0]: the input directory containing the tmx files (and tile sets, relative to the path listed in the tmx * file). args[1]: The output directory for the tmx files, should be empty before running. WARNING: Use caution if * you have a "../" in the path of your tile sets! The output for these tile sets will be relative to the output * directory. For example, if your output directory is "C:\mydir\output" and you have a tileset with the path - * "../tileset.png", the tileset will be output to "C:\mydir\" and the maps will be in "C:\mydir\output". - */ + * "../tileset.png", the tileset will be output to "C:\mydir\" and the maps will be in "C:\mydir\output". */ public static void main (String[] args) { File tmxFile, inputDir, outputDir; @@ -335,22 +325,28 @@ public static void main (String[] args) { // Create a new JoglApplication so that Gdx stuff works properly new JoglApplication(new ApplicationListener() { - @Override public void create () { + @Override + public void create () { } - @Override public void dispose () { + @Override + public void dispose () { } - @Override public void pause () { + @Override + public void pause () { } - @Override public void render () { + @Override + public void render () { } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } - @Override public void resume () { + @Override + public void resume () { } }, "", 0, 0, false); diff --git a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/ButtonTestAndroid.java b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/ButtonTestAndroid.java index 18d95ea3c39..66587937df5 100644 --- a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/ButtonTestAndroid.java +++ b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/ButtonTestAndroid.java @@ -1,15 +1,14 @@ + package com.badlogic.gdx.twl; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class ButtonTestAndroid extends AndroidApplication -{ +public class ButtonTestAndroid extends AndroidApplication { @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize(new com.badlogic.gdx.twl.tests.ButtonTest(), false); } -} \ No newline at end of file +} diff --git a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/NodeTestAndroid.java b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/NodeTestAndroid.java index e22c4da6e32..22e6f882896 100644 --- a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/NodeTestAndroid.java +++ b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/NodeTestAndroid.java @@ -1,14 +1,13 @@ + package com.badlogic.gdx.twl; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; -public class NodeTestAndroid extends AndroidApplication -{ +public class NodeTestAndroid extends AndroidApplication { @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize(new com.badlogic.gdx.twl.tests.nodes.NodeTest(false, 10), false); } diff --git a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTestAndroid.java b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTestAndroid.java index ae11147131b..d5e2ff0c2a9 100644 --- a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTestAndroid.java +++ b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TextAreaTestAndroid.java @@ -13,17 +13,16 @@ * 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 TextAreaTestAndroid extends AndroidApplication -{ - public void onCreate (Bundle bundle) - { +public class TextAreaTestAndroid extends AndroidApplication { + public void onCreate (Bundle bundle) { super.onCreate(bundle); initialize(new com.badlogic.gdx.twl.tests.TextAreaTest(), false); } -} \ No newline at end of file +} diff --git a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TwlTestActivity.java b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TwlTestActivity.java index 9e3f141f587..b269b85f603 100644 --- a/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TwlTestActivity.java +++ b/extensions/twl/gdx-twl-tests-android/src/com/badlogic/gdx/twl/TwlTestActivity.java @@ -1,6 +1,7 @@ /** * */ + package com.badlogic.gdx.twl; import android.app.Activity; @@ -9,52 +10,44 @@ import android.view.View; import android.widget.Button; -/** - * @author Kurtis Kopf - */ -public class TwlTestActivity extends Activity -{ +/** @author Kurtis Kopf */ +public class TwlTestActivity extends Activity { - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); - + Button twlButton = (Button)findViewById(R.id.button1); - twlButton.setOnClickListener(new View.OnClickListener() - { + twlButton.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { - Intent myIntent = new Intent(v.getContext(),ButtonTestAndroid.class); + public void onClick (View v) { + Intent myIntent = new Intent(v.getContext(), ButtonTestAndroid.class); startActivityForResult(myIntent, 0); } }); - + Button twlTextArea = (Button)findViewById(R.id.button2); - twlTextArea.setOnClickListener(new View.OnClickListener() - { + twlTextArea.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { - Intent myIntent = new Intent(v.getContext(),TextAreaTestAndroid.class); + public void onClick (View v) { + Intent myIntent = new Intent(v.getContext(), TextAreaTestAndroid.class); startActivityForResult(myIntent, 0); } }); - + Button twlNode = (Button)findViewById(R.id.button3); - twlNode.setOnClickListener(new View.OnClickListener() - { + twlNode.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { - Intent myIntent = new Intent(v.getContext(),NodeTestAndroid.class); + public void onClick (View v) { + Intent myIntent = new Intent(v.getContext(), NodeTestAndroid.class); startActivityForResult(myIntent, 0); } }); } -} \ No newline at end of file +} diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTest.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTest.java index b6c602b2cde..72453fecd05 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTest.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl.tests; import com.badlogic.gdx.ApplicationListener; @@ -32,7 +33,8 @@ public class ButtonTest implements ApplicationListener, InputProcessor { private TWL twl; private InputMultiplexer input = new InputMultiplexer(); - @Override public void create () { + @Override + public void create () { Button button = new Button("Click Me"); FPSCounter fpsCounter = new FPSCounter(4, 2); @@ -48,22 +50,27 @@ public class ButtonTest implements ApplicationListener, InputProcessor { Gdx.input.setInputProcessor(input); } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } - @Override public void render () { + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); twl.render(); } - @Override public void dispose () { + @Override + public void dispose () { twl.dispose(); } - @Override public void pause () { + @Override + public void pause () { } - @Override public void resume () { + @Override + public void resume () { } public boolean keyDown (int keycode) { @@ -91,11 +98,13 @@ public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTestDesktop.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTestDesktop.java index afea0ee6c94..63dc59b46ad 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTestDesktop.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/ButtonTestDesktop.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl.tests; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTest.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTest.java index 7647264bf2d..361c29f5b8d 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTest.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl.tests; import com.badlogic.gdx.ApplicationListener; @@ -36,7 +37,8 @@ public class TextAreaTest implements ApplicationListener { TWL twl; - @Override public void create () { + @Override + public void create () { final HTMLTextAreaModel htmlText = new HTMLTextAreaModel(); TextArea textArea = new TextArea(htmlText); htmlText @@ -84,21 +86,26 @@ public void run () { Gdx.input.setInputProcessor(twl); } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } - @Override public void render () { + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); twl.render(); } - @Override public void dispose () { + @Override + public void dispose () { twl.dispose(); } - @Override public void pause () { + @Override + public void pause () { } - @Override public void resume () { + @Override + public void resume () { } } diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTestDesktop.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTestDesktop.java index c853535a8a5..7767d7f92e2 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTestDesktop.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/TextAreaTestDesktop.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl.tests; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Connection.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Connection.java index 25b5c49c552..6318f14f813 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Connection.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Connection.java @@ -27,51 +27,49 @@ * 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.twl.tests.nodes; -/** - * - * @author Matthias Mann - */ +/** @author Matthias Mann */ public class Connection { - private final Pad source; - private final Pad destination; + private final Pad source; + private final Pad destination; + + public Connection (Pad source, Pad destination) { + if (source == null) { + throw new NullPointerException("source"); + } + if (destination == null) { + throw new NullPointerException("dest"); + } + this.source = source; + this.destination = destination; + } - public Connection(Pad source, Pad destination) { - if(source == null) { - throw new NullPointerException("source"); - } - if(destination == null) { - throw new NullPointerException("dest"); - } - this.source = source; - this.destination = destination; - } + public Pad getDestination () { + return destination; + } - public Pad getDestination() { - return destination; - } + public Pad getSource () { + return source; + } - public Pad getSource() { - return source; - } + @Override + public boolean equals (Object obj) { + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final Connection other = (Connection)obj; + return (this.source == other.source) && (this.destination == other.destination); + } - @Override - public boolean equals(Object obj) { - if(obj == null || getClass() != obj.getClass()) { - return false; - } - final Connection other = (Connection)obj; - return (this.source == other.source) && (this.destination == other.destination); - } + @Override + public int hashCode () { + int hash = 7; + hash = 79 * hash + System.identityHashCode(this.source); + hash = 79 * hash + System.identityHashCode(this.destination); + return hash; + } - @Override - public int hashCode() { - int hash = 7; - hash = 79 * hash + System.identityHashCode(this.source); - hash = 79 * hash + System.identityHashCode(this.destination); - return hash; - } - } diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Node.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Node.java index 096d65d18d0..718adb3e8e8 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Node.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Node.java @@ -27,68 +27,67 @@ * 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.twl.tests.nodes; -import de.matthiasmann.twl.ResizableFrame; import java.util.ArrayList; -/** - * - * @author Matthias Mann - */ +import de.matthiasmann.twl.ResizableFrame; + +/** @author Matthias Mann */ public class Node extends ResizableFrame { - private final NodeArea nodeArea; - private final ArrayList pads; + private final NodeArea nodeArea; + private final ArrayList pads; + + public Node (NodeArea nodeArea) { + this.nodeArea = nodeArea; + this.pads = new ArrayList(); + } - public Node(NodeArea nodeArea) { - this.nodeArea = nodeArea; - this.pads = new ArrayList(); - } + public NodeArea getNodeArea () { + return nodeArea; + } - public NodeArea getNodeArea() { - return nodeArea; - } + public Pad addPad (String name, boolean input) { + Pad pad = new Pad(this, input); + pad.setTooltipContent(name); + pads.add(pad); + add(pad); + return pad; + } - public Pad addPad(String name, boolean input) { - Pad pad = new Pad(this, input); - pad.setTooltipContent(name); - pads.add(pad); - add(pad); - return pad; - } + public Pad padFromMouse (int x, int y) { + for (int i = 0, n = pads.size(); i < n; i++) { + Pad pad = pads.get(i); + if (pad.isInside(x, y)) { + return pad; + } + } + return null; + } - public Pad padFromMouse(int x, int y) { - for(int i=0,n=pads.size() ; i nodes; - private final ArrayList connections; - private final float[] bezierPoints; - private final Label infoText; - - private Pad newConnectionPad; - private int newConnectionX; - private int newConnectionY; - - private boolean doubleClick = true; - - public NodeArea(boolean doubleClick) { - this.doubleClick = doubleClick; - this.nodes = new ArrayList(); - this.connections = new ArrayList(); - this.bezierPoints = new float[NUM_BEZIER_POINTS*2]; - this.infoText = new Label((doubleClick ? "Double click" : "Click") + " to create new nodes, then drag pads onto other pads to make connections"); - - add(infoText); - } - - public Node addNode(String name) { - Node node = new Node(this); - node.setTitle(name); - nodes.add(node); - add(node); - return node; - } - - public Pad padFromMouse(int x, int y) { - for(int i=nodes.size() ; i-->0 ;) { - Node node = nodes.get(i); - - if(node.isInside(x, y)) { - return node.padFromMouse(x, y); - } - } - return null; - } - - public void addConnection(Pad src, Pad dest) { - if(!dest.isInput() || src.isInput() || src.getNode() == dest.getNode()) { - return; - } - Connection c = dest.getInConnection(); - if(c != null) { - connections.remove(c); - } - - c = new Connection(src, dest); - connections.add(c); - dest.setInConnection(c); - } - - public void removeConnection(Connection connection) { - connections.remove(connection); - } - - public void dragNewConnection(Pad source, int x, int y) { - this.newConnectionPad = source; - this.newConnectionX = x; - this.newConnectionY = y; - } - - @Override - protected boolean handleEvent(Event evt) { - if(super.handleEvent(evt)) { - return true; - } - - if(evt.getType() == Event.Type.MOUSE_CLICKED) { - if(!doubleClick || evt.getMouseClickCount() == 2) { - Random r = new Random(); - Node node = addNode("Node " + (1+r.nextInt(100))); - for(int i=0,n=r.nextInt(3) ; i<=n ; i++) { - node.addPad("Input " + (i+1), true); - } - for(int i=0,n=r.nextInt(2) ; i<=n ; i++) { - node.addPad("Output " + (i+1), false); - } - node.adjustSize(); - //System.out.println("clicked at " + evt.getMouseX() + "," + evt.getMouseY()); - node.setPosition( - evt.getMouseX() - node.getWidth()/2, - evt.getMouseY()); - } - } - - return evt.isMouseEventNoWheel(); - } - - @Override - protected void layout() { - infoText.adjustSize(); - infoText.setPosition( - getInnerX()+(getInnerWidth()-infoText.getWidth())/2, - getInnerY()); - } - - @Override - protected void paintWidget(GUI gui) { - LineRenderer lineRenderer = gui.getRenderer().getLineRenderer(); - if(lineRenderer != null) { - for(int i=0,n=connections.size() ; i nodes; + private final ArrayList connections; + private final float[] bezierPoints; + private final Label infoText; + + private Pad newConnectionPad; + private int newConnectionX; + private int newConnectionY; + + private boolean doubleClick = true; + + public NodeArea (boolean doubleClick) { + this.doubleClick = doubleClick; + this.nodes = new ArrayList(); + this.connections = new ArrayList(); + this.bezierPoints = new float[NUM_BEZIER_POINTS * 2]; + this.infoText = new Label((doubleClick ? "Double click" : "Click") + + " to create new nodes, then drag pads onto other pads to make connections"); + + add(infoText); + } + + public Node addNode (String name) { + Node node = new Node(this); + node.setTitle(name); + nodes.add(node); + add(node); + return node; + } + + public Pad padFromMouse (int x, int y) { + for (int i = nodes.size(); i-- > 0;) { + Node node = nodes.get(i); + + if (node.isInside(x, y)) { + return node.padFromMouse(x, y); + } + } + return null; + } + + public void addConnection (Pad src, Pad dest) { + if (!dest.isInput() || src.isInput() || src.getNode() == dest.getNode()) { + return; + } + Connection c = dest.getInConnection(); + if (c != null) { + connections.remove(c); + } + + c = new Connection(src, dest); + connections.add(c); + dest.setInConnection(c); + } + + public void removeConnection (Connection connection) { + connections.remove(connection); + } + + public void dragNewConnection (Pad source, int x, int y) { + this.newConnectionPad = source; + this.newConnectionX = x; + this.newConnectionY = y; + } + + @Override + protected boolean handleEvent (Event evt) { + if (super.handleEvent(evt)) { + return true; + } + + if (evt.getType() == Event.Type.MOUSE_CLICKED) { + if (!doubleClick || evt.getMouseClickCount() == 2) { + Random r = new Random(); + Node node = addNode("Node " + (1 + r.nextInt(100))); + for (int i = 0, n = r.nextInt(3); i <= n; i++) { + node.addPad("Input " + (i + 1), true); + } + for (int i = 0, n = r.nextInt(2); i <= n; i++) { + node.addPad("Output " + (i + 1), false); + } + node.adjustSize(); + // System.out.println("clicked at " + evt.getMouseX() + "," + evt.getMouseY()); + node.setPosition(evt.getMouseX() - node.getWidth() / 2, evt.getMouseY()); + } + } + + return evt.isMouseEventNoWheel(); + } + + @Override + protected void layout () { + infoText.adjustSize(); + infoText.setPosition(getInnerX() + (getInnerWidth() - infoText.getWidth()) / 2, getInnerY()); + } + + @Override + protected void paintWidget (GUI gui) { + LineRenderer lineRenderer = gui.getRenderer().getLineRenderer(); + if (lineRenderer != null) { + for (int i = 0, n = connections.size(); i < n; i++) { + Connection c = connections.get(i); + drawCurve(lineRenderer, c.getSource().getCenterX(), c.getSource().getCenterY(), c.getDestination().getCenterX(), c + .getDestination().getCenterY(), +1, -1, Color.GRAY); + } + + if (newConnectionPad != null) { + drawCurve(lineRenderer, newConnectionPad.getCenterX(), newConnectionPad.getCenterY(), newConnectionX, newConnectionY, + newConnectionPad.isInput() ? -1 : +1, newConnectionPad.isInput() ? +1 : -1, Color.RED); + } + } + } + + private void drawCurve (LineRenderer lineRenderer, int x0, int y0, int x1, int y1, int dir0, int dir1, Color color) { + float xM = Math.abs(x1 - x0) * 0.5f; + + computeBezierCurve(x0, x0 + xM * dir0, x1 + xM * dir1, x1, bezierPoints, 0, NUM_BEZIER_POINTS); + computeBezierCurve(y0, y0, y1, y1, bezierPoints, 1, NUM_BEZIER_POINTS); + + lineRenderer.drawLine(bezierPoints, NUM_BEZIER_POINTS, 2.0f, color, false); + } + + private void computeBezierCurve (float q0, float q1, float q2, float q3, float[] dst, int off, int cnt) { + float f = cnt - 1; + float ff = f * f; + float fff = f * ff; + float rt1 = 3.0f * (q1 - q0) / f; + float rt2 = 3.0f * (q0 - 2.0f * q1 + q2) / ff; + float rt3 = (q3 - q0 + 3.0f * (q1 - q2)) / fff; + + q1 = rt1 + rt2 + rt3; + q2 = 2 * rt2 + 6 * rt3; + q3 = 6 * rt3; + + for (int i = 0; i < cnt; i++) { + dst[off + i * 2] = q0; + q0 += q1; + q1 += q2; + q2 += q3; + } + } } diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTest.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTest.java index 7cc29ea212c..c5be2f6f039 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTest.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTest.java @@ -1,87 +1,82 @@ -package com.badlogic.gdx.twl.tests.nodes; -import java.nio.FloatBuffer; +package com.badlogic.gdx.twl.tests.nodes; import com.badlogic.gdx.ApplicationListener; +import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.InputProcessor; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.GL10; -import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.twl.TWL; -import com.badlogic.gdx.utils.BufferUtils; import de.matthiasmann.twl.ScrollPane; -public class NodeTest implements ApplicationListener, InputProcessor -{ +public class NodeTest implements ApplicationListener, InputProcessor { private TWL twl; private InputMultiplexer input = new InputMultiplexer(); - + private NodeArea nodeArea; private Node nodeSource; private Node nodeSink; - + private boolean doubleClick = true; - - public NodeTest(boolean doubleClick, int radius) - { + + public NodeTest (boolean doubleClick, int radius) { super(); this.doubleClick = doubleClick; Pad.RADIUS = radius; } - + @Override - public void create() - { + public void create () { nodeArea = new NodeArea(doubleClick); - ScrollPane scrollPane = new ScrollPane(nodeArea); - scrollPane.setExpandContentSize(true); - - SpriteBatch batch = new SpriteBatch(); + ScrollPane scrollPane = new ScrollPane(nodeArea); + scrollPane.setExpandContentSize(true); + + SpriteBatch batch = new SpriteBatch(); twl = new TWL(batch, "data/nodes.xml", FileType.Internal, scrollPane); input.addProcessor(twl); input.addProcessor(this); Gdx.input.setInputProcessor(twl); - + nodeSource = nodeArea.addNode("Source"); Pad nodeSourceColor = nodeSource.addPad("Output 1", false); - Pad nodeSourceAlpha = nodeSource.addPad("Alpha", false); - - nodeSink = nodeArea.addNode("Sink"); - Pad nodeSinkColor = nodeSink.addPad("Input 1", true); - nodeArea.addConnection(nodeSourceColor, nodeSinkColor); + Pad nodeSourceAlpha = nodeSource.addPad("Alpha", false); + + nodeSink = nodeArea.addNode("Sink"); + Pad nodeSinkColor = nodeSink.addPad("Input 1", true); + nodeArea.addConnection(nodeSourceColor, nodeSinkColor); } + @Override - public void resume() - { + public void resume () { } + @Override - public void render() - { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); twl.render(); } + @Override - public void resize(int width, int height) - { - nodeSource.setPosition((int)(width * 0.2f), (int)(height * 0.3f)); - nodeSource.adjustSize(); + public void resize (int width, int height) { + nodeSource.setPosition((int)(width * 0.2f), (int)(height * 0.3f)); + nodeSource.adjustSize(); - nodeSink.setPosition((int)(width * 0.75f), (int)(height * 0.6f)); - nodeSink.adjustSize(); + nodeSink.setPosition((int)(width * 0.75f), (int)(height * 0.6f)); + nodeSink.adjustSize(); } + @Override - public void pause() - { + public void pause () { } + @Override - public void dispose() - { + public void dispose () { twl.dispose(); } + public boolean keyDown (int keycode) { return false; } @@ -107,11 +102,13 @@ public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTestDesktop.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTestDesktop.java index 3be0c54fd4b..907147b319c 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTestDesktop.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/NodeTestDesktop.java @@ -1,11 +1,10 @@ + package com.badlogic.gdx.twl.tests.nodes; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; -public class NodeTestDesktop -{ - public static void main (String[] argv) - { +public class NodeTestDesktop { + public static void main (String[] argv) { new LwjglApplication(new NodeTest(true, 5), "Node Test", 1024, 600, false); } } diff --git a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Pad.java b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Pad.java index aa89a261e25..070782c7cd6 100644 --- a/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Pad.java +++ b/extensions/twl/gdx-twl-tests/src/com/badlogic/gdx/twl/tests/nodes/Pad.java @@ -27,125 +27,123 @@ * 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.twl.tests.nodes; import de.matthiasmann.twl.Event; import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.renderer.AnimationState.StateKey; -/** - * - * @author Matthias Mann - */ +/** @author Matthias Mann */ public class Pad extends Widget { - public static final StateKey STATE_HOVER = StateKey.get("hover"); - public static final StateKey STATE_DRAG_DESTINATION = StateKey.get("dragDestination"); - - public static int RADIUS = 5; - - private final Node node; - private final boolean input; - private Connection inConnection; - - private boolean isDragActive; - private Pad dragDestinationPad; - - public Pad(Node node, boolean input) { - this.node = node; - this.input = input; - } - - public Node getNode() { - return node; - } - - public boolean isInput() { - return input; - } - - public Connection getInConnection() { - return inConnection; - } - - public void setInConnection(Connection inConnection) { - this.inConnection = inConnection; - } - - @Override - protected boolean handleEvent(Event evt) { - if(evt.isMouseEvent()) { - getAnimationState().setAnimationState(STATE_HOVER, evt.getType() != Event.Type.MOUSE_EXITED); - } - - if(evt.getType() == Event.Type.MOUSE_DRAGGED) { - NodeArea nodeArea = node.getNodeArea(); - - if(!isDragActive) { - isDragActive = true; - - if(isInput()) { - nodeArea.removeConnection(getInConnection()); - } - } - - nodeArea.dragNewConnection(this, evt.getMouseX(), evt.getMouseY()); - - Pad pad = nodeArea.padFromMouse(evt.getMouseX(), evt.getMouseY()); - setDragDestPad(pad); - } - - if(isDragActive && evt.isMouseDragEnd()) { - NodeArea nodeArea = node.getNodeArea(); - if(dragDestinationPad != null) { - if(isInput()) { - nodeArea.addConnection(dragDestinationPad, this); - } else { - nodeArea.addConnection(this, dragDestinationPad); - } - } - setDragDestPad(null); - nodeArea.dragNewConnection(null, 0, 0); - isDragActive = false; - } - - return evt.isMouseEventNoWheel(); - } - - @Override - public int getPreferredHeight() { - return RADIUS*2; - } - - @Override - public int getPreferredWidth() { - return RADIUS*2; - } - - public int getCenterX() { - return getX() + RADIUS; - } - - public int getCenterY() { - return getY() + RADIUS; - } - - @Override - public boolean isInside(int x, int y) { - int dx = x - getCenterX(); - int dy = y - getCenterY(); - return dx*dx + dy*dy <= RADIUS*RADIUS; - } - - private void setDragDestPad(Pad pad) { - if(pad != dragDestinationPad) { - if(dragDestinationPad != null) { - dragDestinationPad.getAnimationState().setAnimationState(STATE_DRAG_DESTINATION, false); - } - dragDestinationPad = pad; - if(dragDestinationPad != null) { - dragDestinationPad.getAnimationState().setAnimationState(STATE_DRAG_DESTINATION, true); - } - } - } + public static final StateKey STATE_HOVER = StateKey.get("hover"); + public static final StateKey STATE_DRAG_DESTINATION = StateKey.get("dragDestination"); + + public static int RADIUS = 5; + + private final Node node; + private final boolean input; + private Connection inConnection; + + private boolean isDragActive; + private Pad dragDestinationPad; + + public Pad (Node node, boolean input) { + this.node = node; + this.input = input; + } + + public Node getNode () { + return node; + } + + public boolean isInput () { + return input; + } + + public Connection getInConnection () { + return inConnection; + } + + public void setInConnection (Connection inConnection) { + this.inConnection = inConnection; + } + + @Override + protected boolean handleEvent (Event evt) { + if (evt.isMouseEvent()) { + getAnimationState().setAnimationState(STATE_HOVER, evt.getType() != Event.Type.MOUSE_EXITED); + } + + if (evt.getType() == Event.Type.MOUSE_DRAGGED) { + NodeArea nodeArea = node.getNodeArea(); + + if (!isDragActive) { + isDragActive = true; + + if (isInput()) { + nodeArea.removeConnection(getInConnection()); + } + } + + nodeArea.dragNewConnection(this, evt.getMouseX(), evt.getMouseY()); + + Pad pad = nodeArea.padFromMouse(evt.getMouseX(), evt.getMouseY()); + setDragDestPad(pad); + } + + if (isDragActive && evt.isMouseDragEnd()) { + NodeArea nodeArea = node.getNodeArea(); + if (dragDestinationPad != null) { + if (isInput()) { + nodeArea.addConnection(dragDestinationPad, this); + } else { + nodeArea.addConnection(this, dragDestinationPad); + } + } + setDragDestPad(null); + nodeArea.dragNewConnection(null, 0, 0); + isDragActive = false; + } + + return evt.isMouseEventNoWheel(); + } + + @Override + public int getPreferredHeight () { + return RADIUS * 2; + } + + @Override + public int getPreferredWidth () { + return RADIUS * 2; + } + + public int getCenterX () { + return getX() + RADIUS; + } + + public int getCenterY () { + return getY() + RADIUS; + } + + @Override + public boolean isInside (int x, int y) { + int dx = x - getCenterX(); + int dy = y - getCenterY(); + return dx * dx + dy * dy <= RADIUS * RADIUS; + } + + private void setDragDestPad (Pad pad) { + if (pad != dragDestinationPad) { + if (dragDestinationPad != null) { + dragDestinationPad.getAnimationState().setAnimationState(STATE_DRAG_DESTINATION, false); + } + dragDestinationPad = pad; + if (dragDestinationPad != null) { + dragDestinationPad.getAnimationState().setAnimationState(STATE_DRAG_DESTINATION, true); + } + } + } } diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/Layout.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/Layout.java index 0734b8e1c59..55b9cc430be 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/Layout.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/Layout.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl; import de.matthiasmann.twl.Alignment; @@ -20,10 +21,8 @@ import de.matthiasmann.twl.Event; import de.matthiasmann.twl.Widget; -/** - * Adds convenience methods to {@link DialogLayout}. - * @author Nathan Sweet - */ +/** Adds convenience methods to {@link DialogLayout}. + * @author Nathan Sweet */ public class Layout extends DialogLayout { private boolean eatEvents; @@ -64,9 +63,7 @@ public class Direction { this.horizontal = horizontal; } - /** - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group sequence (Object... widgets) { DialogLayout.Group dialogGroup = createSequentialGroup(); if (horizontal) @@ -76,9 +73,7 @@ public Group sequence (Object... widgets) { return new Group(null, dialogGroup).add(widgets); } - /** - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group parallel (Object... widgets) { DialogLayout.Group dialogGroup = createParallelGroup(); if (horizontal) @@ -97,51 +92,39 @@ public class Group { this.dialogGroup = dialogGroup; } - /** - * Adds the specified widgets. Sets the alignment to {@link Alignment#FILL fill} if the widget is not yet in the layout. - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** Adds the specified widgets. Sets the alignment to {@link Alignment#FILL fill} if the widget is not yet in the layout. + * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group sequence (Object... widgets) { return sequence(Alignment.FILL, widgets); } - /** - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group sequence (Alignment alignment, Object... widgets) { DialogLayout.Group dialogGroup = createSequentialGroup(); this.dialogGroup.addGroup(dialogGroup); return new Group(this, dialogGroup).add(widgets); } - /** - * Adds the specified widgets. Sets the alignment to {@link Alignment#FILL fill} if the widget is not yet in the layout. - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** Adds the specified widgets. Sets the alignment to {@link Alignment#FILL fill} if the widget is not yet in the layout. + * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group parallel (Object... widgets) { return parallel(Alignment.FILL, widgets); } - /** - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group parallel (Alignment alignment, Object... widgets) { DialogLayout.Group dialogGroup = createParallelGroup(); this.dialogGroup.addGroup(dialogGroup); return new Group(this, dialogGroup).add(widgets); } - /** - * Adds the specified widgets. Sets the alignment to {@link Alignment#FILL fill} if the widget is not yet in the layout. - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** Adds the specified widgets. Sets the alignment to {@link Alignment#FILL fill} if the widget is not yet in the layout. + * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group add (Object... widgets) { return add(Alignment.FILL, widgets); } - /** - * @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. - */ + /** @param widgets Either {@link Widget} or {@link Integer} objects. Integers are used to specify the gap size. */ public Group add (Alignment alignment, Object... widgets) { for (int i = 0, n = widgets.length; i < n; i++) { Object object = widgets[i]; diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/TWL.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/TWL.java index 48e4606fb05..05cc304b10e 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/TWL.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/TWL.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl; import java.io.File; @@ -39,8 +40,7 @@ import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.theme.ThemeManager; -/** - * Convenience class for using TWL. This provides all the basics sufficient for most UIs. TWL can be used without this class if +/** Convenience class for using TWL. This provides all the basics sufficient for most UIs. TWL can be used without this class if * more complex configurations are required (eg, multiple GUI instances).
        *
        * This class provides a single {@link GUI} instance with a root pane set to a widget that takes up the whole screen. @@ -54,8 +54,7 @@ * to use {@link InputMultiplexer} to avoid dispatching events that TWL handled to your application.
        *
        * If an instance of this call will no longer be used, {@link #dispose()} must be called to release resources. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class TWL implements InputProcessor { private final GdxRenderer renderer; private final GUI gui; @@ -63,17 +62,13 @@ public class TWL implements InputProcessor { private boolean mouseDown, ignoreMouse, lastPressConsumed; public Widget root; - /** - * Creates a new TWL instance with the specified theme file. The specified widget is added to the root pane. - */ + /** Creates a new TWL instance with the specified theme file. The specified widget is added to the root pane. */ public TWL (SpriteBatch batch, String themeFile, FileType fileType, Widget widget) { this(batch, themeFile, fileType); setWidget(widget); } - /** - * Creates a new TWL instance with the specified theme file. - */ + /** Creates a new TWL instance with the specified theme file. */ public TWL (SpriteBatch batch, String themeFile, FileType fileType) { renderer = new GdxRenderer(batch); @@ -95,33 +90,25 @@ protected void layout () { } } - /** - * Returns the GUI instance, which is the root of the TWL UI hierachy and manages timing, inputs, etc. - */ + /** Returns the GUI instance, which is the root of the TWL UI hierachy and manages timing, inputs, etc. */ public GUI getGUI () { return gui; } - /** - * Sets the widget in the GUI's root pane. By default the root pane takes up the whole screen. - * @param widget If null, this method is equivalent to {@link #clear()}. - */ + /** Sets the widget in the GUI's root pane. By default the root pane takes up the whole screen. + * @param widget If null, this method is equivalent to {@link #clear()}. */ public void setWidget (Widget widget) { Widget root = gui.getRootPane(); root.removeAllChildren(); if (widget != null) root.add(widget); } - /** - * Removes all widgets from the GUI's root pane. This effectively means that no TWL UI will be drawn. - */ + /** Removes all widgets from the GUI's root pane. This effectively means that no TWL UI will be drawn. */ public void clear () { gui.getRootPane().removeAllChildren(); } - /** - * Draws the TWL UI. - */ + /** Draws the TWL UI. */ public void render () { GUI gui = this.gui; int viewWidth = Gdx.graphics.getWidth(); @@ -318,11 +305,9 @@ static public int getTwlKeyCode (int gdxKeyCode) { return Event.KEY_NONE; } - /** - * Returns a URL to a theme file, which can be used with + /** Returns a URL to a theme file, which can be used with * {@link ThemeManager#createThemeManager(URL, de.matthiasmann.twl.renderer.Renderer) ThemeManager} to create a theme for - * {@link GUI#applyTheme(ThemeManager)}. This is only needed if not using the {@link TWL} class to make use of TWL. - */ + * {@link GUI#applyTheme(ThemeManager)}. This is only needed if not using the {@link TWL} class to make use of TWL. */ static public URL getThemeURL (String themeFile, final FileType fileType) throws MalformedURLException { File file = new File(themeFile); final File themeRoot = file.getParentFile(); diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxCacheContext.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxCacheContext.java index 470df6115f6..a2b60235e2c 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxCacheContext.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxCacheContext.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.twl.renderer; import java.io.IOException; @@ -24,9 +25,7 @@ import de.matthiasmann.twl.renderer.CacheContext; -/** - * @author Nathan Sweet - */ +/** @author Nathan Sweet */ public class GdxCacheContext implements CacheContext { final GdxRenderer renderer; private final ObjectMap textures = new ObjectMap(); 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 81754990f13..dba6a96c181 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 @@ -28,8 +28,8 @@ import java.util.Map; import com.badlogic.gdx.graphics.g2d.BitmapFont; -import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; +import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.math.MathUtils; import de.matthiasmann.twl.Color; @@ -39,11 +39,9 @@ import de.matthiasmann.twl.renderer.FontParameter; import de.matthiasmann.twl.utils.StateExpression; -/** - * @author Nathan Sweet +/** @author Nathan Sweet * @author Matthias Mann - * @author Kurtis Kopf - */ + * @author Kurtis Kopf */ public class GdxFont implements Font { static private final HAlignment[] gdxAlignment = HAlignment.values(); @@ -51,7 +49,7 @@ public class GdxFont implements Font { final BitmapFont bitmapFont; private final FontState[] fontStates; private final float yOffset; - + private Boolean proportional = null; public GdxFont (GdxRenderer renderer, BitmapFont bitmapFont, Map params, Collection condParams) { @@ -201,18 +199,13 @@ public void destroy () { } } - public boolean isProportional() - { - if (proportional == null) - { - try - { + public boolean isProportional () { + if (proportional == null) { + try { int iBound = (int)bitmapFont.getBounds("i").width; int mBound = (int)bitmapFont.getBounds("m").width; proportional = iBound != 0 && mBound != 0 && iBound != mBound; - } - catch(Exception e) - { + } catch (Exception e) { proportional = false; } } diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxImage.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxImage.java index 0c15a1df316..eff5bdef036 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxImage.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxImage.java @@ -30,10 +30,8 @@ import de.matthiasmann.twl.renderer.Image; import de.matthiasmann.twl.renderer.SupportsDrawRepeat; -/** - * @author Nathan Sweet - * @author Matthias Mann - */ +/** @author Nathan Sweet + * @author Matthias Mann */ public class GdxImage implements Image, SupportsDrawRepeat { private final GdxRenderer renderer; private final Sprite sprite; diff --git a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxRenderer.java b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxRenderer.java index bd9808e1ace..11153aa9fdb 100644 --- a/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxRenderer.java +++ b/extensions/twl/gdx-twl/src/com/badlogic/gdx/twl/renderer/GdxRenderer.java @@ -52,11 +52,9 @@ // BOZO - Add cursors. -/** - * @author Nathan Sweet +/** @author Nathan Sweet * @author Matthias Mann - * @author Kurtis Kopf - */ + * @author Kurtis Kopf */ public class GdxRenderer implements Renderer, LineRenderer { private int mouseX, mouseY; private GdxCacheContext cacheContext; @@ -67,7 +65,7 @@ public class GdxRenderer implements Renderer, LineRenderer { private boolean rendering; private int width, height; final SpriteBatch batch; - + private final ClipStack clipStack; public GdxRenderer (SpriteBatch batch) { @@ -234,65 +232,56 @@ public TintStack push (float r, float g, float b, float a) { } @Override - public void clipEnter(Rect rect) - { + public void clipEnter (Rect rect) { clipStack.push(rect); // using null might not be correct here. setClipRect(null); } @Override - public void clipEnter(int x, int y, int w, int h) - { + public void clipEnter (int x, int y, int w, int h) { clipStack.push(x, y, w, h); setClipRect(null); } - + @Override - public void clipLeave() - { + public void clipLeave () { clipStack.pop(); setClipRect(null); } @Override - public boolean clipIsEmpty() - { + public boolean clipIsEmpty () { return clipStack.isClipEmpty(); } - + @Override - public OffscreenRenderer getOffscreenRenderer() - { + public OffscreenRenderer getOffscreenRenderer () { // this is the same as in LWJGLRenderer in the main TWL project return null; } @Override - public void drawLine(float[] pts, int numPts, float width, de.matthiasmann.twl.Color color, boolean drawAsLoop) - { - if(numPts*2 > pts.length) - { - throw new ArrayIndexOutOfBoundsException(numPts*2); - } - if(numPts >= 2) - { - if (Gdx.gl11 != null) - { - //tintStack.push(color.getRedFloat(), color.getGreenFloat(), color.getBlueFloat(), color.getAlphaFloat()); - Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); - Gdx.gl.glLineWidth(width); - FloatBuffer fb = BufferUtils.newFloatBuffer(pts.length); - fb.put(pts); - fb.position(0); - Gdx.gl11.glEnableClientState(GL11.GL_VERTEX_ARRAY); - Gdx.gl11.glVertexPointer(2, GL11.GL_FLOAT, 0, fb); - Gdx.gl11.glColor4f(color.getRedFloat(), color.getGreenFloat(), color.getBlueFloat(), color.getAlphaFloat()); - Gdx.gl11.glDrawArrays((drawAsLoop ? GL11.GL_LINE_LOOP : GL11.GL_LINE_STRIP), 0, numPts); - Gdx.gl11.glColor4f(tintStack.r, tintStack.g, tintStack.b, tintStack.a); - Gdx.gl11.glDisableClientState(GL11.GL_VERTEX_ARRAY); - Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); - } - } + public void drawLine (float[] pts, int numPts, float width, de.matthiasmann.twl.Color color, boolean drawAsLoop) { + if (numPts * 2 > pts.length) { + throw new ArrayIndexOutOfBoundsException(numPts * 2); + } + if (numPts >= 2) { + if (Gdx.gl11 != null) { + // tintStack.push(color.getRedFloat(), color.getGreenFloat(), color.getBlueFloat(), color.getAlphaFloat()); + Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); + Gdx.gl.glLineWidth(width); + FloatBuffer fb = BufferUtils.newFloatBuffer(pts.length); + fb.put(pts); + fb.position(0); + Gdx.gl11.glEnableClientState(GL11.GL_VERTEX_ARRAY); + Gdx.gl11.glVertexPointer(2, GL11.GL_FLOAT, 0, fb); + Gdx.gl11.glColor4f(color.getRedFloat(), color.getGreenFloat(), color.getBlueFloat(), color.getAlphaFloat()); + Gdx.gl11.glDrawArrays((drawAsLoop ? GL11.GL_LINE_LOOP : GL11.GL_LINE_STRIP), 0, numPts); + Gdx.gl11.glColor4f(tintStack.r, tintStack.g, tintStack.b, tintStack.a); + Gdx.gl11.glDisableClientState(GL11.GL_VERTEX_ARRAY); + Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); + } + } } } 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 3cc329effad..7a945fa98ae 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,10 +22,7 @@ package com.badlogic.gdx.twl.renderer; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; -import com.badlogic.gdx.graphics.Texture.TextureFilter; -import com.badlogic.gdx.graphics.Texture.TextureWrap; import de.matthiasmann.twl.Color; import de.matthiasmann.twl.renderer.Image; @@ -33,20 +30,17 @@ import de.matthiasmann.twl.renderer.Resource; import de.matthiasmann.twl.renderer.Texture; -/** - * @author Nathan Sweet - */ +/** @author Nathan Sweet */ public class GdxTexture implements Texture, Resource { private final GdxRenderer renderer; private final com.badlogic.gdx.graphics.Texture texture; public GdxTexture (GdxRenderer renderer, FileHandle textureFile) { this.renderer = renderer; - texture =new com.badlogic.gdx.graphics.Texture(textureFile); + texture = new com.badlogic.gdx.graphics.Texture(textureFile); } - public Image getImage (int x, int y, int width, int height, Color tintColor, boolean tiled, Rotation rotation) - { + public Image getImage (int x, int y, int width, int height, Color tintColor, boolean tiled, Rotation rotation) { if (x < 0 || x >= getWidth()) throw new IllegalArgumentException("x"); if (y < 0 || y >= getHeight()) throw new IllegalArgumentException("y"); if (x + Math.abs(width) > getWidth()) throw new IllegalArgumentException("width"); @@ -54,24 +48,22 @@ public Image getImage (int x, int y, int width, int height, Color tintColor, boo if (tiled && (width <= 0 || height <= 0)) throw new IllegalArgumentException("Tiled rendering requires positive width & height."); float rd = 0f; - switch(rotation) - { - case CLOCKWISE_90: - rd = 90f; - break; - case CLOCKWISE_180: - rd = 180f; - break; - case CLOCKWISE_270: - rd = 270f; - break; + switch (rotation) { + case CLOCKWISE_90: + rd = 90f; + break; + case CLOCKWISE_180: + rd = 180f; + break; + case CLOCKWISE_270: + rd = 270f; + break; } return new GdxImage(renderer, texture, x, y, width, height, tintColor, tiled, rd); } - public MouseCursor createCursor (int x, int y, int width, int height, int hotSpotX, int hotSpotY, Image imageRef) - { - //System.out.println("trying to build a cursor!"); + public MouseCursor createCursor (int x, int y, int width, int height, int hotSpotX, int hotSpotY, Image imageRef) { + // System.out.println("trying to build a cursor!"); return null; // Unsupported. } diff --git a/gdx/src/com/badlogic/gdx/Application.java b/gdx/src/com/badlogic/gdx/Application.java index a171ab6a969..a4197ea04a2 100644 --- a/gdx/src/com/badlogic/gdx/Application.java +++ b/gdx/src/com/badlogic/gdx/Application.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; -/** - *

        +/**

        * An Application is the main entry point of your project. It sets up a window and rendering surface and manages the * different aspects of your application, namely {@link Graphics}, {@link Audio}, {@link Input} and {@link Files}. Think of an * Application being equivalent to a JFrame of Activity. @@ -80,111 +80,72 @@ * Android. *

        * - * @author mzechner - * - */ + * @author mzechner */ public interface Application { - /** - * Enumeration of possible {@link Application} types - * - * @author mzechner + /** Enumeration of possible {@link Application} types * - */ + * @author mzechner */ public enum ApplicationType { Android, Desktop, Applet, WebGL } - + public static final int LOG_NONE = 0; public static final int LOG_INFO = 1; public static final int LOG_ERROR = 2; - /** - * @return the {@link Graphics} instance - */ + /** @return the {@link Graphics} instance */ public Graphics getGraphics (); - /** - * @return the {@link Audio} instance - */ + /** @return the {@link Audio} instance */ public Audio getAudio (); - /** - * @return the {@link Input} instance - */ + /** @return the {@link Input} instance */ public Input getInput (); - /** - * @return the {@link Files} instance - */ + /** @return the {@link Files} instance */ public Files getFiles (); - /** - * Logs a message to the console or logcat - */ + /** Logs a message to the console or logcat */ public void log (String tag, String message); - - /** - * Logs a message to the console or logcat - */ + + /** Logs a message to the console or logcat */ public void log (String tag, String message, Exception exception); - - /** - * Logs an error message to the console or logcat - */ + + /** Logs an error message to the console or logcat */ public void error (String tag, String message); - - /** - * Logs an error message to the console or logcat - */ + + /** Logs an error message to the console or logcat */ public void error (String tag, String message, Exception exception); - /** - * Sets the log level. {@link #LOG_NONE} will mute all log output. - * {@link #LOG_ERROR} will only let messages issued with {@link #error(String, String)} through. - * {@link #LOG_INFO} will let all messages though, either logged via {@link #error(String, String)} or - * {@link #log(String, String)}. - * @param logLevel {@link #LOG_NONE}, {@link #LOG_ERROR}, {@link #LOG_INFO}. - */ - public void setLogLevel(int logLevel); - - /** - * @return what {@link ApplicationType} this application has, e.g. Android or Desktop - */ + /** Sets the log level. {@link #LOG_NONE} will mute all log output. {@link #LOG_ERROR} will only let messages issued with + * {@link #error(String, String)} through. {@link #LOG_INFO} will let all messages though, either logged via + * {@link #error(String, String)} or {@link #log(String, String)}. + * @param logLevel {@link #LOG_NONE}, {@link #LOG_ERROR}, {@link #LOG_INFO}. */ + public void setLogLevel (int logLevel); + + /** @return what {@link ApplicationType} this application has, e.g. Android or Desktop */ public ApplicationType getType (); - /** - * @return the Android API level on Android or 0 on the desktop. - */ + /** @return the Android API level on Android or 0 on the desktop. */ public int getVersion (); - /** - * @return the Java heap memory use in bytes - */ + /** @return the Java heap memory use in bytes */ public long getJavaHeap (); - /** - * @return the Native heap memory use in bytes - */ + /** @return the Native heap memory use in bytes */ public long getNativeHeap (); - - /** - * Returns the {@link Preferences} instance of this Application. It - * can be used to store application settings across runs. + + /** Returns the {@link Preferences} instance of this Application. It can be used to store application settings across runs. * @param name the name of the preferences, must be useable as a file name. - * @return the preferences. - */ - public Preferences getPreferences(String name); - - /** - * Posts a {@link Runnable} on the main loop thread. - * - * @param runnable the runnable. - */ - public void postRunnable(Runnable runnable); - - /** - * Exits the application. This will cause a call to pause() and dispose() - * some time in the loadFuture, it will not immediately finish your application! - */ - public void exit(); + * @return the preferences. */ + public Preferences getPreferences (String name); + + /** Posts a {@link Runnable} on the main loop thread. + * + * @param runnable the runnable. */ + public void postRunnable (Runnable runnable); + + /** Exits the application. This will cause a call to pause() and dispose() some time in the loadFuture, it will not immediately + * finish your application! */ + public void exit (); } diff --git a/gdx/src/com/badlogic/gdx/ApplicationListener.java b/gdx/src/com/badlogic/gdx/ApplicationListener.java index 6a13b7e92e3..af65596dc1e 100644 --- a/gdx/src/com/badlogic/gdx/ApplicationListener.java +++ b/gdx/src/com/badlogic/gdx/ApplicationListener.java @@ -13,10 +13,10 @@ * 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 created, resumed, rendering, paused or destroyed. * All methods are called in a thread that has the OpenGL context current. You can thus safely create and manipulate graphics * resources. @@ -27,44 +27,30 @@ * accordingly. *

        * - * @author mzechner - * - */ + * @author mzechner */ public interface ApplicationListener { - /** - * Called when the {@link Application} is first created. - */ + /** Called when the {@link Application} is first created. */ public void create (); - /** - * Called when the {@link Application} is resumed from a paused state. On Android this happens when the activity gets focus - * again. On the desktop this method will never be called. - */ + /** Called when the {@link Application} is resumed from a paused state. On Android this happens when the activity gets focus + * again. On the desktop this method will never be called. */ public void resume (); - /** - * Called when the {@link Application} should render itself. - */ + /** Called when the {@link Application} should render itself. */ public void render (); - /** - * Called when the {@link Application} is resized. This can happen at any point during a non-paused state but will never happen + /** Called when the {@link Application} is resized. This can happen at any point during a non-paused state but will never happen * before a call to {@link #create()}. * * @param width the new width in pixels - * @param height the new height in pixels - */ + * @param height the new height in pixels */ public void resize (int width, int height); - /** - * Called when the {@link Application} is paused. An Application is paused before it is destroyed, when a user pressed the Home + /** Called when the {@link Application} is paused. An Application is paused before it is destroyed, when a user pressed the Home * button on Android or an incoming call happend. On the desktop this will only be called immediately before {@link #dispose()} - * is called. - */ + * is called. */ public void pause (); - /** - * Called when the {@link Application} is destroyed. Preceded by a call to {@link #pause()}. - */ + /** Called when the {@link Application} is destroyed. Preceded by a call to {@link #pause()}. */ public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/Audio.java b/gdx/src/com/badlogic/gdx/Audio.java index f77c1c12d57..7c38696f505 100644 --- a/gdx/src/com/badlogic/gdx/Audio.java +++ b/gdx/src/com/badlogic/gdx/Audio.java @@ -13,6 +13,7 @@ * 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,8 +23,7 @@ import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * This interface encapsulates the creation and management of audio resources. It allows you to get direct access to the audio +/** This interface encapsulates the creation and management of audio resources. It allows you to get direct access 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. * @@ -36,35 +36,28 @@ * called, and automatically resumed when the {@link ApplicationListener#resume()} method is called. *

        * - * @author mzechner - * - */ + * @author mzechner */ public interface Audio { - /** - * Creates a new {@link AudioDevice} either in mono or stereo mode. The AudioDevice has to be disposed via its + /** Creates a new {@link AudioDevice} either in mono or stereo mode. The AudioDevice has to be disposed via its * {@link AudioDevice#dispose()} method when it is no longer used. * * @param samplingRate the sampling rate. * @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 - */ + * @throws GdxRuntimeException in case the device could not be created */ public AudioDevice newAudioDevice (int samplingRate, 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 * @return the AudioRecorder * - * @throws GdxRuntimeException in case the recorder could not be created - */ + * @throws GdxRuntimeException in case the recorder could not be created */ 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. @@ -79,19 +72,16 @@ public interface Audio { *

        * * @return the new Sound - * @throws GdxRuntimeException in case the sound could not be loaded - */ + * @throws GdxRuntimeException in case the sound could not be loaded */ public Sound newSound (FileHandle fileHandle); - /** - * Creates a new {@link Music} instance which is used to play back a music stream from a file. Currently supported formats are + /** Creates a new {@link Music} instance which is used to play back 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. * Music instances are automatically paused when {@link ApplicationListener#pause()} is called and resumed when * {@link ApplicationListener#resume()} is called. * * @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 - */ + * @throws GdxRuntimeException in case the music could not be loaded */ public Music newMusic (FileHandle file); } diff --git a/gdx/src/com/badlogic/gdx/Files.java b/gdx/src/com/badlogic/gdx/Files.java index cbc45293b07..63d35f82e5b 100644 --- a/gdx/src/com/badlogic/gdx/Files.java +++ b/gdx/src/com/badlogic/gdx/Files.java @@ -13,86 +13,61 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Provides standard access to the filesystem, classpath, Android SD card, and Android assets directory. +/** Provides standard access to the filesystem, classpath, Android SD card, and Android assets directory. * @author mzechner - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public interface Files { - /** - * Indicates how to resolve a path to a file. + /** Indicates how to resolve a path to a file. * @author mzechner - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public enum FileType { - /** - * Path relative to the root of the classpath. Classpath files are always readonly. Note that classpath files are not + /** Path relative to the root of the classpath. Classpath files are always readonly. Note that classpath files are not * compatible with some functionality on Android, such as {@link Audio#newSound(FileHandle)} and - * {@link Audio#newMusic(FileHandle)}. - */ + * {@link Audio#newMusic(FileHandle)}. */ Classpath, - /** - * Path relative to the asset directory on Android and to the application's root directory on the desktop. On the desktop, + /** Path relative to the asset directory on Android and to the application's root directory on the desktop. On the desktop, * if the file is not found, then the classpath is checked. This enables files to be found when using JWS or applets. - * Internal files are always readonly. - */ + * Internal files are always readonly. */ Internal, - /** - * Path relative to the root of the SD card on Android and to the home directory of the current user on the desktop. - */ + /** Path relative to the root of the SD card on Android and to the home directory of the current user on the desktop. */ External, - /** - * Path that is a fully qualified, absolute filesystem path. To ensure portability across platforms use absolute files only - * when absolutely (heh) necessary. - */ + /** Path that is a fully qualified, absolute filesystem path. To ensure portability across platforms use absolute files only + * when absolutely (heh) necessary. */ Absolute; } - /** - * Returns a handle representing a file or directory. + /** Returns a handle representing a file or directory. * @param type Determines how the path is resolved. * @throws GdxRuntimeException if the type is classpath or internal and the file does not exist. - * @see FileType - */ + * @see FileType */ public FileHandle getFileHandle (String path, FileType type); - /** - * Convenience method that returns a {@link FileType#Classpath} file handle. - */ + /** Convenience method that returns a {@link FileType#Classpath} file handle. */ public FileHandle classpath (String path); - /** - * Convenience method that returns a {@link FileType#Internal} file handle. - */ + /** Convenience method that returns a {@link FileType#Internal} file handle. */ public FileHandle internal (String path); - /** - * Convenience method that returns a {@link FileType#External} file handle. - */ + /** Convenience method that returns a {@link FileType#External} file handle. */ public FileHandle external (String path); - /** - * Convenience method that returns a {@link FileType#Absolute} file handle. - */ + /** Convenience method that returns a {@link FileType#Absolute} file handle. */ public FileHandle absolute (String path); - /** - * Returns the external storage path directory. This is the SD card on Android and the home directory of the current user on - * the desktop. - */ + /** Returns the external storage path directory. This is the SD card on Android and the home directory of the current user on + * the desktop. */ public String getExternalStoragePath (); - /** - * Returns true if the external storage is ready for file IO. Eg, on Android, the SD card is not available when mounted for use - * with a PC. - */ + /** Returns true if the external storage is ready for file IO. Eg, on Android, the SD card is not available when mounted for use + * with a PC. */ public boolean isExternalStorageAvailable (); } diff --git a/gdx/src/com/badlogic/gdx/Game.java b/gdx/src/com/badlogic/gdx/Game.java index 0f6327e3786..88a80952651 100644 --- a/gdx/src/com/badlogic/gdx/Game.java +++ b/gdx/src/com/badlogic/gdx/Game.java @@ -13,44 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; -/** - *

        +/**

        * An {@link ApplicationListener} that delegates to a {@link Screen}. This allows an application to easily have multiple screens. *

        *

        * Screens are not disposed automatically. You must handle whether you want to keep screens around or dispose of them when another * screen is set. - *

        - */ + *

        */ public abstract class Game implements ApplicationListener { private Screen screen; - @Override public void dispose () { + @Override + public void dispose () { if (screen != null) screen.hide(); } - @Override public void pause () { + @Override + public void pause () { if (screen != null) screen.pause(); } - @Override public void resume () { + @Override + public void resume () { if (screen != null) screen.resume(); } - @Override public void render () { + @Override + public void render () { if (screen != null) screen.render(Gdx.graphics.getDeltaTime()); } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { if (screen != null) screen.resize(width, height); } - /** - * Sets the current screen. {@link Screen#hide()} is called on any old screen, and {@link Screen#show()} is called on the new - * screen. - */ + /** Sets the current screen. {@link Screen#hide()} is called on any old screen, and {@link Screen#show()} is called on the new + * screen. */ public void setScreen (Screen screen) { if (this.screen != null) this.screen.hide(); this.screen = screen; @@ -58,9 +60,7 @@ public void setScreen (Screen screen) { screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } - /** - * @return the currently active {@link Screen}. - */ + /** @return the currently active {@link Screen}. */ public Screen getScreen () { return screen; } diff --git a/gdx/src/com/badlogic/gdx/Gdx.java b/gdx/src/com/badlogic/gdx/Gdx.java index 12136673dfc..70f8d4bf737 100644 --- a/gdx/src/com/badlogic/gdx/Gdx.java +++ b/gdx/src/com/badlogic/gdx/Gdx.java @@ -13,6 +13,7 @@ * 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,8 +22,7 @@ import com.badlogic.gdx.graphics.GLCommon; import com.badlogic.gdx.graphics.GLU; -/** - *

        +/**

        * Environment class holding references to the {@link Application}, {@link Graphics}, {@link Audio}, {@link Files} and * {@link 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 @@ -30,17 +30,15 @@ *

        * *

        - * There's also references to {@link GLCommon}, {@link GL10}, {@link GL11}, {@link GL20} and {@link GLU}. The same rules as above apply. Don't - * mess with this or things will break! + * There's also references to {@link GLCommon}, {@link GL10}, {@link GL11}, {@link GL20} and {@link GLU}. 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. *

        * - * @author mzechner - * - */ + * @author mzechner */ public class Gdx { public static Application app; public static Graphics graphics; diff --git a/gdx/src/com/badlogic/gdx/Graphics.java b/gdx/src/com/badlogic/gdx/Graphics.java index a29140683bf..88262086c36 100644 --- a/gdx/src/com/badlogic/gdx/Graphics.java +++ b/gdx/src/com/badlogic/gdx/Graphics.java @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx; -import java.nio.ByteBuffer; +package com.badlogic.gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; @@ -27,90 +26,66 @@ import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; -import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.graphics.glutils.IndexBufferObject; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.graphics.glutils.VertexArray; import com.badlogic.gdx.graphics.glutils.VertexBufferObject; -/** - *

        - * 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 and {@link Texture}s. +/**

        + * 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 and {@link Texture}s. *

        * *

        - * {@link Texture}s can be either managed or not managed. Managed and Textures - * will be restored when the OpenGL context is lost. An OpenGL ES context loss - * happens when a user pauses the Application ( - * {@link ApplicationListener#pause()}) and switches to another application on - * Android. On the desktop there is no concept of context loss for OpenGL. + * {@link Texture}s can be either managed or not managed. Managed and Textures will be restored when the OpenGL context is lost. + * An OpenGL ES context loss happens when a user pauses the Application ( {@link ApplicationListener#pause()}) and switches to + * another application on Android. On the desktop there is no concept of context loss for OpenGL. *

        * *

        - * There are many more utility classes that are not directly generated by the - * {@link Graphics} interfaces. See {@link VertexArray}, - * {@link VertexBufferObject}, {@link IndexBufferObject}, {@link Mesh}, - * {@link ShaderProgram} and {@link FrameBuffer}, {@link BitmapFont}, - * {@link SpriteBatch} and so on. All these classes are managed, meaning they - * don't need to be reloaded on a context loss. Explore the - * com.badlogic.gdx.graphics package for more classes that might come in handy. + * There are many more utility classes that are not directly generated by the {@link Graphics} interfaces. See {@link VertexArray}, {@link VertexBufferObject}, {@link IndexBufferObject}, {@link Mesh}, {@link ShaderProgram} and {@link FrameBuffer}, + * {@link BitmapFont}, {@link SpriteBatch} and so on. All these classes are managed, meaning they don't need to be reloaded on a + * context loss. Explore the com.badlogic.gdx.graphics package for more classes that might come in handy. *

        * *

        - * All graphical resources, be the generated by the {@link Graphics} interface - * or via a constructor must be disposed when no longer used! + * All graphical resources, be the generated by the {@link Graphics} interface or via a constructor must be disposed when + * no longer used! *

        * - * @author mzechner - * - */ + * @author mzechner */ public interface Graphics { - /** - * Enumeration describing different types of {@link Graphics} - * implementations. + /** Enumeration describing different types of {@link Graphics} implementations. * - * @author mzechner - * - */ + * @author mzechner */ public enum GraphicsType { AndroidGL, JoglGL, LWJGL, Angle, WebGL } - /** - * Class describing a fullscreen display mode - * - * @author mzechner + /** Class describing a fullscreen display mode * - */ + * @author mzechner */ public class DisplayMode { public final int width; public final int height; public final int refreshRate; public final int bitsPerPixel; - protected DisplayMode(int width, int height, int refreshRate, - int bitsPerPixel) { + protected DisplayMode (int width, int height, int refreshRate, int bitsPerPixel) { this.width = width; this.height = height; this.refreshRate = refreshRate; this.bitsPerPixel = bitsPerPixel; } - public String toString() { - return width + "x" + height + ", bpp: " + bitsPerPixel + ", hz: " - + refreshRate; + public String toString () { + return width + "x" + height + ", bpp: " + bitsPerPixel + ", hz: " + refreshRate; } } - /** - * Class describing the bits per pixel, depth buffer precision, stencil - * precision and number of MSAA samples. - */ + /** Class describing the bits per pixel, depth buffer precision, stencil precision and number of MSAA samples. */ public static class BufferFormat { /** number of bits per color channel **/ public final int r, g, b, a; @@ -118,14 +93,10 @@ public static class BufferFormat { public final int depth, stencil; /** number of samples for MSAA **/ public final int samples; - /** - * whether coverage sampling anti-aliasing is used. in that case you - * have to clear the coverage buffer as well! - */ + /** whether coverage sampling anti-aliasing is used. in that case you have to clear the coverage buffer as well! */ public final boolean coverageSampling; - public BufferFormat(int r, int g, int b, int a, int depth, int stencil, - int samples, boolean coverageSampling) { + public BufferFormat (int r, int g, int b, int a, int depth, int stencil, int samples, boolean coverageSampling) { this.r = r; this.g = g; this.b = b; @@ -136,197 +107,122 @@ public BufferFormat(int r, int g, int b, int a, int depth, int stencil, this.coverageSampling = coverageSampling; } - public String toString() { - return "r: " + r + ", g: " + g + ", b: " + b + ", a: " + a - + ", depth: " + depth + ", stencil: " + stencil - + ", num samples: " + samples + ", coverage sampling: " - + coverageSampling; + public String toString () { + return "r: " + r + ", g: " + g + ", b: " + b + ", a: " + a + ", depth: " + depth + ", stencil: " + stencil + + ", num samples: " + samples + ", coverage sampling: " + coverageSampling; } } - /** - * 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. This also implies that {@link #getGL10()} will return an - * instance. + /** 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. This also implies that {@link #getGL10()} will return an instance. * - * @return whether OpenGL ES 1.1 is available - */ - 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 {@link Application} instance to use OpenGL ES 2.0! + * @return whether OpenGL ES 1.1 is available */ + 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 + * {@link Application} instance to use OpenGL ES 2.0! * - * @return whether OpenGL ES 2.0 is available - */ - public boolean isGL20Available(); - - /** - * @return a {@link GLCommon} instance - */ - public GLCommon getGLCommon(); - - /** - * @return the {@link GL10} instance or null if not supported - */ - public GL10 getGL10(); - - /** - * @return the {@link GL11} instance or null if not supported - */ - public GL11 getGL11(); - - /** - * @return the {@link GL20} instance or null if not supported - */ - public GL20 getGL20(); - - /** - * @return the {@link GLU} instance - */ - public GLU getGLU(); - - /** - * @return the width in pixels of the display surface - */ - public int getWidth(); - - /** - * @return the height in pixels of the display surface - */ - public int getHeight(); - - /** - * @return the time span between the current frame and the last frame in - * seconds - */ - public float getDeltaTime(); - - /** - * @return the average number of frames per second - */ - public int getFramesPerSecond(); - - /** - * @return the {@link GraphicsType} of this Graphics instance - */ - public GraphicsType getType(); - - /** - * @return the pixels per inch on the x-axis - */ - public float getPpiX(); - - /** - * @return the pixels per inch on the y-axis - */ - public float getPpiY(); - - /** - * @return the pixels per centimeter on the x-axis - */ - public float getPpcX(); - - /** - * @return the pixels per centimeter on the y-axis. - */ - public float getPpcY(); - - /** - * This is a scaling factor for the Density Independent Pixel unit, - * following the same conventions as android.util.DisplayMetrics#density, - * where one DIP is one pixel on an approximately 160 dpi screen. Thus on a - * 160dpi screen this density value will be 1; on a 120 dpi screen it would - * be .75; etc. + * @return whether OpenGL ES 2.0 is available */ + public boolean isGL20Available (); + + /** @return a {@link GLCommon} instance */ + public GLCommon getGLCommon (); + + /** @return the {@link GL10} instance or null if not supported */ + public GL10 getGL10 (); + + /** @return the {@link GL11} instance or null if not supported */ + public GL11 getGL11 (); + + /** @return the {@link GL20} instance or null if not supported */ + public GL20 getGL20 (); + + /** @return the {@link GLU} instance */ + public GLU getGLU (); + + /** @return the width in pixels of the display surface */ + public int getWidth (); + + /** @return the height in pixels of the display surface */ + public int getHeight (); + + /** @return the time span between the current frame and the last frame in seconds */ + public float getDeltaTime (); + + /** @return the average number of frames per second */ + public int getFramesPerSecond (); + + /** @return the {@link GraphicsType} of this Graphics instance */ + public GraphicsType getType (); + + /** @return the pixels per inch on the x-axis */ + public float getPpiX (); + + /** @return the pixels per inch on the y-axis */ + public float getPpiY (); + + /** @return the pixels per centimeter on the x-axis */ + public float getPpcX (); + + /** @return the pixels per centimeter on the y-axis. */ + public float getPpcY (); + + /** This is a scaling factor for the Density Independent Pixel unit, following the same conventions as + * android.util.DisplayMetrics#density, where one DIP is one pixel on an approximately 160 dpi screen. Thus on a 160dpi screen + * this density value will be 1; on a 120 dpi screen it would be .75; etc. * - * @return the logical density of the Display. - */ - public float getDensity(); + * @return the logical density of the Display. */ + public float getDensity (); - /** - * Whether the given backend supports a display mode change via calling - * {@link Graphics#setDisplayMode(DisplayMode)} + /** Whether the given backend supports a display mode change via calling {@link Graphics#setDisplayMode(DisplayMode)} * - * @return whether display mode changes are supported or not. - */ - public boolean supportsDisplayModeChange(); - - /** - * @return the supported fullscreen {@link DisplayMode}. - */ - public DisplayMode[] getDisplayModes(); - - /** - * @return the display mode of the primary graphics adapter. - */ - public DisplayMode getDesktopDisplayMode(); - - /** - * Sets the current {@link DisplayMode}. Returns false in case the operation - * failed. Not all backends support this methods. See + * @return whether display mode changes are supported or not. */ + public boolean supportsDisplayModeChange (); + + /** @return the supported fullscreen {@link DisplayMode}. */ + public DisplayMode[] getDisplayModes (); + + /** @return the display mode of the primary graphics adapter. */ + public DisplayMode getDesktopDisplayMode (); + + /** Sets the current {@link DisplayMode}. Returns false in case the operation failed. Not all backends support this methods. See * {@link Graphics#supportsDisplayModeChange()}. * - * @param displayMode - * the display mode. - * @return whether the operation succeeded. - */ - public boolean setDisplayMode(DisplayMode displayMode); - - /** - * Tries to set the display mode width the given width and height in pixels. - * Will always succeed if fullscreen is set to false, in which case the - * application will be run in windowed mode. Use - * {@link Graphics#getDisplayModes()} to get a list of supported fullscreen - * modes. + * @param displayMode the display mode. + * @return whether the operation succeeded. */ + public boolean setDisplayMode (DisplayMode displayMode); + + /** Tries to set the display mode width the given width and height in pixels. Will always succeed if fullscreen is set to false, + * in which case the application will be run in windowed mode. Use {@link Graphics#getDisplayModes()} to get a list of + * supported fullscreen modes. * - * @param width - * the width in pixels - * @param height - * the height in pixels - * @param fullscreen - * whether to use fullscreen rendering or not - */ - public boolean setDisplayMode(int width, int height, boolean fullscreen); - - /** - * Sets the title of the window. Ignored on Android. + * @param width the width in pixels + * @param height the height in pixels + * @param fullscreen whether to use fullscreen rendering or not */ + public boolean setDisplayMode (int width, int height, boolean fullscreen); + + /** Sets the title of the window. Ignored on Android. * - * @param title - * the title. - */ - public void setTitle(String title); + * @param title the title. */ + public void setTitle (String title); - /** - * Sets the icon of the window. Ignored on Android. + /** Sets the icon of the window. Ignored on Android. * - * @param pixmap - */ - public void setIcon(Pixmap pixmap); + * @param pixmap */ + public void setIcon (Pixmap pixmap); - /** - * Enable/Disable vsynching. This is a best-effort attempt which might not - * work on all platforms. + /** Enable/Disable vsynching. This is a best-effort attempt which might not work on all platforms. * - * @param vsync - * vsync enabled or not. - */ - public void setVSync(boolean vsync); - - /** - * @return the format of the color, depth and stencil buffer in a - * {@link BufferFormat} instance - */ - public BufferFormat getBufferFormat(); - - /** - * @param extension - * the extension name - * @return whether the extension is supported - */ - public boolean supportsExtension(String extension); + * @param vsync vsync enabled or not. */ + public void setVSync (boolean vsync); + + /** @return the format of the color, depth and stencil buffer in a {@link BufferFormat} instance */ + public BufferFormat getBufferFormat (); + + /** @param extension the extension name + * @return whether the extension is supported */ + public boolean supportsExtension (String extension); // /** // * Opens the first back facing video camera. Only one camera diff --git a/gdx/src/com/badlogic/gdx/Input.java b/gdx/src/com/badlogic/gdx/Input.java index 37589041066..3bf32686de5 100644 --- a/gdx/src/com/badlogic/gdx/Input.java +++ b/gdx/src/com/badlogic/gdx/Input.java @@ -13,10 +13,10 @@ * 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. *

        @@ -36,38 +36,28 @@ * The class also offers methods to let the phone vibrate as well as getting compass readings. *

        * - * @author mzechner - * - */ + * @author mzechner */ public interface Input { - /** - * Callback interface for {@link Input#getTextInput(TextInputListener, String, String)} - * - * @author mzechner + /** Callback interface for {@link Input#getTextInput(TextInputListener, String, String)} * - */ + * @author mzechner */ public interface TextInputListener { public void input (String text); - public void canceled(); + + public void canceled (); } - /** - * Mouse buttons. - * @author mzechner - * - */ + /** Mouse buttons. + * @author mzechner */ public class Buttons { public static final int LEFT = 0; public static final int RIGHT = 1; public static final int MIDDLE = 2; } - /** - * Keys. + /** Keys. * - * @author mzechner - * - */ + * @author mzechner */ public class Keys { public static final int ANY_KEY = -1; public static final int NUM_0 = 7; @@ -201,26 +191,25 @@ public class Keys { public static final int BUTTON_START = 108; public static final int BUTTON_SELECT = 109; public static final int BUTTON_MODE = 110; - - -// public static final int BACKTICK = 0; -// public static final int TILDE = 0; -// public static final int UNDERSCORE = 0; -// public static final int DOT = 0; -// public static final int BREAK = 0; -// public static final int PIPE = 0; -// public static final int EXCLAMATION = 0; -// public static final int QUESTIONMARK = 0; - -// ` | VK_BACKTICK -// ~ | VK_TILDE -// : | VK_COLON -// _ | VK_UNDERSCORE -// . | VK_DOT -// (break) | VK_BREAK -// | | VK_PIPE -// ! | VK_EXCLAMATION -// ? | VK_QUESTION + +// public static final int BACKTICK = 0; +// public static final int TILDE = 0; +// public static final int UNDERSCORE = 0; +// public static final int DOT = 0; +// public static final int BREAK = 0; +// public static final int PIPE = 0; +// public static final int EXCLAMATION = 0; +// public static final int QUESTIONMARK = 0; + +// ` | VK_BACKTICK +// ~ | VK_TILDE +// : | VK_COLON +// _ | VK_UNDERSCORE +// . | VK_DOT +// (break) | VK_BREAK +// | | VK_PIPE +// ! | VK_EXCLAMATION +// ? | VK_QUESTION public static final int COLON = 243; public static final int F1 = 244; public static final int F2 = 245; @@ -235,263 +224,185 @@ public class Keys { public static final int F11 = 254; public static final int F12 = 255; } - - /** - * Enumeration of potentially available peripherals. Use with - * {@link Input#isPeripheralAvailable(Peripheral)}. - * @author mzechner - * - */ + + /** Enumeration of potentially available peripherals. Use with {@link Input#isPeripheralAvailable(Peripheral)}. + * @author mzechner */ public enum Peripheral { - HardwareKeyboard, - OnscreenKeyboard, - MultitouchScreen, - Accelerometer, - Compass, - Vibrator + HardwareKeyboard, OnscreenKeyboard, MultitouchScreen, Accelerometer, Compass, Vibrator } - /** - * @return The value of the accelerometer on its x-axis. ranges between [-10,10]. - */ + /** @return The value of the accelerometer on its x-axis. ranges between [-10,10]. */ public float getAccelerometerX (); - /** - * @return The value of the accelerometer on its y-axis. ranges between [-10,10]. - */ + /** @return The value of the accelerometer on its y-axis. ranges between [-10,10]. */ public float getAccelerometerY (); - /** - * @return The value of the accelerometer on its y-axis. ranges between [-10,10]. - */ + /** @return The value of the accelerometer on its y-axis. ranges between [-10,10]. */ public float getAccelerometerZ (); - /** - * @return the last touch x coordinate in screen coordinates. The screen origin is the top left corner. - */ + /** @return the last touch x coordinate in screen coordinates. The screen origin is the top left corner. */ public int getX (); - - /** - * Returns the x coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The pointer id + /** 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 keeps its index. If another finger is placed on * the touch screen the first free index will be used. * * @param pointer the pointer id. - * @return the x coordinate - */ + * @return the x coordinate */ public int getX (int pointer); - - /** - * @return the different between the current pointer location and the last pointer location on the x-axis. - */ - public int getDeltaX(); - - /** - * @return the different between the current pointer location and the last pointer location on the x-axis. - */ - public int getDeltaX(int pointer); - - /** - * @return the last touch y coordinate in screen coordinates. The screen origin is the top left corner. - */ + + /** @return the different between the current pointer location and the last pointer location on the x-axis. */ + public int getDeltaX (); + + /** @return the different between the current pointer location and the last pointer location on the x-axis. */ + public int getDeltaX (int pointer); + + /** @return the last touch y coordinate in screen coordinates. The screen origin is the top left corner. */ public int getY (); - /** - * Returns the y coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The pointer id + /** 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 keeps its index. If another finger is placed on * the touch screen the first free index will be used. * * @param pointer the pointer id. - * @return the y coordinate - */ + * @return the y coordinate */ public int getY (int pointer); - - /** - * @return the different between the current pointer location and the last pointer location on the y-axis. - */ - public int getDeltaY(); - - /** - * @return the different between the current pointer location and the last pointer location on the y-axis. - */ - public int getDeltaY(int pointer); - - /** - * @return whether the screen is currently touched. - */ + + /** @return the different between the current pointer location and the last pointer location on the y-axis. */ + public int getDeltaY (); + + /** @return the different between the current pointer location and the last pointer location on the y-axis. */ + public int getDeltaY (int pointer); + + /** @return whether the screen is currently touched. */ public boolean isTouched (); - /** - * @return whether a new touch down event just occured. - */ + /** @return whether a new touch down event just occured. */ public boolean justTouched (); - /** - * Whether the screen is currently touched by the pointer with the given index. Pointers are indexed from 0 to n. The pointer + /** Whether the screen is currently touched by the pointer with the given index. 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 keeps its index. If another finger is placed on * the touch screen the first free index will be used. * * @param pointer the pointer - * @return whether the screen is touched by the pointer - */ + * @return whether the screen is touched by the pointer */ public boolean isTouched (int pointer); - /** - * Whether a given button is pressed or not. Button constants can be found in {@link Buttons}. On Android only the Button#LEFT + /** Whether a given button is pressed or not. Button constants can be found in {@link Buttons}. On Android only the Button#LEFT * constant is meaningful. * @param button the button to check. - * @return whether the button is down or not. - */ + * @return whether the button is down or not. */ public boolean isButtonPressed (int button); - /** - * Returns whether the key is pressed. + /** Returns whether the key is pressed. * * @param key The key code as found in {@link Input.Keys}. - * @return true or false. - */ + * @return true or false. */ 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 + /** 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 but not * necessarily in the rendering thread in which all the {@link ApplicationListener} methods are called. You have to synchronize * this yourself. * * @param listener The TextInputListener. * @param title The title of the text input dialog. - * @param text The message presented to the user. - */ + * @param text The message presented to the user. */ public void getTextInput (TextInputListener listener, String title, String text); - /** - * Sets the on-screen keyboard visible if available. + /** Sets the on-screen keyboard visible if available. * - * @param visible visible or not - */ + * @param visible visible or not */ public void setOnscreenKeyboardVisible (boolean visible); - /** - * Vibrates for the given amount of time. Note that you'll need the permission + /** Vibrates for the given amount of time. Note that you'll need the permission * in your manifest file in order for this to work. * - * @param milliseconds the number of milliseconds to vibrate. - */ + * @param milliseconds the number of milliseconds to vibrate. */ public void vibrate (int milliseconds); - - /** - * Vibrate with a given pattern. - * Pass in an array of ints that are the times at which to turn on or off the vibrator. The first one is how long to wait before turning it on, and then after that it alternates. If you want to repeat, pass the index into the pattern at which to start the repeat. + + /** Vibrate with a given pattern. Pass in an array of ints that are the times at which to turn on or off the vibrator. The first + * one is how long to wait before turning it on, and then after that it alternates. If you want to repeat, pass the index into + * the pattern at which to start the repeat. * @param pattern an array of longs of times to turn the vibrator on or off. - * @param repeat the index into pattern at which to repeat, or -1 if you don't want to repeat. - */ + * @param repeat the index into pattern at which to repeat, or -1 if you don't want to repeat. */ public void vibrate (long[] pattern, int repeat); - - /** - * Stops the vibrator - */ - public void cancelVibrate(); - - /** - * The azimuth is the angle of the device's orientation around the z-axis. The - * positive z-axis points towards the earths center. + + /** Stops the vibrator */ + public void cancelVibrate (); + + /** The azimuth is the angle of the device's orientation around the z-axis. The positive z-axis points towards the earths + * center. * - * @see http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[]) - * @return the azimuth in degrees - */ - public float getAzimuth(); - - /** - * The pitch is the angle of the device's orientation around the x-axis. The - * positive x-axis roughly points to the west and is orthogonal to the z- and y-axis. - * @see http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[]) - * @return the pitch in degrees - */ - public float getPitch(); - - /** - * The roll is the angle of the device's orientation around the y-axis. The - * positive y-axis points to the magnetic north pole of the earth. - * @see http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[]) - * @return the roll in degrees - */ - public float getRoll(); - - /** - * Sets whether the BACK button on Android should be caught. This will prevent the app from being paused. Will have no effect + * @see http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[]) + * @return the azimuth in degrees */ + public float getAzimuth (); + + /** The pitch is the angle of the device's orientation around the x-axis. The positive x-axis roughly points to the west and is + * orthogonal to the z- and y-axis. + * @see http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[]) + * @return the pitch in degrees */ + public float getPitch (); + + /** The roll is the angle of the device's orientation around the y-axis. The positive y-axis points to the magnetic north pole + * of the earth. + * @see http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[]) + * @return the roll in degrees */ + public float getRoll (); + + /** Sets whether the BACK button on Android should be caught. This will prevent the app from being paused. Will have no effect * on the desktop. * - * @param catchBack whether to catch the back button - */ + * @param catchBack whether to catch the back button */ public void setCatchBackKey (boolean catchBack); - - /** - * Sets whether the MENU button on Android should be caught. This will prevent the onscreen keyboard to show up. Will have no effect - * on the desktop. + + /** Sets whether the MENU button on Android should be caught. This will prevent the onscreen keyboard to show up. Will have no + * effect on the desktop. * - * @param catchMenu whether to catch the back button - */ - public void setCatchMenuKey(boolean catchMenu); + * @param catchMenu whether to catch the back button */ + public void setCatchMenuKey (boolean catchMenu); - /** - * Sets the {@link InputProcessor} that will receive all touch and key input events. It will be called before the + /** Sets the {@link InputProcessor} that will receive all touch and key input events. It will be called before the * {@link ApplicationListener#render()} method each frame. * - * @param processor the InputProcessor - */ + * @param processor the InputProcessor */ public void setInputProcessor (InputProcessor processor); - - /** - * @return the currently set {@link InputProcessor} or null. - */ - public InputProcessor getInputProcessor(); - - /** - * Queries whether a {@link Peripheral} is currently available. In case of Android - * and the {@link Peripheral#HardwareKeyboard} this returns the whether the keyboard - * is currently slid out or not. + + /** @return the currently set {@link InputProcessor} or null. */ + public InputProcessor getInputProcessor (); + + /** Queries whether a {@link Peripheral} is currently available. In case of Android and the {@link Peripheral#HardwareKeyboard} + * this returns the whether the keyboard is currently slid out or not. * * @param peripheral the {@link Peripheral} - * @return whether the peripheral is available or not. - */ - public boolean isPeripheralAvailable(Peripheral peripheral); - - /** - * @return the rotation of the device with respect to its native orientation. - */ - public int getRotation(); - - /** - * @return the native orientation of the device. - */ - public Orientation getNativeOrientation(); - + * @return whether the peripheral is available or not. */ + public boolean isPeripheralAvailable (Peripheral peripheral); + + /** @return the rotation of the device with respect to its native orientation. */ + public int getRotation (); + + /** @return the native orientation of the device. */ + public Orientation getNativeOrientation (); + public enum Orientation { - Landscape, - Portrait + Landscape, Portrait } - - /** - * Only viable on the desktop. Will confine the mouse cursor location - * to the window and hide the mouse cursor. - * @param catched whether to catch or not to catch the mouse cursor - */ - public void setCursorCatched(boolean catched); - - /** - * @return whether the mouse cursor is catched. - */ - public boolean isCursorCatched (); - - /** - * Only viable on the desktop. Will set the mouse cursor location - * to the given window coordinates (origin top-left corner). + + /** Only viable on the desktop. Will confine the mouse cursor location to the window and hide the mouse cursor. + * @param catched whether to catch or not to catch the mouse cursor */ + public void setCursorCatched (boolean catched); + + /** @return whether the mouse cursor is catched. */ + public boolean isCursorCatched (); + + /** Only viable on the desktop. Will set the mouse cursor location to the given window coordinates (origin top-left corner). * @param x the x-position - * @param y the y-position - */ - public void setCursorPosition(int x, int y); + * @param y the y-position */ + public void setCursorPosition (int x, int y); } diff --git a/gdx/src/com/badlogic/gdx/InputAdapter.java b/gdx/src/com/badlogic/gdx/InputAdapter.java index 94f3575367f..36d5717b3db 100644 --- a/gdx/src/com/badlogic/gdx/InputAdapter.java +++ b/gdx/src/com/badlogic/gdx/InputAdapter.java @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; -/** - * An adapter class for {@link InputProcessor}. You can derive from this and only override what you are interested in. - * - * @author mzechner +/** An adapter class for {@link InputProcessor}. You can derive from this and only override what you are interested in. * - */ + * @author mzechner */ public class InputAdapter implements InputProcessor { public boolean keyDown (int keycode) { return false; @@ -46,11 +44,13 @@ public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/gdx/src/com/badlogic/gdx/InputMultiplexer.java b/gdx/src/com/badlogic/gdx/InputMultiplexer.java index 17ff3b1d2ab..0a2716447b6 100644 --- a/gdx/src/com/badlogic/gdx/InputMultiplexer.java +++ b/gdx/src/com/badlogic/gdx/InputMultiplexer.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import java.util.ArrayList; -/** - * An {@link InputProcessor} that delegates to an ordered list of other InputProcessors. Delegation for an event stops if a +/** An {@link InputProcessor} that delegates to an ordered list of other InputProcessors. Delegation for an event stops if a * processor returns true, which indicates that the event was handled. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class InputMultiplexer implements InputProcessor { private ArrayList processors = new ArrayList(4); @@ -77,13 +76,15 @@ public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { for (int i = 0, n = processors.size(); i < n; i++) if (processors.get(i).touchMoved(x, y)) return true; return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { for (int i = 0, n = processors.size(); i < n; i++) if (processors.get(i).scrolled(amount)) return true; return false; diff --git a/gdx/src/com/badlogic/gdx/InputProcessor.java b/gdx/src/com/badlogic/gdx/InputProcessor.java index e03b7c8a833..a2f82cfabd4 100644 --- a/gdx/src/com/badlogic/gdx/InputProcessor.java +++ b/gdx/src/com/badlogic/gdx/InputProcessor.java @@ -13,92 +13,74 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import com.badlogic.gdx.Input.Buttons; -/** - * An InputProcessor is used to receive input events from the keyboard and the touch screen (mouse on the desktop). For this it +/** An InputProcessor 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#setInputProcessor(InputProcessor)} method. It will be called each frame before the * call to {@link ApplicationListener#render()}. The methods return a* boolean in case you want to write a multiplexing * InputProcessor that has a chain of child processors that signal whether they processed the event. The {@link InputMultiplexer} * offers you exactly this functionality. * - * @author badlogicgames@gmail.com - * - */ + * @author badlogicgames@gmail.com */ public interface InputProcessor { - /** - * Called when a key was pressed + /** Called when a key was pressed * * @param keycode one of the constants in {@link Input.Keys} - * @return whether the input was processed - */ + * @return whether the input was processed */ public boolean keyDown (int keycode); - /** - * Called when a key was released + /** Called when a key was released * * @param keycode one of the constants in {@link Input.Keys} - * @return whether the input was processed - */ + * @return whether the input was processed */ public boolean keyUp (int keycode); - /** - * Called when a key was typed + /** Called when a key was typed * * @param character The character - * @return whether the input was processed - */ + * @return whether the input was processed */ public boolean keyTyped (char character); - /** - * Called when the screen was touched or a mouse button was pressed. The button parameter will be {@link Buttons#LEFT} on + /** Called when the screen was touched or a mouse button was pressed. The button parameter will be {@link Buttons#LEFT} on * Android. * * @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. * @param button the button - * @return whether the input was processed - */ + * @return whether the input was processed */ public boolean touchDown (int x, int y, int pointer, int button); - /** - * Called when a finger was lifted or a mouse button was released. The button parameter will be {@link Buttons#LEFT} on + /** Called when a finger was lifted or a mouse button was released. The button parameter will be {@link Buttons#LEFT} on * Android. * * @param x The x coordinate * @param y The y coordinate * @param pointer the pointer for the event. * @param button the button - * @return whether the input was processed - */ + * @return whether the input was processed */ public boolean touchUp (int x, int y, int pointer, int button); - /** - * 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. - * @return whether the input was processed - */ + * @return whether the input was processed */ public boolean touchDragged (int x, int y, int pointer); - /** - * Called when the mouse was moved without any buttons being pressed. Will not be called on Android. + /** Called when the mouse was moved without any buttons being pressed. Will not be called on Android. * * @param x The x coordinate * @param y The y coordinate - * @return whether the input was processed - */ + * @return whether the input was processed */ public boolean touchMoved (int x, int y); - /** - * Called when the mouse wheel was scrolled. Will not be called on Android. + /** Called when the mouse wheel was scrolled. Will not be called on Android. * @param amount the scroll amount, -1 or 1 depending on the direction the wheel was scrolled. - * @return whether the input was processed. - */ + * @return whether the input was processed. */ public boolean scrolled (int amount); } diff --git a/gdx/src/com/badlogic/gdx/Preferences.java b/gdx/src/com/badlogic/gdx/Preferences.java index 8741e5d57af..6ffcb00d3cf 100644 --- a/gdx/src/com/badlogic/gdx/Preferences.java +++ b/gdx/src/com/badlogic/gdx/Preferences.java @@ -13,49 +13,61 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; import java.util.Map; -/** - *

        A Preference instance is a hash map holding different - * values. It is stored alongside your application (SharedPreferences - * on Android, flat file in apps root directory on desktop).

        +/**

        + * A Preference instance is a hash map holding different values. It is stored alongside your application (SharedPreferences on + * Android, flat file in apps root directory on desktop). + *

        * *

        - * On the desktop the file will be located in the user directory. Make - * sure you give the preferences instance a name that can be used as - * a filename. + * On the desktop the file will be located in the user directory. Make sure you give the preferences instance a name that can be + * used as a filename. *

        * - * @author mzechner - * - */ + * @author mzechner */ public interface Preferences { - public void putBoolean(String key, boolean val); - public void putInteger(String key, int val); - public void putLong(String key, long val); - public void putFloat(String key, float val); - public void putString(String key, String val); - public void put(Map vals); - - public boolean getBoolean(String key); - public int getInteger(String key); - public long getLong(String key); - public float getFloat(String key); - public String getString(String key); - public boolean getBoolean(String key, boolean defValue); - public int getInteger(String key, int defValue); - public long getLong(String key, long defValue); - public float getFloat(String key, float defValue); - public String getString(String key, String defValue); - public Map get(); - - public boolean contains(String key); - public void clear(); - - /** - * Makes sure the preferences are persisted. - */ - public void flush(); + public void putBoolean (String key, boolean val); + + public void putInteger (String key, int val); + + public void putLong (String key, long val); + + public void putFloat (String key, float val); + + public void putString (String key, String val); + + public void put (Map vals); + + public boolean getBoolean (String key); + + public int getInteger (String key); + + public long getLong (String key); + + public float getFloat (String key); + + public String getString (String key); + + public boolean getBoolean (String key, boolean defValue); + + public int getInteger (String key, int defValue); + + public long getLong (String key, long defValue); + + public float getFloat (String key, float defValue); + + public String getString (String key, String defValue); + + public Map get (); + + public boolean contains (String key); + + public void clear (); + + /** Makes sure the preferences are persisted. */ + public void flush (); } diff --git a/gdx/src/com/badlogic/gdx/Screen.java b/gdx/src/com/badlogic/gdx/Screen.java index c48c79aae2a..cae2d0f1227 100644 --- a/gdx/src/com/badlogic/gdx/Screen.java +++ b/gdx/src/com/badlogic/gdx/Screen.java @@ -13,51 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx; -/** - *

        +/**

        * Represents one of many application screens, such as a main menu, a settings menu, the game screen and so on. *

        *

        * Note that {@link #dispose()} is not called automatically. *

        - * @see Game - */ + * @see Game */ public interface Screen { - /** - * Called when the screen should render itself. - * @param delta The time in seconds since the last render. - */ + /** Called when the screen should render itself. + * @param delta The time in seconds since the last render. */ public void render (float delta); - /** - * @see ApplicationListener#resize(int, int) - */ + /** @see ApplicationListener#resize(int, int) */ public void resize (int width, int height); - /** - * Called when this screen becomes the current screen for a {@link Game}. - */ + /** Called when this screen becomes the current screen for a {@link Game}. */ public void show (); - /** - * Called when this screen is no longer the current screen for a {@link Game}. - */ + /** Called when this screen is no longer the current screen for a {@link Game}. */ public void hide (); - /** - * @see ApplicationListener#pause() - */ + /** @see ApplicationListener#pause() */ public void pause (); - /** - * @see ApplicationListener#resume() - */ + /** @see ApplicationListener#resume() */ public void resume (); - /** - * Called when this screen should release all resources. - */ + /** Called when this screen should release all resources. */ public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/Version.java b/gdx/src/com/badlogic/gdx/Version.java index ea6ce4f49f7..b568c645a56 100644 --- a/gdx/src/com/badlogic/gdx/Version.java +++ b/gdx/src/com/badlogic/gdx/Version.java @@ -13,15 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx; +package com.badlogic.gdx; -/** - * The version of libgdx - * - * @author mzechner +/** The version of libgdx * - */ + * @author mzechner */ public class Version { /** the current version of libgdx in the major.minor format **/ public static String VERSION = "0.9.2"; diff --git a/gdx/src/com/badlogic/gdx/assets/AssetDescriptor.java b/gdx/src/com/badlogic/gdx/assets/AssetDescriptor.java index eeaf199bfcd..0d33a33c722 100644 --- a/gdx/src/com/badlogic/gdx/assets/AssetDescriptor.java +++ b/gdx/src/com/badlogic/gdx/assets/AssetDescriptor.java @@ -1,24 +1,22 @@ + package com.badlogic.gdx.assets; -/** - * Describes an asset to be loaded by it's filename, type and {@link AssetLoaderParameters}. - * Instances of this are used in {@link AssetLoadingTask} to load the actual asset. - * @author mzechner - * - */ +/** Describes an asset to be loaded by it's filename, type and {@link AssetLoaderParameters}. Instances of this are used in + * {@link AssetLoadingTask} to load the actual asset. + * @author mzechner */ public class AssetDescriptor { final String fileName; final Class type; final AssetLoaderParameters params; - - public AssetDescriptor(String fileName, Class assetType, AssetLoaderParameters params) { + + public AssetDescriptor (String fileName, Class assetType, AssetLoaderParameters params) { this.fileName = fileName.replaceAll("\\\\", "/"); this.type = assetType; this.params = params; } - + @Override - public String toString() { + public String toString () { return fileName; } } diff --git a/gdx/src/com/badlogic/gdx/assets/AssetErrorListener.java b/gdx/src/com/badlogic/gdx/assets/AssetErrorListener.java index 76829037499..af60130f325 100644 --- a/gdx/src/com/badlogic/gdx/assets/AssetErrorListener.java +++ b/gdx/src/com/badlogic/gdx/assets/AssetErrorListener.java @@ -1,5 +1,6 @@ + package com.badlogic.gdx.assets; public interface AssetErrorListener { - public void error(String fileName, Class type, Throwable throwable); + public void error (String fileName, Class type, Throwable throwable); } diff --git a/gdx/src/com/badlogic/gdx/assets/AssetLoaderParameters.java b/gdx/src/com/badlogic/gdx/assets/AssetLoaderParameters.java index 6fab05f0b91..eb9faf515bc 100644 --- a/gdx/src/com/badlogic/gdx/assets/AssetLoaderParameters.java +++ b/gdx/src/com/badlogic/gdx/assets/AssetLoaderParameters.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets; public interface AssetLoaderParameters { diff --git a/gdx/src/com/badlogic/gdx/assets/AssetLoadingTask.java b/gdx/src/com/badlogic/gdx/assets/AssetLoadingTask.java index 74efbc7cc87..bc93a6428d7 100644 --- a/gdx/src/com/badlogic/gdx/assets/AssetLoadingTask.java +++ b/gdx/src/com/badlogic/gdx/assets/AssetLoadingTask.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets; import java.util.concurrent.Callable; @@ -10,15 +11,11 @@ import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Responsible for loading an asset through an {@link AssetLoader} based on - * an {@link AssetDescriptor}. Implements {@link Callable} and is used with - * an {@link ExecutorService threadpool} to load parts of an asset asynchronously - * if the asset is loaded with an {@link AsynchronousAssetLoader}. +/** Responsible for loading an asset through an {@link AssetLoader} based on an {@link AssetDescriptor}. Implements + * {@link Callable} and is used with an {@link ExecutorService threadpool} to load parts of an asset asynchronously if the asset + * is loaded with an {@link AsynchronousAssetLoader}. * - * @author mzechner - * - */ + * @author mzechner */ class AssetLoadingTask implements Callable { final AssetDescriptor assetDesc; final AssetLoader loader; @@ -29,25 +26,22 @@ class AssetLoadingTask implements Callable { boolean updateOnRenderThread = false; Object asset = null; AssetManager manager; - - public AssetLoadingTask(AssetManager manager, AssetDescriptor assetDesc, AssetLoader loader, ExecutorService threadPool) { + + public AssetLoadingTask (AssetManager manager, AssetDescriptor assetDesc, AssetLoader loader, ExecutorService threadPool) { this.manager = manager; this.assetDesc = assetDesc; this.loader = loader; this.threadPool = threadPool; } - - /** - * Loads parts of the asset asynchronously if the loader is an - * {@link AsynchronousAssetLoader}. - */ + + /** Loads parts of the asset asynchronously if the loader is an {@link AsynchronousAssetLoader}. */ @Override public Void call () throws Exception { AsynchronousAssetLoader asyncLoader = (AsynchronousAssetLoader)loader; - if(dependenciesLoaded == false) { + if (dependenciesLoaded == false) { Array dependencies = asyncLoader.getDependencies(assetDesc.fileName, assetDesc.params); - if(dependencies != null) { - for(AssetDescriptor desc: dependencies) { + if (dependencies != null) { + for (AssetDescriptor desc : dependencies) { manager.injectDependency(assetDesc.fileName, desc); } } @@ -56,48 +50,45 @@ public Void call () throws Exception { } return null; } - - /** - * Updates the loading of the asset. In case the asset is loaded with an - * {@link AsynchronousAssetLoader}, the loaders {@link AsynchronousAssetLoader#loadAsync(AssetManager, String, Object)} - * method is first called on a worker thread. Once this method returns, the rest - * of the asset is loaded on the rendering thread via {@link AsynchronousAssetLoader#loadSync()}. + + /** Updates the loading of the asset. In case the asset is loaded with an {@link AsynchronousAssetLoader}, the loaders + * {@link AsynchronousAssetLoader#loadAsync(AssetManager, String, Object)} method is first called on a worker thread. Once this + * method returns, the rest of the asset is loaded on the rendering thread via {@link AsynchronousAssetLoader#loadSync()}. * @return true in case the asset was fully loaded, false otherwise - * @throws GdxRuntimeException - */ - public boolean update() { - if(loader instanceof SynchronousAssetLoader) { + * @throws GdxRuntimeException */ + public boolean update () { + if (loader instanceof SynchronousAssetLoader) { handleSyncLoader(); } else { handleAsyncLoader(); } return asset != null; } - - private void handleSyncLoader() { + + private void handleSyncLoader () { SynchronousAssetLoader syncLoader = (SynchronousAssetLoader)loader; - if(!dependenciesLoaded) { + if (!dependenciesLoaded) { dependenciesLoaded = true; Array dependencies = syncLoader.getDependencies(assetDesc.fileName, assetDesc.params); - if(dependencies == null) { + if (dependencies == null) { asset = syncLoader.load(manager, assetDesc.fileName, assetDesc.params); return; } - for(AssetDescriptor desc: dependencies) { + for (AssetDescriptor desc : dependencies) { manager.injectDependency(assetDesc.fileName, desc); } } else { asset = syncLoader.load(manager, assetDesc.fileName, assetDesc.params); } } - - private void handleAsyncLoader() { + + private void handleAsyncLoader () { AsynchronousAssetLoader asyncLoader = (AsynchronousAssetLoader)loader; - if(!dependenciesLoaded) { - if(depsFuture == null) { + if (!dependenciesLoaded) { + if (depsFuture == null) { depsFuture = threadPool.submit(this); } else { - if(depsFuture.isDone()) { + if (depsFuture.isDone()) { try { depsFuture.get(); } catch (Exception e) { @@ -107,10 +98,10 @@ private void handleAsyncLoader() { } } } else { - if(loadFuture == null) { + if (loadFuture == null) { loadFuture = threadPool.submit(this); } else { - if(loadFuture.isDone()) { + if (loadFuture.isDone()) { try { loadFuture.get(); } catch (Exception e) { @@ -121,8 +112,8 @@ private void handleAsyncLoader() { } } } - - public Object getAsset() { + + public Object getAsset () { return asset; } -} \ No newline at end of file +} diff --git a/gdx/src/com/badlogic/gdx/assets/AssetManager.java b/gdx/src/com/badlogic/gdx/assets/AssetManager.java index 7862ada3eec..445d12f2959 100644 --- a/gdx/src/com/badlogic/gdx/assets/AssetManager.java +++ b/gdx/src/com/badlogic/gdx/assets/AssetManager.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets; import java.util.Stack; @@ -27,25 +28,23 @@ import com.badlogic.gdx.utils.ObjectMap; public class AssetManager implements Disposable { - final ObjectMap> assets = new ObjectMap>(); + final ObjectMap> assets = new ObjectMap>(); final ObjectMap assetTypes = new ObjectMap(); final ObjectMap> assetDependencies = new ObjectMap>(); final ObjectMap loaders = new ObjectMap(); final Array preloadQueue = new Array(); final ExecutorService threadPool; - + Stack tasks = new Stack(); AssetErrorListener listener = null; int loaded = 0; int toLoad = 0; - + Logger log = new Logger(AssetManager.class.getSimpleName()); - - /** - * Creates a new AssetManager. - */ - public AssetManager() { + + /** Creates a new AssetManager. */ + public AssetManager () { log.setEnabled(false); setLoader(BitmapFont.class, new BitmapFontLoader(new InternalFileHandleResolver())); setLoader(Music.class, new MusicLoader(new InternalFileHandleResolver())); @@ -53,7 +52,7 @@ public AssetManager() { setLoader(Sound.class, new SoundLoader(new InternalFileHandleResolver())); setLoader(TextureAtlas.class, new TextureAtlasLoader(new InternalFileHandleResolver())); setLoader(Texture.class, new TextureLoader(new InternalFileHandleResolver())); - threadPool = Executors.newFixedThreadPool(1, new ThreadFactory() { + threadPool = Executors.newFixedThreadPool(1, new ThreadFactory() { @Override public Thread newThread (Runnable r) { Thread thread = new Thread(r, "AssetManager-Loader-Thread"); @@ -62,111 +61,96 @@ public Thread newThread (Runnable r) { } }); } - - /** - * @param fileName the asset file name + + /** @param fileName the asset file name * @param type the asset type - * @return the asset or null - */ + * @return the asset or null */ public synchronized T get (String fileName, Class type) { ObjectMap assetsByType = assets.get(type); - if(assetsByType == null) throw new GdxRuntimeException("Asset '" + fileName + "' not loaded"); + if (assetsByType == null) throw new GdxRuntimeException("Asset '" + fileName + "' not loaded"); T asset = (T)assetsByType.get(fileName); - if(asset == null) throw new GdxRuntimeException("Asset '" + fileName + "' not loaded"); + if (asset == null) throw new GdxRuntimeException("Asset '" + fileName + "' not loaded"); return asset; } - /** - * Removes the asset and all its dependencies if they are not used by - * other assets. - * @param fileName the file name - */ + /** Removes the asset and all its dependencies if they are not used by other assets. + * @param fileName the file name */ public synchronized void remove (String fileName) { // get the asset and its type Class type = assetTypes.get(fileName); - if(type == null) throw new GdxRuntimeException("Asset '" + fileName + "' not loaded"); - Object asset = assets.get(type).get(fileName); - + if (type == null) throw new GdxRuntimeException("Asset '" + fileName + "' not loaded"); + Object asset = assets.get(type).get(fileName); + // if it is disposable dispose it - if(asset instanceof Disposable) ((Disposable)asset).dispose(); - + if (asset instanceof Disposable) ((Disposable)asset).dispose(); + // if it is reference counted, check if we can really get rid of it. - if(asset instanceof ReferenceCountedAsset) { - if(((ReferenceCountedAsset)asset).getRefCount() > 0) return; + if (asset instanceof ReferenceCountedAsset) { + if (((ReferenceCountedAsset)asset).getRefCount() > 0) return; } - + // remove the asset from the manager. assetTypes.remove(fileName); assets.get(type).remove(fileName); - + // remove any dependencies (which might also be reference counted) Array dependencies = assetDependencies.remove(fileName); - if(dependencies != null) { - for(String dependency: dependencies) { + if (dependencies != null) { + for (String dependency : dependencies) { remove(dependency); } } } - /** - * @param asset the asset - * @return whether the asset is contained in this manager - */ - public synchronized boolean containsAsset(T asset) { + /** @param asset the asset + * @return whether the asset is contained in this manager */ + public synchronized boolean containsAsset (T asset) { ObjectMap typedAssets = assets.get(asset.getClass()); - for(String fileName: typedAssets.keys()) { + for (String fileName : typedAssets.keys()) { Object otherAsset = typedAssets.get(fileName); - if(otherAsset == asset || asset.equals(otherAsset)) return true; + if (otherAsset == asset || asset.equals(otherAsset)) return true; } return false; } - - /** - * @param asset the asset - * @return whether the filename of the asset or null - */ + + /** @param asset the asset + * @return whether the filename of the asset or null */ public synchronized String getAssetFileName (T asset) { ObjectMap typedAssets = assets.get(asset.getClass()); - for(String fileName: typedAssets.keys()) { + for (String fileName : typedAssets.keys()) { Object otherAsset = typedAssets.get(fileName); - if(otherAsset == asset || asset.equals(otherAsset)) return fileName; + if (otherAsset == asset || asset.equals(otherAsset)) return fileName; } return null; } - /** - * @param fileName the file name of the asset - * @return whether the asset is loaded - */ + /** @param fileName the file name of the asset + * @return whether the asset is loaded */ public synchronized boolean isLoaded (String fileName) { return assetTypes.containsKey(fileName); } - /** - * Adds the given asset to the loading queue of the AssetManager. + /** Adds the given asset to the loading queue of the AssetManager. * @param fileName the file name (interpretation depends on {@link AssetLoader}) - * @param type the type of the asset. - */ + * @param type the type of the asset. */ public synchronized void preload (String fileName, Class type) { preload(fileName, type, null); } - - /** - * Adds the given asset to the loading queue of the AssetManager. + + /** Adds the given asset to the loading queue of the AssetManager. * @param fileName the file name (interpretation depends on {@link AssetLoader}) * @param type the type of the asset. - * @param parameter parameters for the AssetLoader. - */ + * @param parameter parameters for the AssetLoader. */ public synchronized void preload (String fileName, Class type, AssetLoaderParameters parameter) { AssetLoader loader = loaders.get(type); - if(loader == null) throw new GdxRuntimeException("No loader for type '" + type.getSimpleName() + "'"); - if(isLoaded(fileName)) throw new GdxRuntimeException("Asset '" + fileName + "' already loaded"); - for(AssetDescriptor desc: preloadQueue) { - if(desc.fileName.equals(fileName)) { + if (loader == null) throw new GdxRuntimeException("No loader for type '" + type.getSimpleName() + "'"); + if (isLoaded(fileName)) throw new GdxRuntimeException("Asset '" + fileName + "' already loaded"); + for (AssetDescriptor desc : preloadQueue) { + if (desc.fileName.equals(fileName)) { throw new GdxRuntimeException("Asset '" + fileName + "' already in preload queue"); } } - if(preloadQueue.size == 0) { + if (preloadQueue.size == 0) { loaded = 0; toLoad = 0; } @@ -176,37 +160,35 @@ public synchronized void preload (String fileName, Class type, AssetLoade log.log("Added asset '" + assetDesc + "' to preload queue"); } - /** - * Updates the AssetManager, keeping it loading any assets in the preload queue. - * @return true if all loading is finished. - */ + /** Updates the AssetManager, keeping it loading any assets in the preload queue. + * @return true if all loading is finished. */ public synchronized boolean update () { try { - if(tasks.size() == 0) { - if(preloadQueue.size == 0) return true; + if (tasks.size() == 0) { + if (preloadQueue.size == 0) return true; nextTask(); } return updateTask() && preloadQueue.size == 0; - } catch(Throwable t) { + } catch (Throwable t) { handleTaskError(t); return preloadQueue.size == 0; } } - - synchronized void injectDependency(String parentAssetFilename, AssetDescriptor dependendAssetDesc) { + + synchronized void injectDependency (String parentAssetFilename, AssetDescriptor dependendAssetDesc) { // add the asset as a dependency of the parent asset Array dependencies = assetDependencies.get(parentAssetFilename); - if(dependencies == null) { + if (dependencies == null) { dependencies = new Array(); assetDependencies.put(parentAssetFilename, dependencies); } dependencies.add(dependendAssetDesc.fileName); // if the asset is already loaded, increase its reference count if needed. - if(isLoaded(dependendAssetDesc.fileName)) { + if (isLoaded(dependendAssetDesc.fileName)) { Class type = assetTypes.get(dependendAssetDesc.fileName); Object asset = assets.get(type).get(dependendAssetDesc.fileName); - if(asset instanceof ReferenceCountedAsset) ((ReferenceCountedAsset)asset).incRefCount(); + if (asset instanceof ReferenceCountedAsset) ((ReferenceCountedAsset)asset).incRefCount(); } // else add a new task for the asset. if the asset is already on the preloading queue else { @@ -215,57 +197,50 @@ synchronized void injectDependency(String parentAssetFilename, AssetDescriptor d log.log("Injected dependency '" + dependendAssetDesc + "' for asset '" + parentAssetFilename + "'"); } - - /** - * Removes a task from the preloadQueue and adds it to the task stack. If the - * asset is already loaded (which can happen if it was a dependency of a previously - * loaded asset) and if it is a {@link ReferenceCountedAsset} its reference count - * will be increased. - */ - private void nextTask() { + + /** Removes a task from the preloadQueue and adds it to the task stack. If the asset is already loaded (which can happen if it + * was a dependency of a previously loaded asset) and if it is a {@link ReferenceCountedAsset} its reference count will be + * increased. */ + private void nextTask () { AssetDescriptor assetDesc = preloadQueue.removeIndex(0); - - if(isLoaded(assetDesc.fileName)) { + + if (isLoaded(assetDesc.fileName)) { Class type = assetTypes.get(assetDesc.fileName); Object asset = assets.get(type).get(assetDesc.fileName); - if(asset instanceof ReferenceCountedAsset) ((ReferenceCountedAsset)asset).incRefCount(); + if (asset instanceof ReferenceCountedAsset) ((ReferenceCountedAsset)asset).incRefCount(); } else { addTask(assetDesc); } } - - /** - * Adds a {@link AssetLoadingTask} to the task stack for the given asset. - * @param assetDesc - */ - private void addTask(AssetDescriptor assetDesc) { + + /** Adds a {@link AssetLoadingTask} to the task stack for the given asset. + * @param assetDesc */ + private void addTask (AssetDescriptor assetDesc) { AssetLoader loader = loaders.get(assetDesc.type); - if(loader == null) throw new GdxRuntimeException("No loader for type '" + assetDesc.type.getSimpleName() + "'"); + if (loader == null) throw new GdxRuntimeException("No loader for type '" + assetDesc.type.getSimpleName() + "'"); tasks.push(new AssetLoadingTask(this, assetDesc, loader, threadPool)); } - - /** - * Updates the current task on the top of the task stack. - * @return true if the asset is loaded. - */ - private boolean updateTask() { + + /** Updates the current task on the top of the task stack. + * @return true if the asset is loaded. */ + private boolean updateTask () { AssetLoadingTask task = tasks.peek(); // if the task has finished loading - if(task.update()) { + if (task.update()) { // add the asset to the filename lookup assetTypes.put(task.assetDesc.fileName, task.assetDesc.type); - + // add the asset to the type lookup ObjectMap typeToAssets = assets.get(task.assetDesc.type); - if(typeToAssets == null) { + if (typeToAssets == null) { typeToAssets = new ObjectMap(); assets.put(task.assetDesc.type, typeToAssets); } typeToAssets.put(task.assetDesc.fileName, task.getAsset()); - + // increase the ref count of all dependencies (and their dependencies) incrementRefCountedDependencies(task.assetDesc.fileName); - + // increase the number of loaded assets and pop the task from the stack loaded++; tasks.pop(); @@ -274,85 +249,69 @@ private boolean updateTask() { return false; } } - - private void incrementRefCountedDependencies(String parent) { + + private void incrementRefCountedDependencies (String parent) { Array dependencies = assetDependencies.get(parent); - if(dependencies == null) return; - - for(String dependency: dependencies) { + if (dependencies == null) return; + + for (String dependency : dependencies) { Class type = assetTypes.get(dependency); - if(type == null) throw new GdxRuntimeException("Asset '" + dependency + "' not loaded"); + if (type == null) throw new GdxRuntimeException("Asset '" + dependency + "' not loaded"); // if we found a reference counted dependency we increase the ref count Object asset = assets.get(type).get(dependency); - if(asset instanceof ReferenceCountedAsset) { + if (asset instanceof ReferenceCountedAsset) { ((ReferenceCountedAsset)asset).incRefCount(); - } + } // otherwise we go deeper down the rabbit hole else { incrementRefCountedDependencies(dependency); } } } - - /** - * Handles a runtime/loading error in {@link #update()} by optionally - * invoking the {@link AssetErrorListener}. - * @param t - */ - private void handleTaskError(Throwable t) { + + /** Handles a runtime/loading error in {@link #update()} by optionally invoking the {@link AssetErrorListener}. + * @param t */ + private void handleTaskError (Throwable t) { // pop the faulty task from the stack AssetLoadingTask task = tasks.pop(); AssetDescriptor assetDesc = task.assetDesc; - if(listener != null) { + if (listener != null) { listener.error(assetDesc.fileName, assetDesc.type, t); } else { throw new GdxRuntimeException(t); } } - - /** - * Sets a new {@link AssetLoader} for the given type. + + /** Sets a new {@link AssetLoader} for the given type. * @param type the type of the asset - * @param loader the loader - */ - public synchronized void setLoader(Class type, AssetLoader loader) { + * @param loader the loader */ + public synchronized void setLoader (Class type, AssetLoader loader) { loaders.put(type, loader); } - /** - * @return the number of loaded assets - */ + /** @return the number of loaded assets */ public synchronized int getLoadedAssets () { return assetTypes.size; } - /** - * @return the number of currently queued assets - */ + /** @return the number of currently queued assets */ public synchronized int getQueuedAssets () { return preloadQueue.size + (tasks.size()); } - - /** - * @return the progress in percent of completion. - */ - public synchronized float getProgress() { + + /** @return the progress in percent of completion. */ + public synchronized float getProgress () { return loaded / (float)toLoad; } - /** - * Sets an {@link AssetErrorListener} to be invoked in case loading an - * asset failed. - * @param listener the listener or null - */ - public synchronized void setErrorListener(AssetErrorListener listener) { + /** Sets an {@link AssetErrorListener} to be invoked in case loading an asset failed. + * @param listener the listener or null */ + public synchronized void setErrorListener (AssetErrorListener listener) { this.listener = listener; } - - /** - * Disposes all assets in the manager and stops all asynchronous loading. - */ + + /** Disposes all assets in the manager and stops all asynchronous loading. */ public synchronized void dispose () { clear(); threadPool.shutdown(); @@ -363,23 +322,22 @@ public synchronized void dispose () { } } - /** - * Clears and disposes all assets and the preloading queue. - */ + /** Clears and disposes all assets and the preloading queue. */ public synchronized void clear () { - if(preloadQueue.size > 0 || tasks.size() != 0) { + if (preloadQueue.size > 0 || tasks.size() != 0) { try { - while(!updateTask()); - } catch(Throwable t) { + while (!updateTask()) + ; + } catch (Throwable t) { handleTaskError(t); } } - + Array assets = assetTypes.keys().toArray(); - for(String asset: assets) { + for (String asset : assets) { remove(asset); } - + this.assets.clear(); this.assetTypes.clear(); this.assetDependencies.clear(); @@ -387,37 +345,33 @@ public synchronized void clear () { this.preloadQueue.clear(); this.tasks.clear(); } - - /** - * @return the {@link Logger} used by the {@link AssetManager} - */ - public Logger getLogger() { + + /** @return the {@link Logger} used by the {@link AssetManager} */ + public Logger getLogger () { return log; } - - /** - * @return a string containg ref count and dependency information for all assets. - */ - public synchronized String getDiagonistics() { + + /** @return a string containg ref count and dependency information for all assets. */ + public synchronized String getDiagonistics () { StringBuffer buffer = new StringBuffer(); - for(String fileName: assetTypes.keys()) { + for (String fileName : assetTypes.keys()) { buffer.append(fileName); buffer.append(", "); - + Class type = assetTypes.get(fileName); Object asset = assets.get(type).get(fileName); Array dependencies = assetDependencies.get(fileName); - + buffer.append(type.getSimpleName()); - - if(asset instanceof ReferenceCountedAsset) { + + if (asset instanceof ReferenceCountedAsset) { buffer.append(", refs: "); buffer.append(((ReferenceCountedAsset)asset).getRefCount()); } - - if(dependencies != null) { + + if (dependencies != null) { buffer.append(", deps: ["); - for(String dep: dependencies) { + for (String dep : dependencies) { buffer.append(dep); buffer.append(","); } diff --git a/gdx/src/com/badlogic/gdx/assets/ReferenceCountedAsset.java b/gdx/src/com/badlogic/gdx/assets/ReferenceCountedAsset.java index befb622410b..df8a4c1ab59 100644 --- a/gdx/src/com/badlogic/gdx/assets/ReferenceCountedAsset.java +++ b/gdx/src/com/badlogic/gdx/assets/ReferenceCountedAsset.java @@ -1,6 +1,8 @@ + package com.badlogic.gdx.assets; public interface ReferenceCountedAsset { - public void incRefCount(); - public int getRefCount(); + public void incRefCount (); + + public int getRefCount (); } diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/AssetLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/AssetLoader.java index 00fbbe4e40e..186e5ba90a8 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/AssetLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/AssetLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.assets.AssetDescriptor; @@ -6,14 +7,14 @@ public abstract class AssetLoader { private FileHandleResolver resolver; - - public AssetLoader(FileHandleResolver resolver) { + + public AssetLoader (FileHandleResolver resolver) { this.resolver = resolver; } - - public FileHandle resolve(String fileName) { + + public FileHandle resolve (String fileName) { return resolver.resolve(fileName); } - - public abstract Array getDependencies(String fileName, P parameter); + + public abstract Array getDependencies (String fileName, P parameter); } diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.java index be78f3e3553..cfa794be83d 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.java @@ -1,12 +1,14 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.assets.AssetManager; -public abstract class AsynchronousAssetLoader extends AssetLoader { +public abstract class AsynchronousAssetLoader extends AssetLoader { public AsynchronousAssetLoader (FileHandleResolver resolver) { super(resolver); } - - public abstract void loadAsync(AssetManager manager, String fileName, P parameter); - public abstract T loadSync(); + + public abstract void loadAsync (AssetManager manager, String fileName, P parameter); + + public abstract T loadSync (); } diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontLoader.java index 01ea50c27d0..d3f029b6da7 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.assets.AssetDescriptor; @@ -9,8 +10,7 @@ import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.Array; - -public class BitmapFontLoader extends AsynchronousAssetLoader{ +public class BitmapFontLoader extends AsynchronousAssetLoader { public BitmapFontLoader (FileHandleResolver resolver) { super(resolver); } @@ -22,8 +22,8 @@ public BitmapFontLoader (FileHandleResolver resolver) { @Override public Array getDependencies (String fileName, BitmapFontParameter parameter) { FileHandle handle = resolve(fileName); - data = new BitmapFontData(handle, parameter != null? parameter.flip: false); - + data = new BitmapFontData(handle, parameter != null ? parameter.flip : false); + Array deps = new Array(); deps.add(new AssetDescriptor(data.getImageFile(), Texture.class, null)); return deps; @@ -38,7 +38,7 @@ public void loadAsync (AssetManager manager, String fileName, BitmapFontParamete @Override public BitmapFont loadSync () { FileHandle handle = resolve(fileName); - TextureRegion region = new TextureRegion(manager.get(data.getImageFile(), Texture.class)); + TextureRegion region = new TextureRegion(manager.get(data.getImageFile(), Texture.class)); return new BitmapFont(data, region, true); } diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontParameter.java b/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontParameter.java index 85b216f5a7b..eb3288e219e 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontParameter.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/BitmapFontParameter.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; public class BitmapFontParameter { diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/FileHandleResolver.java b/gdx/src/com/badlogic/gdx/assets/loaders/FileHandleResolver.java index 1de07bcb045..ebe58139ad8 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/FileHandleResolver.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/FileHandleResolver.java @@ -1,7 +1,8 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.files.FileHandle; public interface FileHandleResolver { - public FileHandle resolve(String fileName); + public FileHandle resolve (String fileName); } diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/MusicLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/MusicLoader.java index 66404800d57..564f1cb37e5 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/MusicLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/MusicLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.Gdx; diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/MusicParameter.java b/gdx/src/com/badlogic/gdx/assets/loaders/MusicParameter.java index e44e9f534f8..c98a032311c 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/MusicParameter.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/MusicParameter.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; public class MusicParameter { diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/PixmapLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/PixmapLoader.java index 0783a58ab9e..69aa11f180d 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/PixmapLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/PixmapLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.assets.AssetDescriptor; @@ -11,11 +12,11 @@ public PixmapLoader (FileHandleResolver resolver) { } Pixmap pixmap; - + @Override public void loadAsync (AssetManager manager, String fileName, PixmapParameter parameter) { pixmap = null; - pixmap = new Pixmap(resolve(fileName)); + pixmap = new Pixmap(resolve(fileName)); } @Override diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/PixmapParameter.java b/gdx/src/com/badlogic/gdx/assets/loaders/PixmapParameter.java index 4ba39563271..d635f122cbd 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/PixmapParameter.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/PixmapParameter.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; public class PixmapParameter { diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/SoundLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/SoundLoader.java index bb808fa8793..3f199146875 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/SoundLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/SoundLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.Gdx; diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/SoundParameter.java b/gdx/src/com/badlogic/gdx/assets/loaders/SoundParameter.java index a1aa8fc6c6a..c37204fb108 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/SoundParameter.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/SoundParameter.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; public class SoundParameter { diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/SynchronousAssetLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/SynchronousAssetLoader.java index 014a70f8079..0da48183b1a 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/SynchronousAssetLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/SynchronousAssetLoader.java @@ -1,11 +1,12 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.assets.AssetManager; -public abstract class SynchronousAssetLoader extends AssetLoader{ +public abstract class SynchronousAssetLoader extends AssetLoader { public SynchronousAssetLoader (FileHandleResolver resolver) { super(resolver); } - public abstract T load(AssetManager assetManager, String fileName, P parameter); + public abstract T load (AssetManager assetManager, String fileName, P parameter); } diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasLoader.java index 7a8e5c78fef..74785b821b1 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasLoader.java @@ -1,6 +1,6 @@ + package com.badlogic.gdx.assets.loaders; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.files.FileHandle; @@ -10,20 +10,20 @@ import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData.Page; import com.badlogic.gdx.utils.Array; -public class TextureAtlasLoader extends SynchronousAssetLoader{ +public class TextureAtlasLoader extends SynchronousAssetLoader { public TextureAtlasLoader (FileHandleResolver resolver) { super(resolver); } TextureAtlasData data; - + @Override public TextureAtlas load (AssetManager assetManager, String fileName, TextureAtlasParameter parameter) { - for(Page page: data.getPages()) { + for (Page page : data.getPages()) { Texture texture = assetManager.get(page.textureFile.path().replaceAll("\\\\", "/"), Texture.class); page.texture = texture; } - + return new TextureAtlas(data); } @@ -31,12 +31,14 @@ public TextureAtlas load (AssetManager assetManager, String fileName, TextureAtl public Array getDependencies (String fileName, TextureAtlasParameter parameter) { FileHandle atlasFile = resolve(fileName); FileHandle imgDir = atlasFile.parent(); - - if(parameter != null) data = new TextureAtlasData(atlasFile, imgDir, parameter.flip); - else data = new TextureAtlasData(atlasFile, imgDir, false); - + + if (parameter != null) + data = new TextureAtlasData(atlasFile, imgDir, parameter.flip); + else + data = new TextureAtlasData(atlasFile, imgDir, false); + Array dependencies = new Array(); - for(Page page: data.getPages()) { + for (Page page : data.getPages()) { FileHandle handle = resolve(page.textureFile.path()); TextureParameter params = new TextureParameter(); params.format = page.format; diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasParameter.java b/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasParameter.java index 263dfd1762a..213ff9fb174 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasParameter.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/TextureAtlasParameter.java @@ -1,6 +1,5 @@ -package com.badlogic.gdx.assets.loaders; -import com.badlogic.gdx.files.FileHandle; +package com.badlogic.gdx.assets.loaders; public class TextureAtlasParameter { /** whether to flip the texture atlas vertically **/ diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java index 897d6240ecc..9d36d2a5f97 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.assets.AssetDescriptor; @@ -14,11 +15,11 @@ public class TextureLoader extends AsynchronousAssetLoader { TextureData data; Texture texture; - + public TextureLoader (FileHandleResolver resolver) { super(resolver); } - + @Override public void loadAsync (AssetManager manager, String fileName, TextureParameter parameter) { FileHandle handle = resolve(fileName); @@ -26,31 +27,31 @@ public void loadAsync (AssetManager manager, String fileName, TextureParameter p Format format = null; boolean genMipMaps = false; texture = null; - - if(parameter != null) { + + if (parameter != null) { format = parameter.format; genMipMaps = parameter.genMipMaps; texture = parameter.texture; } - + data = new FileTextureData(handle, pixmap, format, genMipMaps); } @Override public Texture loadSync () { - if(texture != null) { + if (texture != null) { texture.load(data); return texture; } else { return new ReferenceCountedTexture(data); - } + } } @Override public Array getDependencies (String fileName, TextureParameter parameter) { return null; } - + public static class ReferenceCountedTexture extends Texture implements ReferenceCountedAsset { public ReferenceCountedTexture (TextureData data) { super(data); @@ -67,11 +68,11 @@ public void incRefCount () { public int getRefCount () { return refCount; } - + @Override - public void dispose() { - refCount --; - if(refCount > 0) return; + public void dispose () { + refCount--; + if (refCount > 0) return; super.dispose(); } } diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/TextureParameter.java b/gdx/src/com/badlogic/gdx/assets/loaders/TextureParameter.java index 26cb393ff77..c6763ec57b0 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/TextureParameter.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/TextureParameter.java @@ -1,11 +1,12 @@ + package com.badlogic.gdx.assets.loaders; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.graphics.Pixmap.Format; -import com.badlogic.gdx.graphics.TextureData; import com.badlogic.gdx.graphics.Texture; +import com.badlogic.gdx.graphics.TextureData; -public class TextureParameter implements AssetLoaderParameters{ +public class TextureParameter implements AssetLoaderParameters { /** the format of the final Texture. Uses the source images format if null **/ public Format format = null; /** whether to generate mipmaps **/ diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/ExternalFileHandleResolver.java b/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/ExternalFileHandleResolver.java index dfeac33d4d4..db6766613c5 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/ExternalFileHandleResolver.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/ExternalFileHandleResolver.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders.resolvers; import com.badlogic.gdx.Gdx; diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/InternalFileHandleResolver.java b/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/InternalFileHandleResolver.java index 29a7fce1e71..520284b3f66 100644 --- a/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/InternalFileHandleResolver.java +++ b/gdx/src/com/badlogic/gdx/assets/loaders/resolvers/InternalFileHandleResolver.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.assets.loaders.resolvers; import com.badlogic.gdx.Gdx; diff --git a/gdx/src/com/badlogic/gdx/audio/AudioDevice.java b/gdx/src/com/badlogic/gdx/audio/AudioDevice.java index 4d02827cc2a..b268bdedde6 100644 --- a/gdx/src/com/badlogic/gdx/audio/AudioDevice.java +++ b/gdx/src/com/badlogic/gdx/audio/AudioDevice.java @@ -13,50 +13,38 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; import com.badlogic.gdx.utils.Disposable; -/** - * Encapsulates an audio device in 44.1khz mono or stereo mode. Use the {@link #writeSamples(float[], int, int)} and +/** Encapsulates an audio device in 44.1khz mono or stereo mode. Use the {@link #writeSamples(float[], int, int)} and * {@link #writeSamples(short[], int, int)} 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 - * - */ + * @author badlogicgames@gmail.com */ public interface AudioDevice extends Disposable { - /** - * @return whether this AudioDevice is in mono or stereo mode. - */ + /** @return whether this AudioDevice is in mono or stereo mode. */ 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 - */ + * @param numSamples the number of samples to write to the device */ 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 - */ + * @param numSamples the number of samples to write to the device */ public void writeSamples (float[] samples, int offset, int numSamples); - - /** - * @return the latency in samples. - */ - public int getLatency(); - /** - * Frees all resources associated with this AudioDevice. Needs to be called when the device is no longer needed. - */ + /** @return the latency in samples. */ + public int getLatency (); + + /** Frees all resources associated with this AudioDevice. Needs to be called when the device is no longer needed. */ public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java b/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java index 547eafc9e80..a1337a11e32 100644 --- a/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java +++ b/gdx/src/com/badlogic/gdx/audio/AudioRecorder.java @@ -13,31 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; import com.badlogic.gdx.utils.Disposable; -/** - * An AudioRecorder allows to record input from an audio device. It has a sampling rate and is either stereo or mono. Samples are +/** 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. Stereo samples are interleaved in the order left channel, right channel. The * AudioRecorder has to be disposed if no longer needed via the {@link #dispose()}. * - * @author mzechner - * - */ + * @author mzechner */ public interface AudioRecorder extends Disposable { - /** - * Reads in numSamples samples into the array samples starting at offset. If the recorder is in stereo you have to multiply + /** 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 - */ + * @param numSamples the number of samples to be read */ public void read (short[] samples, int offset, int numSamples); - /** - * Disposes the AudioRecorder - */ + /** Disposes the AudioRecorder */ public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/Music.java b/gdx/src/com/badlogic/gdx/audio/Music.java index 84b58010880..f224058b48e 100644 --- a/gdx/src/com/badlogic/gdx/audio/Music.java +++ b/gdx/src/com/badlogic/gdx/audio/Music.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; import com.badlogic.gdx.Application; @@ -21,8 +22,7 @@ import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Disposable; -/** - *

        +/**

        * A Music instance represents a streamed audio file. The interface supports setting the play back position, pausing and resuming * and so on. When you are done with using the Music instance you have to dispose it via the {@link #dispose()} method. *

        @@ -36,59 +36,39 @@ * {@link ApplicationListener}. *

        * - * @author mzechner - * - */ + * @author mzechner */ public interface Music extends Disposable { - /** - * Starts the play back of the music stream. In case the stream was paused this will resume the play back. In case the music - * stream is finished playing this will restart the play back. - */ + /** Starts the play back of the music stream. In case the stream was paused this will resume the play back. In case the music + * stream is finished playing this will restart the play back. */ public void play (); - /** - * Pauses the play back. If the music stream has not been started yet or has finished playing a call to this method will be - * ignored. - */ + /** Pauses the play back. If the music stream has not been started yet or has finished playing a call to this method will be + * ignored. */ 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 (); - /** - * @return whether this music stream is playing - */ + /** @return whether this music stream is playing */ public boolean isPlaying (); - /** - * Sets whether the music stream is looping. This can be called at any time, whether the stream is playing. + /** Sets whether the music stream is looping. This can be called at any time, whether the stream is playing. * - * @param isLooping whether to loop the stream - */ + * @param isLooping whether to loop the stream */ public void setLooping (boolean isLooping); - /** - * @return whether the music stream is playing. - */ + /** @return whether the music stream is playing. */ 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 + /** 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 - */ + * @param volume */ public void setVolume (float volume); - /** - * Returns the playback position in milliseconds. - */ + /** Returns the playback position in milliseconds. */ public float getPosition (); - /** - * Needs to be called when the Music is no longer needed. - */ + /** Needs to be called when the Music is no longer needed. */ public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/audio/Sound.java b/gdx/src/com/badlogic/gdx/audio/Sound.java index 9e484f17352..698803d23c5 100644 --- a/gdx/src/com/badlogic/gdx/audio/Sound.java +++ b/gdx/src/com/badlogic/gdx/audio/Sound.java @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio; import com.badlogic.gdx.Audio; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Disposable; -/** - *

        +/**

        * A Sound is a short audio clip that can be played numerous times in parallel. It's completely loaded into memory so only load * small audio files. Call the {@link #dispose()} method when you're done using the Sound. *

        @@ -29,28 +29,18 @@ * Sound instances are created via a call to {@link Audio#newSound(FileHandle)}. *

        * - * @author badlogicgames@gmail.com - * - */ + * @author badlogicgames@gmail.com */ public interface Sound extends Disposable { - /** - * Plays the sound. If the sound is already playing, it will be played again, concurrently. - */ + /** Plays the sound. If the sound is already playing, it will be played again, concurrently. */ public void play (); - /** - * Plays the sound. If the sound is already playing, it will be played again, concurrently. - * @param volume the volume in the range [0,1] - */ + /** Plays the sound. If the sound is already playing, it will be played again, concurrently. + * @param volume the volume in the range [0,1] */ public void play (float volume); - /** - * Stops playing all instances of this sound. - */ + /** Stops playing all instances of this sound. */ public void stop (); - /** - * Releases all the resources. - */ + /** Releases all the resources. */ 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 4a925eaa5fc..b3bbcb6560e 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/AudioTools.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/AudioTools.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.analysis; import java.nio.ByteBuffer; @@ -20,90 +21,73 @@ import java.nio.FloatBuffer; import java.nio.ShortBuffer; -/** - * Class holding various static native methods for processing audio data. - * - * @author mzechner +/** Class holding various static native methods for processing audio data. * - */ + * @author mzechner */ 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 + /** 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. All buffers must be * direct. * * @param source the source buffer * @param target the target buffer - * @param numSamples the number of samples - */ + * @param numSamples the number of samples */ 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 + /** 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. All buffers must be * direct. * * @param source the source buffer * @param target the target buffer - * @param numSamples the number of samples - */ + * @param numSamples the number of samples */ public static native void convertToShort (FloatBuffer 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 + /** 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. All buffers must be direct. * * @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) - */ + * @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); - /** - * Converts the samples in source which are assumed to be interleaved left/right stereo samples to mono, writting the converted + /** 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. All buffers must be direct. * * @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) - */ + * @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); - /** - * Calculates the spectral flux between the two given spectra. Both buffers are assumed to hold numSamples elements. Spectrum B + /** 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. All buffers must be direct. * * @param spectrumA the first spectrum * @param spectrumB 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); - /** - * Allcoates a direct buffer for the given number of samples and channels. The final numer of samples is numSamples * + /** 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 - */ + * @return the direct buffer */ 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 * + /** 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 - */ + * @return the direct buffer */ public static ShortBuffer allocateShortBuffer (int numSamples, int numChannels) { ByteBuffer b = ByteBuffer.allocateDirect(numSamples * numChannels * 2); b.order(ByteOrder.nativeOrder()); diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java b/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java index 205a5eae5fc..f70002a7dc9 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/DFT.java @@ -13,8 +13,7 @@ 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 +/** 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. @@ -23,17 +22,13 @@ * * @see FourierTransform * @see FFT - * @see The Discrete Fourier Transform - * - */ + * @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 + /** 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 - */ + * @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."); @@ -46,15 +41,11 @@ protected void allocateArrays () { imag = new float[timeSize / 2 + 1]; } - /** - * Not currently implemented. - */ + /** Not currently implemented. */ public void scaleBand (int i, float s) { } - /** - * Not currently implemented. - */ + /** Not currently implemented. */ public void setBand (int i, float a) { } diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java b/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java index fe0cfcc2148..334e893d1b0 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/FFT.java @@ -13,8 +13,7 @@ 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 +/** 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 @@ -23,18 +22,14 @@ * @see FourierTransform * @see The Fast Fourier Transform * - * @author Damien Di Fede - * - */ + * @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 + /** 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 - */ + * @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."); @@ -129,12 +124,10 @@ public void forward (float[] buffer) { fillSpectrum(); } - /** - * Performs a forward transform on the passed buffers. + /** 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 - */ + * @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()."); @@ -218,9 +211,9 @@ private void buildTrigTables () { } } -// 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 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 af993972d5e..0b3ea36b46d 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/FourierTransform.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/FourierTransform.java @@ -13,8 +13,7 @@ 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 +/** 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. @@ -91,8 +90,7 @@ * modify it in some other way. * * @author Damien Di Fede - * @see The Discrete Fourier Transform - */ + * @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; @@ -114,13 +112,11 @@ public abstract class FourierTransform { protected int octaves; protected int avgPerOctave; - /** - * Construct a FourierTransform that will analyze sample buffers that are ts samples long and contain samples with + /** 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 - */ + * @param sr the sample rate of the samples that will be analyzed */ FourierTransform (int ts, float sr) { timeSize = ts; sampleRate = (int)sr; @@ -189,21 +185,16 @@ protected void fillSpectrum () { } } - /** - * Sets the object to not compute averages. - * - */ + /** 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, + /** 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 - */ + * @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 @@ -214,16 +205,14 @@ public void linAverages (int 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 + /** 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 - */ + * @param bandsPerOctave how many bands to split each octave into */ public void logAverages (int minBandwidth, int bandsPerOctave) { float nyq = (float)sampleRate / 2f; octaves = 1; @@ -235,12 +224,10 @@ public void logAverages (int minBandwidth, int 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 + /** 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 - */ + * @param which FourierTransform.HAMMING or FourierTransform.NONE */ public void window (int which) { if (which < 0 || which > 1) { throw new IllegalArgumentException("Invalid window type."); @@ -264,71 +251,57 @@ protected void hamming (float[] samples) { } } - /** - * Returns the length of the time domain signal expected by this transform. + /** Returns the length of the time domain signal expected by this transform. * - * @return 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 + /** 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 - */ + * @return the size of the spectrum */ public int specSize () { return spectrum.length; } - /** - * Returns the amplitude of the requested frequency band. + /** Returns the amplitude of the requested frequency band. * * @param i the index of a frequency band - * @return the amplitude of the requested 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 + /** 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. - */ + * @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 + /** 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 - */ + * @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 + /** 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 - */ + * @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. + /** 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 - */ + * @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; @@ -340,10 +313,8 @@ public int freqToIndex (float freq) { return i; } - /** - * Returns the middle frequency of the ith band. - * @param i the index of the band you want to middle frequency of - */ + /** 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. @@ -362,11 +333,9 @@ public float indexToFreq (int i) { return i * bw; } - /** - * Returns the center frequency of the ith average band. + /** Returns the center frequency of the ith average band. * - * @param i which average band you want the center frequency of. - */ + * @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 @@ -400,51 +369,41 @@ public float getAverageCenterFrequency (int i) { return 0; } - /** - * Gets the amplitude of the requested frequency in the spectrum. + /** 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 - */ + * @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. + /** Sets the amplitude of the requested frequency in the spectrum to a. * * @param freq the frequency in Hz - * @param a the new amplitude - */ + * @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. + /** Scales the amplitude of the requested frequency by a. * * @param freq the frequency in Hz - * @param s the scaling factor - */ + * @param s the scaling factor */ public void scaleFreq (float freq, float s) { scaleBand(freqToIndex(freq), s); } - /** - * Returns the number of averages currently being calculated. + /** Returns the number of averages currently being calculated. * - * @return the length of the averages array - */ + * @return the length of the averages array */ public int avgSize () { return averages.length; } - /** - * Gets the value of the ith average. + /** Gets the value of the ith average. * * @param i the average you want the value of - * @return the value of the requested average band - */ + * @return the value of the requested average band */ public float getAvg (int i) { float ret; if (averages.length > 0) @@ -454,13 +413,11 @@ public float getAvg (int i) { return ret; } - /** - * Calculate the average amplitude of the frequency band bounded by lowFreq and hiFreq, inclusive. + /** 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 - */ + * @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); @@ -472,21 +429,16 @@ public float calcAvg (float lowFreq, float hiFreq) { return avg; } - /** - * Performs a forward transform on buffer. + /** Performs a forward transform on buffer. * - * @param buffer the buffer to analyze - */ + * @param buffer the buffer to analyze */ public abstract void forward (float[] buffer); - /** - * Performs a forward transform on values in 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. - * - */ + * 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 @@ -499,43 +451,33 @@ public void forward (float[] buffer, int startAt) { forward(section); } - /** - * Performs an inverse transform of the frequency spectrum and places the result in buffer. + /** 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 - */ + * @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 + /** 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 - */ + * @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. - */ + /** @return the spectrum of the last FourierTransform.forward() call. */ public float[] getSpectrum () { return spectrum; } - /** - * @return the real part of the last FourierTransform.forward() call. - */ + /** @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. - */ + /** @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 ec1313e570f..26d799c1c1a 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/KissFFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/KissFFT.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.analysis; import java.nio.FloatBuffer; @@ -20,61 +21,46 @@ import com.badlogic.gdx.utils.Disposable; -/** - * A class for spectral analysis using native KissFFT - * @author mzechner - * - */ +/** A class for spectral analysis using native KissFFT + * @author mzechner */ public class KissFFT implements Disposable { /** 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. - */ + * @param numSamples the number of samples to be analysed. */ public KissFFT (int numSamples) { handle = create(numSamples); } - /** - * Creates a new kiss fft object + /** Creates a new kiss fft object * @param timeSize the number of samples - * @return the handle to the kiss fft object - */ + * @return the handle to the kiss fft object */ private native long create (int timeSize); - /** - * Destroys a kiss fft object - * @param handle the handle to the kiss fft object - */ + /** Destroys a kiss fft object + * @param handle the handle to the kiss fft object */ 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 + /** 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 - */ + * @param spectrum the 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 + /** 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 - */ + * @param spectrum the spectrum */ public void spectrum (ShortBuffer samples, FloatBuffer spectrum) { spectrum(handle, samples, spectrum); } - /** - * Releases all resources of this object - */ + /** Releases all resources of this object */ public void dispose () { destroy(handle); } @@ -91,41 +77,41 @@ public void getImagPart (ShortBuffer imag) { 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; -// short samples[] = new short[1024]; +// 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; +// short samples[] = new short[1024]; // -// for (int i = 0; i < samples.length; i++) { -// float value = (float)Math.sin(angle); -// samples[i] = (short)(value * 32767); -// angle += increment; -// } +// 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); +// 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.spectrum(samplesBuffer, spectrum); // -// fft.getRealPart(realBuffer); -// fft.getImagPart(imagBuffer); -// short[] re = new short[512]; -// short[] im = new short[512]; -// float[] sp = new float[513]; -// realBuffer.position(0); -// realBuffer.get(re); -// imagBuffer.position(0); -// imagBuffer.get(im); -// spectrum.position(0); -// spectrum.get(sp); +// fft.getRealPart(realBuffer); +// fft.getImagPart(imagBuffer); +// short[] re = new short[512]; +// short[] im = new short[512]; +// float[] sp = new float[513]; +// realBuffer.position(0); +// realBuffer.get(re); +// imagBuffer.position(0); +// 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 dc40253891d..30f92216302 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/NativeFFT.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/NativeFFT.java @@ -13,18 +13,16 @@ * 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 com.badlogic.gdx.utils.Disposable; -/** - * A native implementation of the Fast Fourier Transform, directly ported from the {@link FFT} class. - * - * @author mzechner +/** A native implementation of the Fast Fourier Transform, directly ported from the {@link FFT} class. * - */ + * @author mzechner */ public class NativeFFT implements Disposable { /** the handle to the native fft instance **/ private long handle; diff --git a/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java b/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java index c8d60264934..6833b31cd1c 100644 --- a/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java +++ b/gdx/src/com/badlogic/gdx/audio/analysis/ThresholdFunction.java @@ -13,17 +13,15 @@ * 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. - * - * @author badlogicgames@gmail.com +/** Calculates a threshold function based on the spectral flux. * - */ + * @author badlogicgames@gmail.com */ public class ThresholdFunction { /** the history size **/ private final int historySize; @@ -31,23 +29,19 @@ public class ThresholdFunction { /** 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 + /** 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. - */ + * @param multiplier The average 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. - */ + * @return The threshold function. */ public List calculate (List spectralFlux) { ArrayList thresholds = new ArrayList(spectralFlux.size()); diff --git a/gdx/src/com/badlogic/gdx/audio/io/Decoder.java b/gdx/src/com/badlogic/gdx/audio/io/Decoder.java index 0ce7abcd335..fe47bef9f52 100644 --- a/gdx/src/com/badlogic/gdx/audio/io/Decoder.java +++ b/gdx/src/com/badlogic/gdx/audio/io/Decoder.java @@ -13,53 +13,39 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.audio.io; import java.nio.ShortBuffer; import com.badlogic.gdx.utils.Disposable; -/** - * 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 +/** 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 extends Disposable { - /** - * Reads in samples.capacity() samples in 16-bit signed PCM format from the decoder. Returns the actual number read in. If this + /** 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. The provided ShortBuffer must be * a direct buffer. * - * @param samples The number of read samples. - */ + * @param samples The number of read 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. - */ + * @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); - /** - * @return the number of channels - */ + /** @return the number of channels */ public int getNumChannels (); - /** - * @return the sampling rate in herz, e.g. 44100 - */ + /** @return the sampling rate in herz, e.g. 44100 */ public int getRate (); - /** - * @return the length of the file in seconds - */ + /** @return the length of the file in seconds */ public float getLength (); - /** - * Disposes the decoder and frees all associated resources - */ + /** Disposes the decoder and frees all associated resources */ 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 753050cba33..d03ab17367b 100644 --- a/gdx/src/com/badlogic/gdx/audio/io/Mpg123Decoder.java +++ b/gdx/src/com/badlogic/gdx/audio/io/Mpg123Decoder.java @@ -13,63 +13,51 @@ * 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. - * - * @author mzechner +/** A {@link Decoder} implementation that decodes MP3 files via libmpg123 natively. * - */ + * @author mzechner */ 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 - */ + * @param filename the filename */ public Mpg123Decoder (String filename) { handle = openFile(filename); if (handle == -1) throw new IllegalArgumentException("couldn't open file"); } - /** - * {@inheritDoc} - */ - @Override public int readSamples (ShortBuffer samples) { + /** {@inheritDoc} */ + @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) { + /** {@inheritDoc} */ + @Override + public int skipSamples (int numSamples) { return skipSamples(handle, numSamples); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public int getNumChannels () { return getNumChannels(handle); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public int getRate () { return getRate(handle); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public float getLength () { return getLength(handle); } @@ -88,10 +76,9 @@ public float getLength () { private native void closeFile (long handle); - /** - * {@inheritDoc} - */ - @Override public void dispose () { + /** {@inheritDoc} */ + @Override + public void dispose () { closeFile(handle); } } diff --git a/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java b/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java index 9e23b9b1639..bc6fd9ee736 100644 --- a/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java +++ b/gdx/src/com/badlogic/gdx/audio/io/VorbisDecoder.java @@ -13,70 +13,60 @@ * 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 tremor - * @author mzechner - * - */ +/** A {@link Decoder} implementation that decodes OGG Vorbis files using tremor + * @author mzechner */ 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 - */ + * @param filename the filename */ public VorbisDecoder (String filename) { handle = openFile(filename); if (handle == 0) throw new IllegalArgumentException("couldn't open file '" + filename + "'"); } - /** - * {@inheritDoc} - */ - @Override public void dispose () { + /** {@inheritDoc} */ + @Override + public void dispose () { closeFile(handle); } - /** - * {@inheritDoc} - */ - @Override public float getLength () { + /** {@inheritDoc} */ + @Override + public float getLength () { return getLength(handle); } - /** - * {@inheritDoc} - */ - @Override public int getNumChannels () { + /** {@inheritDoc} */ + @Override + public int getNumChannels () { return getNumChannels(handle); } - /** - * {@inheritDoc} - */ - @Override public int getRate () { + /** {@inheritDoc} */ + @Override + public int getRate () { return getRate(handle); } - /** - * {@inheritDoc} - */ - @Override public int readSamples (ShortBuffer samples) { + /** {@inheritDoc} */ + @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) { + /** {@inheritDoc} */ + @Override + public int skipSamples (int numSamples) { return skipSamples(handle, numSamples); } diff --git a/gdx/src/com/badlogic/gdx/files/FileHandle.java b/gdx/src/com/badlogic/gdx/files/FileHandle.java index 61db337f311..56cab03f219 100644 --- a/gdx/src/com/badlogic/gdx/files/FileHandle.java +++ b/gdx/src/com/badlogic/gdx/files/FileHandle.java @@ -30,12 +30,10 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Represents a file or directory on the filesystem, classpath, Android SD card, or Android assets directory. FileHandles are +/** Represents a file or directory on the filesystem, classpath, Android SD card, or Android assets directory. FileHandles are * created via a {@link Files} instance. * @author mzechner - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class FileHandle { protected File file; protected FileType type; @@ -43,30 +41,22 @@ public class FileHandle { protected FileHandle () { } - /** - * Creates a new absolute FileHandle for the file name. Use this - * for tools on the desktop that don't need any of the backends. - * Do not use this constructor in case you write something cross-platform. - * Use the {@link Files} interface instead. - * @param fileName the filename. - */ - public FileHandle(String fileName) { + /** Creates a new absolute FileHandle for the file name. Use this for tools on the desktop that don't need any of the backends. + * Do not use this constructor in case you write something cross-platform. Use the {@link Files} interface instead. + * @param fileName the filename. */ + public FileHandle (String fileName) { this.file = new File(fileName); this.type = FileType.Absolute; } - - /** - * Creates a new absolute FileHandle for the {@link File}. Use this - * for tools on the desktop that don't need any of the backends. - * Do not use this constructor in case you write something cross-platform. - * Use the {@link Files} interface instead. - * @param file the file. - */ - public FileHandle(File file) { + + /** Creates a new absolute FileHandle for the {@link File}. Use this for tools on the desktop that don't need any of the + * backends. Do not use this constructor in case you write something cross-platform. Use the {@link Files} interface instead. + * @param file the file. */ + public FileHandle (File file) { this.file = file; this.type = FileType.Absolute; } - + protected FileHandle (String fileName, FileType type) { this.type = type; file = new File(fileName); @@ -108,10 +98,8 @@ private File file () { return file; } - /** - * Returns a stream for reading this file. - * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. - */ + /** Returns a stream for reading this file. + * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public InputStream read () { if (type == FileType.Classpath || (type == FileType.Internal && !file.exists())) { InputStream input = FileHandle.class.getResourceAsStream("/" + file.getPath().replace('\\', '/')); @@ -127,18 +115,14 @@ public InputStream read () { } } - /** - * Reads the entire file into a string using the platform's default charset. - * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. - */ + /** Reads the entire file into a string using the platform's default charset. + * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public String readString () { return readString(null); } - /** - * Reads the entire file into a string using the specified charset. - * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. - */ + /** Reads the entire file into a string using the specified charset. + * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public String readString (String charset) { StringBuilder output = new StringBuilder(512); InputStreamReader reader = null; @@ -164,10 +148,8 @@ public String readString (String charset) { return output.toString(); } - /** - * Reads the entire file into a byte array. - * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. - */ + /** Reads the entire file into a byte array. + * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public byte[] readBytes () { int length = (int)length(); if (length == 0) length = 512; @@ -203,12 +185,10 @@ public byte[] readBytes () { return buffer; } - /** - * Returns a stream for writing to this file. + /** Returns a stream for writing to this file. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or - * {@link FileType#Internal} file, or if it could not be written. - */ + * {@link FileType#Internal} file, or if it could not be written. */ public OutputStream write (boolean append) { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot write to a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot write to an internal file: " + file); @@ -221,11 +201,9 @@ public OutputStream write (boolean append) { } } - /** - * Returns the paths to the children of this directory. Returns an empty list if this file handle represents a file and not a + /** Returns the paths to the children of this directory. Returns an empty list if this file handle represents a file and not a * directory. On the desktop, an internal handle to a directory on the classpath will return a zero length array. - * @throw GdxRuntimeException if this file is an {@link FileType#Classpath} file. - */ + * @throw GdxRuntimeException if this file is an {@link FileType#Classpath} file. */ public FileHandle[] list () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot list a classpath directory: " + file); String[] relativePaths = file().list(); @@ -236,12 +214,10 @@ public FileHandle[] list () { return handles; } - /** - * Returns the paths to the children of this directory with the specified suffix. Returns an empty list if this file handle + /** Returns the paths to the children of this directory with the specified suffix. Returns an empty list if this file handle * represents a file and not a directory. On the desktop, an internal handle to a directory on the classpath will return a zero * length array. - * @throw GdxRuntimeException if this file is an {@link FileType#Classpath} file. - */ + * @throw GdxRuntimeException if this file is an {@link FileType#Classpath} file. */ public FileHandle[] list (String suffix) { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot list a classpath directory: " + file); String[] relativePaths = file().list(); @@ -262,21 +238,17 @@ public FileHandle[] list (String suffix) { return handles; } - /** - * Returns true if this file is a directory. Always returns false for classpath files. On Android, an internal handle to an - * empty directory will return false. On the desktop, an internal handle to a directory on the classpath will return false. - */ + /** Returns true if this file is a directory. Always returns false for classpath files. On Android, an internal handle to an + * empty directory will return false. On the desktop, an internal handle to a directory on the classpath will return false. */ public boolean isDirectory () { if (type == FileType.Classpath) return false; return file().isDirectory(); } - /** - * Returns a handle to the child with the specified name. + /** Returns a handle to the child with the specified name. * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the child - * doesn't exist. - */ + * doesn't exist. */ public FileHandle child (String name) { if (file.getPath().length() == 0) return new FileHandle(new File(name), type); return new FileHandle(new File(file, name), type); @@ -293,18 +265,14 @@ public FileHandle parent () { return new FileHandle(parent, type); } - /** - * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. - */ + /** @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */ public void mkdirs () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot mkdirs with a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot mkdirs with an internal file: " + file); file().mkdirs(); } - /** - * Returns true if the file exists. On Android, a classpath handle to a directory will always return false. - */ + /** Returns true if the file exists. On Android, a classpath handle to a directory will always return false. */ public boolean exists () { switch (type) { case Internal: @@ -316,30 +284,24 @@ public boolean exists () { return file().exists(); } - /** - * Deletes this file or empty directory and returns success. Will not delete a directory that has children. - * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. - */ + /** Deletes this file or empty directory and returns success. Will not delete a directory that has children. + * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */ public boolean delete () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot delete a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot delete an internal file: " + file); return file().delete(); } - /** - * Deletes this file or directory and all children, recursively. - * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. - */ + /** Deletes this file or directory and all children, recursively. + * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */ public boolean deleteDirectory () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot delete a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot delete an internal file: " + file); return deleteDirectory(file()); } - /** - * Copies this file to the specified file, overwriting the file if it already exists. - * @throw GdxRuntimeException if the destination file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. - */ + /** Copies this file to the specified file, overwriting the file if it already exists. + * @throw GdxRuntimeException if the destination file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */ public void copyTo (FileHandle dest) { InputStream input = null; OutputStream output = null; @@ -367,11 +329,9 @@ public void copyTo (FileHandle dest) { } } - /** - * Moves this file to the specified file, overwriting the file if it already exists. + /** Moves this file to the specified file, overwriting the file if it already exists. * @throw GdxRuntimeException if the source or destination file handle is a {@link FileType#Classpath} or - * {@link FileType#Internal} file. - */ + * {@link FileType#Internal} file. */ public void moveTo (FileHandle dest) { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot move a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot move an internal file: " + file); @@ -379,10 +339,8 @@ public void moveTo (FileHandle dest) { delete(); } - /** - * Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be - * determined. - */ + /** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be + * determined. */ public long length () { if (type == FileType.Classpath || (type == FileType.Internal && !file.exists())) { InputStream input = read(); diff --git a/gdx/src/com/badlogic/gdx/files/FileHandleStream.java b/gdx/src/com/badlogic/gdx/files/FileHandleStream.java index de8465c8f5d..3d6de4ef6be 100644 --- a/gdx/src/com/badlogic/gdx/files/FileHandleStream.java +++ b/gdx/src/com/badlogic/gdx/files/FileHandleStream.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.files; import java.io.File; @@ -21,11 +22,9 @@ import com.badlogic.gdx.Files.FileType; -/** - * A FileHandle intended to be subclassed for the purpose of implementing {@link #read()} and/or {@link #write(boolean)}. Methods +/** A FileHandle intended to be subclassed for the purpose of implementing {@link #read()} and/or {@link #write(boolean)}. Methods * that would manipulate the file instead throw UnsupportedOperationException. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public abstract class FileHandleStream extends FileHandle { public FileHandleStream (String path) { super(new File(path), FileType.Absolute); diff --git a/gdx/src/com/badlogic/gdx/graphics/Camera.java b/gdx/src/com/badlogic/gdx/graphics/Camera.java index 1e486fc1ac4..65439a41cd3 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Camera.java +++ b/gdx/src/com/badlogic/gdx/graphics/Camera.java @@ -13,6 +13,7 @@ * 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,19 +25,16 @@ import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; -/** - * Base class for {@link OrthographicCamera} and {@link PerspectiveCamera}. - * @author mzechner - * - */ -public abstract class Camera { +/** Base class for {@link OrthographicCamera} and {@link PerspectiveCamera}. + * @author mzechner */ +public abstract class Camera { /** the position of the camera **/ public final Vector3 position = new Vector3(); /** the unit length direction vector of the camera **/ public final Vector3 direction = new Vector3(0, 0, -1); /** the unit length up vector of the camera **/ public final Vector3 up = new Vector3(0, 1, 0); - + /** the projection matrix **/ public final Matrix4 projection = new Matrix4(); /** the view matrix **/ @@ -45,207 +43,167 @@ public abstract class Camera { public final Matrix4 combined = new Matrix4(); /** the inverse combined projection and view matrix **/ public final Matrix4 invProjectionView = new Matrix4(); - + /** the near clipping plane distance, has to be positive **/ - public float near = 1; + public float near = 1; /** the far clipping plane distance, has to be positive **/ public float far = 100; - + /** the viewport width **/ public float viewportWidth = 0; /** the viewport height **/ public float viewportHeight = 0; - + /** the frustum **/ public final Frustum frustum = new Frustum(); - + private final Matrix4 tmpMat = new Matrix4(); private final Vector3 tmpVec = new Vector3(); - - /** - * Recalculates the projection and view matrix of this - * camera and the {@link Frustum} planes. Use this after you've manipulated - * any of the attributes of the camera. - */ - public abstract void update(); - - /** - * Sets the current projection and model-view matrix of this camera. - * Only works with {@link GL10} and {@link GL11} of course. The parameter is there - * to remind you that it does not work with GL20. Make sure to call - * {@link #update()} before calling this method so all matrices are up to date. + + /** Recalculates the projection and view matrix of this camera and the {@link Frustum} planes. Use this after you've manipulated + * any of the attributes of the camera. */ + public abstract void update (); + + /** Sets the current projection and model-view matrix of this camera. Only works with {@link GL10} and {@link GL11} of course. + * The parameter is there to remind you that it does not work with GL20. Make sure to call {@link #update()} before calling + * this method so all matrices are up to date. * - * @param gl the GL10 or GL11 instance. - */ - public void apply(GL10 gl) { + * @param gl the GL10 or GL11 instance. */ + public void apply (GL10 gl) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadMatrixf(projection.val, 0); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadMatrixf(view.val, 0); } - - /** - * Recalculates the direction of the camera to look at the point - * (x, y, z). + + /** Recalculates the direction of the camera to look at the point (x, y, z). * @param x the x-coordinate of the point to look at * @param y the x-coordinate of the point to look at - * @param z the x-coordinate of the point to look at - */ - public void lookAt(float x, float y, float z) { + * @param z the x-coordinate of the point to look at */ + public void lookAt (float x, float y, float z) { direction.set(x, y, z).sub(position).nor(); } - - /** - * Normalizes the up vector by first calculating the - * right vector via a cross product between direction and up, - * and then recalculating the up vector via a cross product - * between right and direction. - */ + + /** Normalizes the up vector by first calculating the right vector via a cross product between direction and up, and then + * recalculating the up vector via a cross product between right and direction. */ final Vector3 right = new Vector3(); - public void normalizeUp() { + + public void normalizeUp () { right.set(direction).crs(up).nor(); up.set(right).crs(direction).nor(); } - /** - * Rotates the direction and up vector of this camera by the - * given angle around the given axis. The direction and up - * vector will not be orthogonalized. + + /** Rotates the direction and up vector of this camera by the given angle around the given axis. The direction and up vector + * will not be orthogonalized. * * @param angle the angle * @param axisX the x-component of the axis * @param axisY the y-component of the axis - * @param axisZ the z-component of the axis - */ - public void rotate(float angle, float axisX, float axisY, float axisZ) { + * @param axisZ the z-component of the axis */ + public void rotate (float angle, float axisX, float axisY, float axisZ) { tmpMat.setToRotation(tmpVec.set(axisX, axisY, axisZ), angle); direction.mul(tmpMat).nor(); up.mul(tmpMat).nor(); } - - /** - * Moves the camera by the given amount on each axis. + + /** Moves the camera by the given amount on each axis. * @param x the displacement on the x-axis * @param y the displacement on the y-axis - * @param z the displacement on the z-axis - */ - public void translate(float x, float y, float z) { + * @param z the displacement on the z-axis */ + public void translate (float x, float y, float z) { position.add(x, y, z); - } - - /** - * Function to translate a point given in window (or window) - * coordinates to world space. It's the same as {@link GLU#gluUnProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} - * but does not rely on OpenGL. The x- and y-coordinate of vec are assumed to be in window coordinates (origin is the - * top left corner, y pointing down, x pointing to the right) as reported by the - * touch methods in {@link Input}. A z-coordinate of 0 will return a point on the - * near plane, a z-coordinate of 1 will return a point on the far plane. This method allows you to - * specify the viewport position and dimensions in the coordinate system expected by {@link GLCommon#glViewport(int, int, int, int)}, with - * the origin in the bottom left corner of the screen. + } + + /** Function to translate a point given in window (or window) coordinates to world space. It's the same as + * {@link GLU#gluUnProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} but does not rely on + * OpenGL. The x- and y-coordinate of vec are assumed to be in window coordinates (origin is the top left corner, y pointing + * down, x pointing to the right) as reported by the touch methods in {@link Input}. A z-coordinate of 0 will return a point on + * the near plane, a z-coordinate of 1 will return a point on the far plane. This method allows you to specify the viewport + * position and dimensions in the coordinate system expected by {@link GLCommon#glViewport(int, int, int, int)}, with the + * origin in the bottom left corner of the screen. * * @param vec the point in window coordinates (origin top left) * @param viewportX the coordinate of the top left corner of the viewport in glViewport coordinates (origin bottom left) * @param viewportY the coordinate of the top left corner of the viewport in glViewport coordinates (origin bottom left) * @param viewportWidth the width of the viewport in pixels - * @param viewportHeight the height of the viewport in pixels - */ - public void unproject(Vector3 vec, float viewportX, float viewportY, float viewportWidth, float viewportHeight) { + * @param viewportHeight the height of the viewport in pixels */ + public void unproject (Vector3 vec, float viewportX, float viewportY, float viewportWidth, float viewportHeight) { float x = vec.x, y = vec.y; - x = x - viewportX; + x = x - viewportX; y = Gdx.graphics.getHeight() - y - 1; - y = y - viewportY; + y = y - viewportY; vec.x = (2 * x) / viewportWidth - 1; vec.y = (2 * y) / viewportHeight - 1; - vec.z = 2 * vec.z - 1; + vec.z = 2 * vec.z - 1; vec.prj(invProjectionView); } - - /** - * Function to translate a point given in window (or window) - * coordinates to world space. It's the same as {@link GLU#gluUnProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} - * but does not rely on OpenGL. The viewport is assuemd to span the whole screen - * and is fetched from {@link Graphics#getWidth()} and {@link Graphics#getHeight()}. The - * x- and y-coordinate of vec are assumed to be in window coordinates (origin is the - * top left corner, y pointing down, x pointing to the right) as reported by the - * touch methods in {@link Input}. A z-coordinate of 0 will return a point on the - * near plane, a z-coordinate of 1 will return a point on the far plane. + + /** Function to translate a point given in window (or window) coordinates to world space. It's the same as + * {@link GLU#gluUnProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} but does not rely on + * OpenGL. The viewport is assuemd to span the whole screen and is fetched from {@link Graphics#getWidth()} and + * {@link Graphics#getHeight()}. The x- and y-coordinate of vec are assumed to be in window coordinates (origin is the top left + * corner, y pointing down, x pointing to the right) as reported by the touch methods in {@link Input}. A z-coordinate of 0 + * will return a point on the near plane, a z-coordinate of 1 will return a point on the far plane. * - * @param vec the point in window coordinates - */ - public void unproject(Vector3 vec) { + * @param vec the point in window coordinates */ + public void unproject (Vector3 vec) { unproject(vec, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } - - /** - * Projects the {@link Vector3} given in object/world space to window coordinates. It's the - * same as {@link GLU#gluProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} with - * one small deviation: - * The viewport is assumed to span the whole screen. The window coordinate - * system has its origin in the bottom left, with the y-axis pointing upwards - * and the x-axis pointing to the right. This makes it easily useable in conjunction with - * {@link SpriteBatch} and similar classes. - * @param vec the position in object/world space. - */ - public void project(Vector3 vec) { + + /** Projects the {@link Vector3} given in object/world space to window coordinates. It's the same as + * {@link GLU#gluProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} with one small deviation: + * The viewport is assumed to span the whole screen. The window coordinate system has its origin in the bottom left, + * with the y-axis pointing upwards and the x-axis pointing to the right. This makes it easily useable in conjunction + * with {@link SpriteBatch} and similar classes. + * @param vec the position in object/world space. */ + public void project (Vector3 vec) { project(vec, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } - /** - * Projects the {@link Vector3} given in object/world space to window coordinates. It's the - * same as {@link GLU#gluProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} with - * one small deviation: - * The viewport is assumed to span the whole screen. The window coordinate - * system has its origin in the bottom left, with the y-axis pointing upwards - * and the x-axis pointing to the right. This makes it easily useable in conjunction with - * {@link SpriteBatch} and similar classes. This method allows you to - * specify the viewport position and dimensions in the coordinate system expected by {@link GLCommon#glViewport(int, int, int, int)}, with - * the origin in the bottom left corner of the screen. + /** Projects the {@link Vector3} given in object/world space to window coordinates. It's the same as + * {@link GLU#gluProject(float, float, float, float[], int, float[], int, int[], int, float[], int)} with one small deviation: + * The viewport is assumed to span the whole screen. The window coordinate system has its origin in the bottom left, + * with the y-axis pointing upwards and the x-axis pointing to the right. This makes it easily useable in conjunction + * with {@link SpriteBatch} and similar classes. This method allows you to specify the viewport position and dimensions in the + * coordinate system expected by {@link GLCommon#glViewport(int, int, int, int)}, with the origin in the bottom left corner of + * the screen. * * @param vec the point in object/world space * @param viewportX the coordinate of the top left corner of the viewport in glViewport coordinates (origin bottom left) * @param viewportY the coordinate of the top left corner of the viewport in glViewport coordinates (origin bottom left) * @param viewportWidth the width of the viewport in pixels - * @param viewportHeight the height of the viewport in pixels - */ + * @param viewportHeight the height of the viewport in pixels */ public void project (Vector3 vec, float viewportX, float viewportY, float viewportWidth, float viewportHeight) { vec.prj(combined); vec.x = viewportWidth * (vec.x + 1) / 2 + viewportX; vec.y = viewportHeight * (vec.y + 1) / 2 + viewportY; vec.z = (vec.z + 1) / 2; } - + final Ray ray = new Ray(new Vector3(), new Vector3()); - /** - * Creates a picking {@link Ray} from the coordinates given in window - * coordinates. It is assumed that the viewport spans the whole screen. - * The window coordinates origin is assumed to be in the top left corner, - * its y-axis pointing down, the x-axis pointing to the right. The - * returned instance is not a new instance but an internal member only - * accessible via this function. + + /** Creates a picking {@link Ray} from the coordinates given in window coordinates. It is assumed that the viewport spans the + * whole screen. The window coordinates origin is assumed to be in the top left corner, its y-axis pointing down, the x-axis + * pointing to the right. The returned instance is not a new instance but an internal member only accessible via this function. * * @param x the x-coordinate in window coordinates. * @param y the y-coordinate in window coordinates. - * @return the picking Ray. - */ - public Ray getPickRay(float x, float y, float viewportX, float viewportY, float viewportWidth, float viewportHeight) { + * @return the picking Ray. */ + public Ray getPickRay (float x, float y, float viewportX, float viewportY, float viewportWidth, float viewportHeight) { unproject(ray.origin.set(x, y, 0), viewportX, viewportY, viewportWidth, viewportHeight); unproject(ray.direction.set(x, y, 1), viewportX, viewportY, viewportWidth, viewportHeight); ray.direction.sub(ray.origin).nor(); return ray; - } - - /** - * Creates a picking {@link Ray} from the coordinates given in window - * coordinates. It is assumed that the viewport spans the whole screen. - * The window coordinates origin is assumed to be in the top left corner, - * its y-axis pointing down, the x-axis pointing to the right. The - * returned instance is not a new instance but an internal member only - * accessible via this function. + } + + /** Creates a picking {@link Ray} from the coordinates given in window coordinates. It is assumed that the viewport spans the + * whole screen. The window coordinates origin is assumed to be in the top left corner, its y-axis pointing down, the x-axis + * pointing to the right. The returned instance is not a new instance but an internal member only accessible via this function. * * @param x the x-coordinate in window coordinates. * @param y the y-coordinate in window coordinates. - * @return the picking Ray. - */ - public Ray getPickRay(float x, float y) { + * @return the picking Ray. */ + public Ray getPickRay (float x, float y) { return getPickRay(x, y, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/Color.java b/gdx/src/com/badlogic/gdx/graphics/Color.java index 2eb8c790ca4..47b392c3315 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Color.java +++ b/gdx/src/com/badlogic/gdx/graphics/Color.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.utils.NumberUtils; -/** - * A color class, holding the r, g, b and alpha component as floats in the range [0,1]. All methods perform clamping on the +/** 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 - * - */ + * @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); @@ -34,21 +32,17 @@ public class Color { /** the red, green, blue and alpha components **/ public float r, g, b, a; - /** - * Constructs a new Color with all components set to 0. - */ - public Color() { - + /** Constructs a new Color with all components set to 0. */ + public Color () { + } - - /** - * Constructor, sets the components of the color + + /** Constructor, sets the components of the color * * @param r the red component * @param g the green component * @param b the blue component - * @param a the alpha component - */ + * @param a the alpha component */ public Color (float r, float g, float b, float a) { this.r = r; this.g = g; @@ -57,20 +51,16 @@ public Color (float r, float g, float b, float a) { clamp(); } - /** - * Constructs a new color using the given color + /** Constructs a new color using the given color * - * @param color the color - */ + * @param color the color */ public Color (Color color) { set(color); } - /** - * Sets this color to the given color. + /** Sets this color to the given color. * - * @param color the Color - */ + * @param color the Color */ public Color set (Color color) { this.r = color.r; this.g = color.g; @@ -80,12 +70,10 @@ public Color set (Color color) { return this; } - /** - * Multiplies the this color and the given color + /** Multiplies the this color and the given color * * @param color the color - * @return this color. - */ + * @return this color. */ public Color mul (Color color) { this.r *= color.r; this.g *= color.g; @@ -95,12 +83,10 @@ public Color mul (Color color) { return this; } - /** - * 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 - */ + * @return this color */ public Color mul (float value) { this.r *= value; this.g *= value; @@ -110,12 +96,10 @@ public Color mul (float value) { return this; } - /** - * Adds the given color to this color. + /** Adds the given color to this color. * * @param color the color - * @return this color - */ + * @return this color */ public Color add (Color color) { this.r += color.r; this.g += color.g; @@ -125,12 +109,10 @@ public Color add (Color color) { return this; } - /** - * Subtracts the given color from this color + /** Subtracts the given color from this color * * @param color the color - * @return this color - */ + * @return this color */ public Color sub (Color color) { this.r -= color.r; this.g -= color.g; @@ -165,7 +147,8 @@ public void set (float r, float g, float b, float a) { this.a = a; } - @Override public boolean equals (Object o) { + @Override + public boolean equals (Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; @@ -179,7 +162,8 @@ public void set (float r, float g, float b, float a) { return true; } - @Override public int hashCode () { + @Override + public int hashCode () { int result = (r != +0.0f ? NumberUtils.floatToIntBits(r) : 0); result = 31 * result + (g != +0.0f ? NumberUtils.floatToIntBits(g) : 0); result = 31 * result + (b != +0.0f ? NumberUtils.floatToIntBits(b) : 0); @@ -191,87 +175,77 @@ public String toString () { return Integer.toHexString(toIntBits()); } - /** - * 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. + /** 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 - */ + * @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 = NumberUtils.intBitsToFloat(color & 0xfeffffff); return floatColor; } - /** - * Packs the four color components which should be in the range 0-255 into a 32-bit. Note that no range checking is performed + /** 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 - */ + * @return the packed color as a 32-bit int */ public static int 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. + /** 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 - */ + * @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 NumberUtils.intBitsToFloat(color & 0xfeffffff); } - /** - * Packs the 4 components of this color into a 32-bit int. + /** Packs the 4 components of this color into a 32-bit int. * - * @return the packed color as 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. + /** 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 - */ + * @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 NumberUtils.intBitsToFloat(color & 0xfeffffff); } - - public static int alpha(float alpha) { + + public static int alpha (float alpha) { return (int)(alpha * 255.0f); } - - public static int luminanceAlpha(float luminance, float alpha) { - return ((int)(luminance * 255.0f) << 8) | (int)(alpha * 255); + + public static int luminanceAlpha (float luminance, float alpha) { + return ((int)(luminance * 255.0f) << 8) | (int)(alpha * 255); } - - public static int rgb565(float r, float g, float b) { + + public static int rgb565 (float r, float g, float b) { return ((int)(r * 31) << 11) | ((int)(g * 63) << 5) | (int)(b * 31); } - - public static int rgba4444(float r, float g, float b, float a) { - return ((int)(r*15) << 12) | ((int)(g*15) << 8) | ((int)(b*15) << 4) | (int)(a*15); + + public static int rgba4444 (float r, float g, float b, float a) { + return ((int)(r * 15) << 12) | ((int)(g * 15) << 8) | ((int)(b * 15) << 4) | (int)(a * 15); } public static int rgb888 (float r, float g, float b) { - return ((int)(r*255) << 16) | ((int)(g*255) << 8) | (int)(b*255); + return ((int)(r * 255) << 16) | ((int)(g * 255) << 8) | (int)(b * 255); + } + + public static int rgba8888 (float r, float g, float b, float a) { + return ((int)(r * 255) << 24) | ((int)(g * 255) << 16) | ((int)(b * 255) << 8) | (int)(a * 255); } - - public static int rgba8888(float r, float g, float b, float a) { - return ((int)(r*255) << 24) | ((int)(g*255) << 16) | ((int)(b*255) << 8) | (int)(a*255); - } } diff --git a/gdx/src/com/badlogic/gdx/graphics/FPSLogger.java b/gdx/src/com/badlogic/gdx/graphics/FPSLogger.java index 74ce571df57..c06944333b8 100644 --- a/gdx/src/com/badlogic/gdx/graphics/FPSLogger.java +++ b/gdx/src/com/badlogic/gdx/graphics/FPSLogger.java @@ -13,31 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.Gdx; -/** - * A simple helper class to log the frames per seconds - * achieved. Just invoke the {@link #log()} method in - * your rendering method. The output will be logged - * once per second. +/** A simple helper class to log the frames per seconds achieved. Just invoke the {@link #log()} method in your rendering method. + * The output will be logged once per second. * - * @author mzechner - * - */ + * @author mzechner */ public class FPSLogger { long startTime; - - public FPSLogger() { + + public FPSLogger () { startTime = System.nanoTime(); } - - /** - * Logs the current frames per second to the console. - */ - public void log() { - if(System.nanoTime()-startTime>1000000000) { + + /** Logs the current frames per second to the console. */ + public void log () { + if (System.nanoTime() - startTime > 1000000000) { Gdx.app.log("FPSLogger", "fps: " + Gdx.graphics.getFramesPerSecond()); startTime = System.nanoTime(); } diff --git a/gdx/src/com/badlogic/gdx/graphics/GL10.java b/gdx/src/com/badlogic/gdx/graphics/GL10.java index b5ff71e7b91..b68c19bc999 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GL10.java +++ b/gdx/src/com/badlogic/gdx/graphics/GL10.java @@ -13,17 +13,15 @@ * 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; -/** - * Interface wrapping all standard OpenGL ES 1.0 methods. Note that this excludes and fixed point OpenGL ES 1.0 methods! - * - * @author mzechner +/** Interface wrapping all standard OpenGL ES 1.0 methods. Note that this excludes and fixed point OpenGL ES 1.0 methods! * - */ + * @author mzechner */ public interface GL10 extends GLCommon { public static final int GL_OES_VERSION_1_0 = 1; public static final int GL_OES_read_format = 1; diff --git a/gdx/src/com/badlogic/gdx/graphics/GL11.java b/gdx/src/com/badlogic/gdx/graphics/GL11.java index c4f28fdb0bc..6b0fde576d8 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GL11.java +++ b/gdx/src/com/badlogic/gdx/graphics/GL11.java @@ -13,18 +13,16 @@ * 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}. Note that this +/** Interface wrapping all OpenGL ES 1.1 methods. This interface inherits all the methods from {@link GL10}. Note that this * excludes all fixed point methods! - * @author mzechner - * - */ + * @author mzechner */ public interface GL11 extends GL10 { public static final int GL_OES_VERSION_1_0 = 1; public static final int GL_MAX_ELEMENTS_VERTICES = 0x80E8; diff --git a/gdx/src/com/badlogic/gdx/graphics/GL20.java b/gdx/src/com/badlogic/gdx/graphics/GL20.java index 00857d7e7b3..62d20029700 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GL20.java +++ b/gdx/src/com/badlogic/gdx/graphics/GL20.java @@ -13,18 +13,16 @@ * 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 the methods of OpenGL ES 2.0 - * @author mzechner - * - */ -public interface GL20 extends GLCommon { +/** Interface wrapping all the methods of OpenGL ES 2.0 + * @author mzechner */ +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,7 +327,7 @@ public interface GL20 extends GLCommon { public static final int GL_MAX_RENDERBUFFER_SIZE = 0x84E8; public static final int GL_INVALID_FRAMEBUFFER_OPERATION = 0x0506; public static final int GL_VERTEX_PROGRAM_POINT_SIZE = 0x8642; - + // Extensions public static final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000; diff --git a/gdx/src/com/badlogic/gdx/graphics/GLCommon.java b/gdx/src/com/badlogic/gdx/graphics/GLCommon.java index 7472ff3803e..49084f340f4 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GLCommon.java +++ b/gdx/src/com/badlogic/gdx/graphics/GLCommon.java @@ -13,16 +13,14 @@ * 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.IntBuffer; -/** - * This interface defines methods common to GL10, GL11 and GL20. - * @author mzechner - * - */ +/** This interface defines methods common to GL10, GL11 and GL20. + * @author mzechner */ public interface GLCommon { public static final int GL_GENERATE_MIPMAP = 0x8191; diff --git a/gdx/src/com/badlogic/gdx/graphics/GLU.java b/gdx/src/com/badlogic/gdx/graphics/GLU.java index 1658a242652..e46dd02b776 100644 --- a/gdx/src/com/badlogic/gdx/graphics/GLU.java +++ b/gdx/src/com/badlogic/gdx/graphics/GLU.java @@ -13,17 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; -/** - * OpenGL utility class. - * @author mzechner - * - */ +/** OpenGL utility class. + * @author mzechner */ public interface GLU { - public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ); + public void gluLookAt (GL10 gl, float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, + float upY, float upZ); + public void gluOrtho2D (GL10 gl, float left, float right, float bottom, float top); + public void gluPerspective (GL10 gl, float fovy, float aspect, float zNear, float zFar); - public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] win, int winOffset); - public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, int projectOffset, int[] view, int viewOffset, float[] obj, int objOffset); + + public boolean gluProject (float objX, float objY, float objZ, float[] model, int modelOffset, float[] project, + int projectOffset, int[] view, int viewOffset, float[] win, int winOffset); + + public boolean gluUnProject (float winX, float winY, float winZ, float[] model, int modelOffset, float[] project, + int projectOffset, int[] view, int viewOffset, float[] obj, int objOffset); } diff --git a/gdx/src/com/badlogic/gdx/graphics/Mesh.java b/gdx/src/com/badlogic/gdx/graphics/Mesh.java index f682ed08c4e..4af236d12fe 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Mesh.java +++ b/gdx/src/com/badlogic/gdx/graphics/Mesh.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.nio.FloatBuffer; @@ -37,8 +38,7 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * 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. @@ -62,10 +62,7 @@ * Meshes can be used with either OpenGL ES 1.x or OpenGL ES 2.0. *

        * - * @author mzechner, Dave Clayton - * - * - */ + * @author mzechner, Dave Clayton */ public class Mesh implements Disposable { public enum VertexDataType { VertexArray, VertexBufferObject, VertexBufferObjectSubData, @@ -79,19 +76,17 @@ public enum VertexDataType { final VertexData vertices; final IndexData indices; - boolean autoBind = true; + boolean autoBind = true; final boolean isVertexArray; int refCount = 0; - /** - * Creates a new Mesh with the given attributes. + /** Creates a new Mesh with the given attributes. * * @param isStatic whether this mesh is static or not. Allows for internal optimizations. * @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 - */ + * normal or texture coordinate */ public Mesh (boolean isStatic, int maxVertices, int maxIndices, VertexAttribute... attributes) { if (Gdx.gl20 != null || Gdx.gl11 != null || Mesh.forceVBO) { vertices = new VertexBufferObject(isStatic, maxVertices, attributes); @@ -105,25 +100,16 @@ public Mesh (boolean isStatic, int maxVertices, int maxIndices, VertexAttribute. addManagedMesh(Gdx.app, this); } - - /** - * Creates a new Mesh with the given attributes. + + /** Creates a new Mesh with the given attributes. * - * @param isStatic - * whether this mesh is static or not. Allows for internal - * optimizations. - * @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 VertexAttributes}. Each vertex attribute defines - * one property of a vertex such as position, normal or texture - * coordinate - */ - public Mesh(boolean isStatic, int maxVertices, int maxIndices, - VertexAttributes attributes) { - if (Gdx.gl20 != null || Gdx.gl11 != null || Mesh.forceVBO ) { + * @param isStatic whether this mesh is static or not. Allows for internal optimizations. + * @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 VertexAttributes}. Each vertex attribute defines one property of a vertex such as position, + * normal or texture coordinate */ + public Mesh (boolean isStatic, int maxVertices, int maxIndices, VertexAttributes attributes) { + if (Gdx.gl20 != null || Gdx.gl11 != null || Mesh.forceVBO) { vertices = new VertexBufferObject(isStatic, maxVertices, attributes); indices = new IndexBufferObject(isStatic, maxIndices); isVertexArray = false; @@ -136,16 +122,14 @@ public Mesh(boolean isStatic, int maxVertices, int maxIndices, addManagedMesh(Gdx.app, this); } - /** - * Creates a new Mesh with the given attributes. This is an expert method with no error checking. Use at your own risk. + /** Creates a new Mesh with the given attributes. This is an expert method with no error checking. Use at your own risk. * * @param type the {@link VertexDataType} to be used, VBO or VA. * @param isStatic whether this mesh is static or not. Allows for internal optimizations. * @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 - */ + * normal or texture coordinate */ public Mesh (VertexDataType type, boolean isStatic, int maxVertices, int maxIndices, VertexAttribute... attributes) { if (type == VertexDataType.VertexArray && Gdx.graphics.isGL20Available()) type = VertexDataType.VertexBufferObject; @@ -162,152 +146,122 @@ public Mesh (VertexDataType type, boolean isStatic, int maxVertices, int maxIndi indices = new IndexBufferObject(maxIndices); isVertexArray = true; } - addManagedMesh(Gdx.app, this); + addManagedMesh(Gdx.app, this); } - /** - * Sets the vertices of this Mesh. The attributes are assumed to be given in float format. If this mesh is configured to use + /** 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 vertices the vertices. */ public void setVertices (float[] vertices) { this.vertices.setVertices(vertices, 0, vertices.length); } - /** - * Sets the vertices of this Mesh. The attributes are assumed to be given in float format. If this mesh is configured to use + /** 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 - */ + * @param count the number of floats to use */ public void setVertices (float[] vertices, int offset, int count) { this.vertices.setVertices(vertices, offset, count); } - - /** - * Copies the vertices from the Mesh to the float array. The float - * array must be large enough to hold all the Mesh's vertices. - * @param vertices the array to copy the vertices to - */ - public void getVertices(float[] vertices) { - if(vertices.length < getNumVertices() * getVertexSize() / 4) - throw new IllegalArgumentException("not enough room in vertices array, has " + vertices.length + " floats, needs " + getNumVertices() * getVertexSize() / 4); - int pos = getVerticesBuffer().position(); + + /** Copies the vertices from the Mesh to the float array. The float array must be large enough to hold all the Mesh's vertices. + * @param vertices the array to copy the vertices to */ + public void getVertices (float[] vertices) { + if (vertices.length < getNumVertices() * getVertexSize() / 4) + throw new IllegalArgumentException("not enough room in vertices array, has " + vertices.length + " floats, needs " + + getNumVertices() * getVertexSize() / 4); + int pos = getVerticesBuffer().position(); getVerticesBuffer().position(0); getVerticesBuffer().get(vertices, 0, getNumVertices() * getVertexSize() / 4); getVerticesBuffer().position(pos); } - /** - * Sets the indices of this Mesh + /** Sets the indices of this Mesh * - * @param indices the indices - */ + * @param indices the indices */ public void setIndices (short[] indices) { this.indices.setIndices(indices, 0, indices.length); } - /** - * Sets the indices of this Mesh. + /** Sets the indices of this Mesh. * * @param indices the indices * @param offset the offset into the indices array - * @param count the number of indices to copy - */ + * @param count the number of indices to copy */ public void setIndices (short[] indices, int offset, int count) { this.indices.setIndices(indices, offset, count); } - - /** - * Copies the indices from the Mesh to the short array. The short - * array must be large enough to hold all the Mesh's indices. - * @param indices the array to copy the indices to - */ - public void getIndices(short[] indices) { - if(indices.length < getNumIndices()) - throw new IllegalArgumentException("not enough room in indices array, has " + indices.length + " floats, needs " + getNumIndices()); - int pos = getIndicesBuffer().position(); + + /** Copies the indices from the Mesh to the short array. The short array must be large enough to hold all the Mesh's indices. + * @param indices the array to copy the indices to */ + public void getIndices (short[] indices) { + if (indices.length < getNumIndices()) + throw new IllegalArgumentException("not enough room in indices array, has " + indices.length + " floats, needs " + + getNumIndices()); + int pos = getIndicesBuffer().position(); getIndicesBuffer().position(0); getIndicesBuffer().get(indices, 0, getNumIndices()); getIndicesBuffer().position(pos); } - /** - * @return the number of defined indices - */ + /** @return the number of defined indices */ public int getNumIndices () { return indices.getNumIndices(); } - /** - * @return the number of defined vertices - */ + /** @return the number of defined vertices */ public int getNumVertices () { return vertices.getNumVertices(); } - /** - * @return the maximum number of vertices this mesh can hold - */ + /** @return the maximum number of vertices this mesh can hold */ public int getMaxVertices () { return vertices.getNumMaxVertices(); } - /** - * @return the maximum number of indices this mesh can hold - */ + /** @return the maximum number of indices this mesh can hold */ public int getMaxIndices () { return indices.getNumMaxIndices(); } - /** - * @return the size of a single vertex in bytes - */ + /** @return the size of a single vertex in bytes */ public int getVertexSize () { return vertices.getAttributes().vertexSize; } - /** - * Sets whether to bind the underlying {@link VertexArray} or {@link VertexBufferObject} automatically on a call to one of the + /** Sets whether to bind the underlying {@link VertexArray} or {@link VertexBufferObject} automatically on a call to one of the * {@link #render(int)} methods or not. Usually you want to use autobind. Manual binding is an expert functionality. There is a * driver bug on the MSM720xa chips that will fuck up memory if you manipulate the vertices and indices of a Mesh multiple * times while it is bound. Keep this in mind. * - * @param autoBind whether to autobind meshes. - */ + * @param autoBind whether to autobind meshes. */ public void setAutoBind (boolean autoBind) { this.autoBind = autoBind; } - - /** - * Binds the underlying {@link VertexArray}/{@link VertexBufferObject} and {@link IndexBufferObject} if indices were given. Use - * this with OpenGL ES 1.x and when auto-bind is disabled. - */ + + /** Binds the underlying {@link VertexArray}/{@link VertexBufferObject} and {@link IndexBufferObject} if indices were given. Use + * this with OpenGL ES 1.x and when auto-bind is disabled. */ public void bind () { if (Gdx.graphics.isGL20Available()) throw new IllegalStateException("can't use this render method with OpenGL ES 2.0"); vertices.bind(); if (!isVertexArray && indices.getNumIndices() > 0) indices.bind(); } - /** - * Unbinds the underlying {@link VertexArray}/{@link VertexBufferObject} and {@link IndexBufferObject} is indices were given. - * Use this with OpenGL ES 1.x and when auto-bind is disabled. - */ + /** Unbinds the underlying {@link VertexArray}/{@link VertexBufferObject} and {@link IndexBufferObject} is indices were given. + * Use this with OpenGL ES 1.x and when auto-bind is disabled. */ public void unbind () { if (Gdx.graphics.isGL20Available()) throw new IllegalStateException("can't use this render method with OpenGL ES 2.0"); vertices.unbind(); if (!isVertexArray && indices.getNumIndices() > 0) indices.unbind(); } - /** - * Binds the underlying {@link VertexBufferObject} and {@link IndexBufferObject} if indices where given. Use this with OpenGL + /** Binds the underlying {@link VertexBufferObject} and {@link IndexBufferObject} if indices where given. Use this with OpenGL * ES 2.0 and when auto-bind is disabled. * - * @param shader the shader (does not bind the shader) - */ + * @param shader the shader (does not bind the shader) */ public void bind (ShaderProgram shader) { if (!Gdx.graphics.isGL20Available()) throw new IllegalStateException("can't use this render method with OpenGL ES 1.x"); @@ -315,12 +269,10 @@ public void bind (ShaderProgram shader) { if (indices.getNumIndices() > 0) indices.bind(); } - /** - * Unbinds the underlying {@link VertexBufferObject} and {@link IndexBufferObject} is indices were given. Use this with OpenGL + /** Unbinds the underlying {@link VertexBufferObject} and {@link IndexBufferObject} is indices were given. Use this with OpenGL * ES 1.x and when auto-bind is disabled. * - * @param shader the shader (does not unbind the shader) - */ + * @param shader the shader (does not unbind the shader) */ public void unbind (ShaderProgram shader) { if (!Gdx.graphics.isGL20Available()) throw new IllegalStateException("can't use this render method with OpenGL ES 1.x"); @@ -328,8 +280,7 @@ public void unbind (ShaderProgram shader) { if (indices.getNumIndices() > 0) indices.unbind(); } - /** - *

        + /**

        * 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. *

        @@ -338,14 +289,12 @@ public void unbind (ShaderProgram shader) { * This method is intended for use with OpenGL ES 1.x and will throw an IllegalStateException when OpenGL ES 2.0 is used. *

        * - * @param primitiveType the primitive type - */ + * @param primitiveType the primitive type */ public void render (int primitiveType) { render(primitiveType, 0, indices.getNumMaxIndices() > 0 ? getNumIndices() : getNumVertices()); } - /** - *

        + /**

        * Renders the mesh using the given primitive type. offset specifies the offset into vertex buffer and is ignored for the index * buffer. Count specifies the number of vertices or indices to use thus count / #vertices per primitive primitives are * rendered. @@ -357,11 +306,10 @@ public void render (int primitiveType) { * * @param primitiveType the primitive type * @param offset the offset into the vertex buffer, ignored for indexed rendering - * @param count number of vertices or indices to use - */ + * @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"); - + if (autoBind) bind(); if (isVertexArray) { @@ -386,8 +334,7 @@ public void render (int primitiveType, int offset, int count) { if (autoBind) unbind(); } - /** - *

        + /**

        * 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. *

        @@ -405,14 +352,12 @@ public void render (int primitiveType, int offset, int count) { * This method is intended for use with OpenGL ES 2.0 and will throw an IllegalStateException when OpenGL ES 1.x is used. *

        * - * @param primitiveType the primitive type - */ + * @param primitiveType the primitive type */ public void render (ShaderProgram shader, int primitiveType) { render(shader, primitiveType, 0, indices.getNumMaxIndices() > 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. @@ -434,8 +379,7 @@ public void render (ShaderProgram shader, int primitiveType) { * @param shader the shader to be used * @param primitiveType the primitive type * @param offset the offset into the vertex or index buffer - * @param count number of vertices or indices to use - */ + * @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"); @@ -449,23 +393,19 @@ public void render (ShaderProgram shader, int primitiveType, int offset, int cou if (autoBind) unbind(shader); } - /** - * Frees all resources associated with this Mesh - */ + /** Frees all resources associated with this Mesh */ public void dispose () { refCount--; - if(refCount > 0) return; - if(meshes.get(Gdx.app) != null) meshes.get(Gdx.app).remove(this); + if (refCount > 0) return; + if (meshes.get(Gdx.app) != null) meshes.get(Gdx.app).remove(this); vertices.dispose(); indices.dispose(); } - /** - * 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. - */ + * @return the VertexAttribute or null if no attribute with that usage was found. */ public VertexAttribute getVertexAttribute (int usage) { VertexAttributes attributes = vertices.getAttributes(); int len = attributes.size(); @@ -475,95 +415,80 @@ public VertexAttribute getVertexAttribute (int usage) { return null; } - /** - * @return the vertex attributes of this Mesh - */ + /** @return the vertex attributes of this Mesh */ public VertexAttributes getVertexAttributes () { return vertices.getAttributes(); } - /** - * @return the backing FloatBuffer holding the vertices. Does not have to be a direct buffer on Android! - */ + /** @return the backing FloatBuffer holding the vertices. Does not have to be a direct buffer on Android! */ public FloatBuffer getVerticesBuffer () { return vertices.getBuffer(); } - - /** - * Calculates the {@link BoundingBox} of the vertices contained - * in this mesh. In case no vertices are defined yet a {@link GdxRuntimeException} - * is thrown. This method creates a new BoundingBox instance. + + /** Calculates the {@link BoundingBox} of the vertices contained in this mesh. In case no vertices are defined yet a + * {@link GdxRuntimeException} is thrown. This method creates a new BoundingBox instance. * - * @return the bounding box. - */ - public BoundingBox calculateBoundingBox() { + * @return the bounding box. */ + public BoundingBox calculateBoundingBox () { BoundingBox bbox = new BoundingBox(); calculateBoundingBox(bbox); return bbox; } - - /** - * Calculates the {@link BoundingBox} of the vertices contained - * in this mesh. In case no vertices are defined yet a {@link GdxRuntimeException} - * is thrown. + + /** Calculates the {@link BoundingBox} of the vertices contained in this mesh. In case no vertices are defined yet a + * {@link GdxRuntimeException} is thrown. * - * @param bbox the bounding box to store the result in. - */ - public void calculateBoundingBox(BoundingBox bbox) { + * @param bbox the bounding box to store the result in. */ + public void calculateBoundingBox (BoundingBox bbox) { final int numVertices = getNumVertices(); - if(numVertices==0) - throw new GdxRuntimeException("No vertices defined"); - + if (numVertices == 0) throw new GdxRuntimeException("No vertices defined"); + final FloatBuffer verts = vertices.getBuffer(); bbox.inf(); final VertexAttribute posAttrib = getVertexAttribute(Usage.Position); - final int offset = posAttrib.offset / 4; + final int offset = posAttrib.offset / 4; final int vertexSize = vertices.getAttributes().vertexSize / 4; int idx = offset; - - switch(posAttrib.numComponents) { - case 1: - for(int i = 0; i < numVertices; i++) { - bbox.ext(verts.get(idx), 0, 0); - idx+=vertexSize; - } - break; - case 2: - for(int i = 0; i < numVertices; i++) { - bbox.ext(verts.get(idx), verts.get(idx+1), 0); - idx+=vertexSize; - } - break; - case 3: - for(int i = 0; i < numVertices; i++) { - bbox.ext(verts.get(idx), verts.get(idx+1), verts.get(idx+2)); - idx+=vertexSize; - } - break; - } - } - - /** - * @return the backing shortbuffer holding the indices. Does not have to be a direct buffer on Android! - */ + + switch (posAttrib.numComponents) { + case 1: + for (int i = 0; i < numVertices; i++) { + bbox.ext(verts.get(idx), 0, 0); + idx += vertexSize; + } + break; + case 2: + for (int i = 0; i < numVertices; i++) { + bbox.ext(verts.get(idx), verts.get(idx + 1), 0); + idx += vertexSize; + } + break; + case 3: + for (int i = 0; i < numVertices; i++) { + bbox.ext(verts.get(idx), verts.get(idx + 1), verts.get(idx + 2)); + idx += vertexSize; + } + break; + } + } + + /** @return the backing shortbuffer holding the indices. Does not have to be a direct buffer on Android! */ public ShortBuffer getIndicesBuffer () { return indices.getBuffer(); } - private static void addManagedMesh(Application app, Mesh mesh) { + private static void addManagedMesh (Application app, Mesh mesh) { List managedResources = meshes.get(app); - if(managedResources == null) managedResources = new ArrayList(); + if (managedResources == null) managedResources = new ArrayList(); managedResources.add(mesh); meshes.put(app, managedResources); } - - /** - * Invalidates all meshes so the next time they are rendered new VBO handles are generated. - * @param app - */ + + /** Invalidates all meshes so the next time they are rendered new VBO handles are generated. + * @param app */ public static void invalidateAllMeshes (Application app) { List meshesList = meshes.get(app); - if(meshesList == null) return; + if (meshesList == null) return; for (int i = 0; i < meshesList.size(); i++) { if (meshesList.get(i).vertices instanceof VertexBufferObject) { ((VertexBufferObject)meshesList.get(i).vertices).invalidate(); @@ -572,70 +497,64 @@ public static void invalidateAllMeshes (Application app) { } } - /** - * Will clear the managed mesh cache. I wouldn't use this if i was you :) - */ - public static void clearAllMeshes (Application app) { + /** Will clear the managed mesh cache. I wouldn't use this if i was you :) */ + public static void clearAllMeshes (Application app) { meshes.remove(app); } - - public static String getManagedStatus() { + + public static String getManagedStatus () { StringBuilder builder = new StringBuilder(); int i = 0; builder.append("Managed meshes/app: { "); - for(Application app: meshes.keySet()) { + for (Application app : meshes.keySet()) { builder.append(meshes.get(app).size()); builder.append(" "); } builder.append("}"); return builder.toString(); } - - /** - * Method to scale the positions in the mesh. Normals will be - * kept as is. This is a potentially slow operation, use with - * care. It will also create a temporary float[] which will - * be garbage collected. + + /** Method to scale the positions in the mesh. Normals will be kept as is. This is a potentially slow operation, use with care. + * It will also create a temporary float[] which will be garbage collected. * * @param scaleX scale on x * @param scaleY scale on y - * @param scaleZ scale on z - */ - public void scale(float scaleX, float scaleY, float scaleZ) { + * @param scaleZ scale on z */ + public void scale (float scaleX, float scaleY, float scaleZ) { VertexAttribute posAttr = getVertexAttribute(Usage.Position); int offset = posAttr.offset / 4; int numComponents = posAttr.numComponents; int numVertices = getNumVertices(); int vertexSize = getVertexSize() / 4; - + float[] vertices = new float[numVertices * vertexSize]; getVertices(vertices); - + int idx = offset; - switch(numComponents) { + switch (numComponents) { case 1: - for(int i = 0; i < numVertices; i++) { - vertices[idx] *= scaleX; - idx+=vertexSize; + for (int i = 0; i < numVertices; i++) { + vertices[idx] *= scaleX; + idx += vertexSize; } break; case 2: - for(int i = 0; i < numVertices; i++) { + for (int i = 0; i < numVertices; i++) { vertices[idx] *= scaleX; - vertices[idx+1] *= scaleY; - idx+=vertexSize; + vertices[idx + 1] *= scaleY; + idx += vertexSize; } break; case 3: - for(int i = 0; i < numVertices; i++) { + for (int i = 0; i < numVertices; i++) { vertices[idx] *= scaleX; - vertices[idx+1] *= scaleY; - vertices[idx+2] *= scaleZ; - idx+=vertexSize; + vertices[idx + 1] *= scaleY; + vertices[idx + 2] *= scaleZ; + idx += vertexSize; } break; } - + setVertices(vertices); - } + } } diff --git a/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java b/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java index ad5a4138cef..6f3f4b51f0d 100644 --- a/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java +++ b/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java @@ -20,12 +20,9 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; -/** - * A camera with orthographic projection. +/** A camera with orthographic projection. * - * @author mzechner - * - */ + * @author mzechner */ public class OrthographicCamera extends Camera { /** the zoom of the camera **/ public float zoom = 1; @@ -34,13 +31,11 @@ public OrthographicCamera () { this.near = 0; } - /** - * Constructs a new OrthographicCamera, using the given viewport width and height. For pixel perfect 2D rendering just supply + /** Constructs a new OrthographicCamera, using the given viewport width and height. For pixel perfect 2D rendering just supply * the screen size, for other unit scales (e.g. meters for box2d) proceed accordingly. * * @param viewportWidth the viewport width - * @param viewportHeight the viewport height - */ + * @param viewportHeight the viewport height */ public OrthographicCamera (float viewportWidth, float viewportHeight) { this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; @@ -48,14 +43,12 @@ public OrthographicCamera (float viewportWidth, float viewportHeight) { update(); } - /** - * Constructs a new OrthographicCamera, using the given viewport width and height. This will create a camera useable for + /** Constructs a new OrthographicCamera, using the given viewport width and height. This will create a camera useable for * iso-metric views. The diamond angle is specifies the angle of a tile viewed isometrically. * * @param viewportWidth the viewport width * @param viewportHeight the viewport height - * @param diamondAngle the angle in degrees - */ + * @param diamondAngle the angle in degrees */ public OrthographicCamera (float viewportWidth, float viewportHeight, float diamondAngle) { this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; diff --git a/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java b/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java index 1f5360f255c..6e6b5255e35 100644 --- a/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java +++ b/gdx/src/com/badlogic/gdx/graphics/PerspectiveCamera.java @@ -13,49 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; -/** - * A Camera with perspective projection. +/** A Camera with perspective projection. * - * @author mzechner - * - */ -public class PerspectiveCamera extends Camera { + * @author mzechner */ +public class PerspectiveCamera extends Camera { /** the field of view in degrees **/ public float fieldOfView = 67; public PerspectiveCamera () { } - /** - * Constructs a new {@link PerspectiveCamera} with the given field of view and viewport - * size. The apsect ratio is derrived from the viewport size. + /** Constructs a new {@link PerspectiveCamera} with the given field of view and viewport size. The apsect ratio is derrived from + * the viewport size. * * @param fieldOfView the field of view in degrees * @param viewportWidth the viewport width - * @param viewportHeight the viewport height - */ - public PerspectiveCamera(float fieldOfView, float viewportWidth, float viewportHeight) { + * @param viewportHeight the viewport height */ + public PerspectiveCamera (float fieldOfView, float viewportWidth, float viewportHeight) { this.fieldOfView = fieldOfView; this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; update(); } - + final Vector3 tmp = new Vector3(); + @Override - public void update() { - float aspect = viewportWidth / viewportHeight; + public void update () { + float aspect = viewportWidth / viewportHeight; projection.setToProjection(Math.abs(near), Math.abs(far), fieldOfView, aspect); - view.setToLookAt(position, tmp.set(position).add(direction), up); + view.setToLookAt(position, tmp.set(position).add(direction), up); combined.set(projection); Matrix4.mul(combined.val, view.val); invProjectionView.set(combined); Matrix4.inv(invProjectionView.val); frustum.update(invProjectionView); - } + } } diff --git a/gdx/src/com/badlogic/gdx/graphics/Pixmap.java b/gdx/src/com/badlogic/gdx/graphics/Pixmap.java index 76995a965b2..69e555e1ac9 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Pixmap.java +++ b/gdx/src/com/badlogic/gdx/graphics/Pixmap.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.io.IOException; -import java.io.InputStream; import java.nio.ByteBuffer; import com.badlogic.gdx.files.FileHandle; @@ -24,130 +24,112 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        A Pixmap represents an image in memory. It has a width and height expressed in pixels as well as a {@link Format} - * specifying the number and order of color components per pixel. Coordinates of pixels are specified with respect - * to the top left corner of the image, with the x-axis pointing to the right and the y-axis pointing downwards.

        - * - *

        By default all methods use blending. You can disable blending with {@link Pixmap#setBlending(Blending)}. The {@link - * Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)} method will scale and stretch the source image - * to a target image. There either nearest neighbour or bilinear filtering can be used.

        +/**

        + * A Pixmap represents an image in memory. It has a width and height expressed in pixels as well as a {@link Format} specifying + * the number and order of color components per pixel. Coordinates of pixels are specified with respect to the top left corner of + * the image, with the x-axis pointing to the right and the y-axis pointing downwards. + *

        * - *

        A Pixmap stores its data in native heap memory. It is mandatory to call {@link Pixmap#dispose()} when the pixmap - * is no longer needed, otherwise memory leaks will result

        + *

        + * By default all methods use blending. You can disable blending with {@link Pixmap#setBlending(Blending)}. The + * {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)} method will scale and stretch the source image to a + * target image. There either nearest neighbour or bilinear filtering can be used. + *

        * - * @author badlogicgames@gmail.com + *

        + * A Pixmap stores its data in native heap memory. It is mandatory to call {@link Pixmap#dispose()} when the pixmap is no longer + * needed, otherwise memory leaks will result + *

        * - */ + * @author badlogicgames@gmail.com */ public class Pixmap implements Disposable { - /** - * Different pixel formats. + /** Different pixel formats. * - * @author mzechner - * - */ + * @author mzechner */ public enum Format { Alpha, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888; - - static int toGdx2DPixmapFormat(Format format) { - if(format == Alpha) return Gdx2DPixmap.GDX2D_FORMAT_ALPHA; - if(format == LuminanceAlpha) return Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA; - if(format == RGB565) return Gdx2DPixmap.GDX2D_FORMAT_RGB565; - if(format == RGBA4444) return Gdx2DPixmap.GDX2D_FORMAT_RGBA4444; - if(format == RGB888) return Gdx2DPixmap.GDX2D_FORMAT_RGB888; - if(format == RGBA8888) return Gdx2DPixmap.GDX2D_FORMAT_RGBA8888; + + static int toGdx2DPixmapFormat (Format format) { + if (format == Alpha) return Gdx2DPixmap.GDX2D_FORMAT_ALPHA; + if (format == LuminanceAlpha) return Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA; + if (format == RGB565) return Gdx2DPixmap.GDX2D_FORMAT_RGB565; + if (format == RGBA4444) return Gdx2DPixmap.GDX2D_FORMAT_RGBA4444; + if (format == RGB888) return Gdx2DPixmap.GDX2D_FORMAT_RGB888; + if (format == RGBA8888) return Gdx2DPixmap.GDX2D_FORMAT_RGBA8888; throw new GdxRuntimeException("Unknown Format: " + format); } - - static Format fromGdx2DPixmapFormat(int format) { - if(format == Gdx2DPixmap.GDX2D_FORMAT_ALPHA) return Alpha; - if(format == Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA) return LuminanceAlpha; - if(format == Gdx2DPixmap.GDX2D_FORMAT_RGB565) return RGB565; - if(format == Gdx2DPixmap.GDX2D_FORMAT_RGBA4444) return RGBA4444; - if(format == Gdx2DPixmap.GDX2D_FORMAT_RGB888) return RGB888; - if(format == Gdx2DPixmap.GDX2D_FORMAT_RGBA8888) return RGBA8888; + + static Format fromGdx2DPixmapFormat (int format) { + if (format == Gdx2DPixmap.GDX2D_FORMAT_ALPHA) return Alpha; + if (format == Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA) return LuminanceAlpha; + if (format == Gdx2DPixmap.GDX2D_FORMAT_RGB565) return RGB565; + if (format == Gdx2DPixmap.GDX2D_FORMAT_RGBA4444) return RGBA4444; + if (format == Gdx2DPixmap.GDX2D_FORMAT_RGB888) return RGB888; + if (format == Gdx2DPixmap.GDX2D_FORMAT_RGBA8888) return RGBA8888; throw new GdxRuntimeException("Unknown Gdx2DPixmap Format: " + format); } } - /** - * Blending functions to be set with {@link Pixmap#setBlending}. - * @author mzechner - * - */ + /** Blending functions to be set with {@link Pixmap#setBlending}. + * @author mzechner */ public enum Blending { None, SourceOver } - - /** - * Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. + + /** Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. * - * @author mzechner - * - */ + * @author mzechner */ public enum Filter { NearestNeighbour, BiLinear } /** global blending state **/ private static Blending blending = Blending.SourceOver; - + final Gdx2DPixmap pixmap; int color = 0; - - /** - * Sets the type of {@link Blending} to be used for all operations. - * @param blending the blending type - */ - public static void setBlending(Blending blending) { + + /** Sets the type of {@link Blending} to be used for all operations. + * @param blending the blending type */ + public static void setBlending (Blending blending) { Pixmap.blending = blending; - Gdx2DPixmap.setBlend(blending==Blending.None?0:1); + Gdx2DPixmap.setBlend(blending == Blending.None ? 0 : 1); } - - /** - * Sets the type of interpolation {@link Filter} to be used in conjunction - * with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. - * @param filter the filter. - */ - public static void setFilter(Filter filter) { - Gdx2DPixmap.setScale(filter==Filter.NearestNeighbour?Gdx2DPixmap.GDX2D_SCALE_NEAREST:Gdx2DPixmap.GDX2D_SCALE_LINEAR); + + /** Sets the type of interpolation {@link Filter} to be used in conjunction with + * {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}. + * @param filter the filter. */ + public static void setFilter (Filter filter) { + Gdx2DPixmap.setScale(filter == Filter.NearestNeighbour ? Gdx2DPixmap.GDX2D_SCALE_NEAREST : Gdx2DPixmap.GDX2D_SCALE_LINEAR); } - - /** - * Creates a new Pixmap instance with the given width, height - * and format. + + /** Creates a new Pixmap instance with the given width, height and format. * @param width the width in pixels * @param height the height in pixels - * @param format the {@link Format} - */ - public Pixmap(int width, int height, Format format) { - pixmap = new Gdx2DPixmap(width, height, Format.toGdx2DPixmapFormat(format)); + * @param format the {@link Format} */ + public Pixmap (int width, int height, Format format) { + pixmap = new Gdx2DPixmap(width, height, Format.toGdx2DPixmapFormat(format)); setColor(0, 0, 0, 0); - fill(); - } - - /** - * Creates a new Pixmap instance from the given encoded image data. The - * image can be encoded as JPEG, PNG or BMP. + fill(); + } + + /** Creates a new Pixmap instance from the given encoded image data. The image can be encoded as JPEG, PNG or BMP. * @param encodedData the encoded image data * @param offset the offset - * @param len the length - */ - public Pixmap(byte[] encodedData, int offset, int len) { + * @param len the length */ + public Pixmap (byte[] encodedData, int offset, int len) { try { pixmap = new Gdx2DPixmap(encodedData, offset, len, 0); - } catch(IOException e) { + } catch (IOException e) { throw new GdxRuntimeException("Couldn't load pixmap from image data", e); } } - - /** - * Creates a new Pixmap instance from the given file. The file must - * be a Png, Jpeg or Bitmap. Paletted formats are not supported. + + /** Creates a new Pixmap instance from the given file. The file must be a Png, Jpeg or Bitmap. Paletted formats are not + * supported. * - * @param file the {@link FileHandle} - */ - public Pixmap(FileHandle file) { + * @param file the {@link FileHandle} */ + public Pixmap (FileHandle file) { try { byte[] bytes = file.readBytes(); pixmap = new Gdx2DPixmap(bytes, 0, bytes.length, 0); @@ -155,76 +137,63 @@ public Pixmap(FileHandle file) { throw new GdxRuntimeException("Couldn't load file: " + file, e); } } - - /** - * Constructs a new Pixmap from a {@link Gdx2DPixmap}. - * @param pixmap - */ - public Pixmap(Gdx2DPixmap pixmap) { + + /** Constructs a new Pixmap from a {@link Gdx2DPixmap}. + * @param pixmap */ + public Pixmap (Gdx2DPixmap pixmap) { this.pixmap = pixmap; } - - /** - * Sets the color for the following drawing operations. + + /** Sets the color for the following drawing operations. * * @param r The red component. * @param g The green component. * @param b The blue component. - * @param a The alpha component. - */ + * @param a The alpha component. */ public void setColor (float r, float g, float b, float a) { color = Color.rgba8888(r, g, b, a); } - /** - * Sets the color for the following drawing operations. - * @param color The color. - */ - public void setColor(Color color) { + /** Sets the color for the following drawing operations. + * @param color The color. */ + public void setColor (Color color) { this.color = Color.rgba8888(color.r, color.g, color.b, color.a); } - - /** - * Fills the complete bitmap with the currently set color. - */ + + /** Fills the complete bitmap with the currently set color. */ public void fill () { pixmap.clear(color); } -// /** -// * Sets the width in pixels of strokes. -// * -// * @param width The stroke width in pixels. -// */ -// public void setStrokeWidth (int width); +// /** +// * Sets the width in pixels of strokes. +// * +// * @param width The stroke width in pixels. +// */ +// public void setStrokeWidth (int width); - /** - * Draws a line between the given coordinates using the currently set color. + /** Draws a line between the given coordinates using the currently set color. * * @param x The x-coodinate of the first point * @param y The y-coordinate of the first point * @param x2 The x-coordinate of the first point - * @param y2 The y-coordinate of the first point - */ + * @param y2 The y-coordinate of the first point */ public void drawLine (int x, int y, int x2, int y2) { pixmap.drawLine(x, y, x2, y2, color); } - /** - * Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards) + /** Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points downwards) * using the current color. * * @param x The x coordinate * @param y The y coordinate * @param width The width in pixels - * @param height The height in pixels - */ + * @param height The height in pixels */ public void drawRectangle (int x, int y, int width, int height) { pixmap.drawRect(x, y, width, height, color); } - /** - * Draws an area form another Pixmap to this Pixmap. + /** Draws an area form another Pixmap to this Pixmap. * * @param pixmap The other Pixmap * @param x The target x-coordinate (top left corner) @@ -232,18 +201,16 @@ public void drawRectangle (int x, int y, int width, int height) { * @param srcx The source x-coordinate (top left corner) * @param srcy The source y-coordinate (top left corner); * @param srcWidth The width of the area form the other Pixmap in pixels - * @param srcHeight The height of the area form the other Pixmap in pixles - */ + * @param srcHeight The height of the area form the other Pixmap in pixles */ public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) { this.pixmap.drawPixmap(pixmap.pixmap, srcx, srcy, x, y, srcWidth, srcHeight); } - - /** - * Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch - * the source image to the specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to - * specify the type of filtering to be used (nearest neighbour or bilinear). + + /** Draws an area form another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the + * specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest + * neighbour or bilinear). * - * @param pixmap The other Pixmap + * @param pixmap The other Pixmap * @param srcx The source x-coordinate (top left corner) * @param srcy The source y-coordinate (top left corner); * @param srcWidth The width of the area form the other Pixmap in pixels @@ -251,141 +218,109 @@ public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int src * @param dstx The target x-coordinate (top left corner) * @param dsty The target y-coordinate (top left corner) * @param dstWidth The target width - * @param dstHeight the target height - * - */ - public void drawPixmap (Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth, int dstHeight) { + * @param dstHeight the target height */ + public void drawPixmap (Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth, + int dstHeight) { this.pixmap.drawPixmap(pixmap.pixmap, srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight); } - /** - * Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using + /** Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using * the current color. * * @param x The x coordinate * @param y The y coordinate * @param width The width in pixels - * @param height The height in pixels - */ + * @param height The height in pixels */ public void fillRectangle (int x, int y, int width, int height) { pixmap.fillRect(x, y, width, height, color); } - /** - * 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 y The y-coordinate of the center - * @param radius The radius in pixels - */ + * @param radius The radius in pixels */ public void drawCircle (int x, int y, int radius) { pixmap.drawCircle(x, y, radius, color); } - /** - * 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 y The y-coordinate of the center - * @param radius The radius in pixels - */ + * @param radius The radius in pixels */ public void fillCircle (int x, int y, int radius) { pixmap.fillCircle(x, y, radius, color); } - /** - * Returns the 32-bit RGBA8888 value of the pixel at x, y. For - * Alpha formats the RGB components will be one. + /** Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one. * * @param x The x-coordinate * @param y The y-coordinate - * @return The pixel color in RGBA8888 format. - */ + * @return The pixel color in RGBA8888 format. */ public int getPixel (int x, int y) { return pixmap.getPixel(x, y); } - /** - * @return The width of the Pixmap in pixels. - */ + /** @return The width of the Pixmap in pixels. */ public int getWidth () { return pixmap.getWidth(); } - /** - * @return The height of the Pixmap in pixels. - */ + /** @return The height of the Pixmap in pixels. */ public int getHeight () { return pixmap.getHeight(); } - /** - * Releases all resources associated with this Pixmap. - */ + /** Releases all resources associated with this Pixmap. */ public void dispose () { pixmap.dispose(); } - /** - * Draws a pixel at the given location with the current color. + /** Draws a pixel at the given location with the current color. * * @param x the x-coordinate - * @param y the y-coordinate - */ - public void drawPixel(int x, int y) { + * @param y the y-coordinate */ + public void drawPixel (int x, int y) { pixmap.setPixel(x, y, color); } - - /** - * Returns the OpenGL ES format of this Pixmap. Used as the seventh - * parameter to {@link GLCommon#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}. - * @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. - */ - public int getGLFormat() { + + /** Returns the OpenGL ES format of this Pixmap. Used as the seventh parameter to + * {@link GLCommon#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}. + * @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. */ + public int getGLFormat () { return pixmap.getGLFormat(); } - - /** - * Returns the OpenGL ES format of this Pixmap. Used as the third - * parameter to {@link GLCommon#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}. - * @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. - */ - public int getGLInternalFormat() { + + /** Returns the OpenGL ES format of this Pixmap. Used as the third parameter to + * {@link GLCommon#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}. + * @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. */ + public int getGLInternalFormat () { return pixmap.getGLInternalFormat(); } - - /** - * Returns the OpenGL ES type of this Pixmap. Used as the eighth parameter to + + /** Returns the OpenGL ES type of this Pixmap. Used as the eighth parameter to * {@link GLCommon#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}. - * @return one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4 - */ - public int getGLType() { + * @return one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4 */ + public int getGLType () { return pixmap.getGLType(); } - - /** - * Returns the direct ByteBuffer holding the pixel data. For the format Alpha each value - * is encoded as a byte. For the format LuminanceAlpha the luminance is the first byte and - * the alpha is the second byte of the pixel. For the formats RGB888 and RGBA8888 the color - * components are stored in a single byte each in the order red, green, blue (alpha). For - * the formats RGB565 and RGBA4444 the pixel colors are stored in shorts in machine dependent - * order. - * @return the direct {@link ByteBuffer} holding the pixel data. - */ - public ByteBuffer getPixels() { + + /** Returns the direct ByteBuffer holding the pixel data. For the format Alpha each value is encoded as a byte. For the format + * LuminanceAlpha the luminance is the first byte and the alpha is the second byte of the pixel. For the formats RGB888 and + * RGBA8888 the color components are stored in a single byte each in the order red, green, blue (alpha). For the formats RGB565 + * and RGBA4444 the pixel colors are stored in shorts in machine dependent order. + * @return the direct {@link ByteBuffer} holding the pixel data. */ + public ByteBuffer getPixels () { return pixmap.getPixels(); } - /** - * @return the {@link Format} of this Pixmap. - */ - public Format getFormat() { + /** @return the {@link Format} of this Pixmap. */ + public Format getFormat () { return Format.fromGdx2DPixmapFormat(pixmap.getFormat()); } - /** - * @return the currently set {@link Blending} - */ + /** @return the currently set {@link Blending} */ public static Blending getBlending () { return blending; } diff --git a/gdx/src/com/badlogic/gdx/graphics/Texture.java b/gdx/src/com/badlogic/gdx/graphics/Texture.java index acdca35d531..8e75260c4b4 100644 --- a/gdx/src/com/badlogic/gdx/graphics/Texture.java +++ b/gdx/src/com/badlogic/gdx/graphics/Texture.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics; import java.nio.IntBuffer; @@ -38,8 +39,7 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * A Texture wraps a standard OpenGL ES texture. *

        * @@ -62,135 +62,130 @@ * A Texture must be disposed when it is no longer used *

        * - * @author badlogicgames@gmail.com - * - */ + * @author badlogicgames@gmail.com */ public class Texture implements Disposable { static private boolean enforcePotImages = true; static private boolean useHWMipMap = true; private static AssetManager assetManager; final private static Map> managedTextures = new HashMap>(); - + public enum TextureFilter { - Nearest(GL10.GL_NEAREST), - Linear(GL10.GL_LINEAR), - MipMap(GL10.GL_LINEAR_MIPMAP_LINEAR), - MipMapNearestNearest(GL10.GL_NEAREST_MIPMAP_NEAREST), - MipMapLinearNearest(GL10.GL_LINEAR_MIPMAP_NEAREST), - MipMapNearestLinear(GL10.GL_NEAREST_MIPMAP_LINEAR), - MipMapLinearLinear(GL10.GL_LINEAR_MIPMAP_LINEAR); + Nearest(GL10.GL_NEAREST), Linear(GL10.GL_LINEAR), MipMap(GL10.GL_LINEAR_MIPMAP_LINEAR), MipMapNearestNearest( + GL10.GL_NEAREST_MIPMAP_NEAREST), MipMapLinearNearest(GL10.GL_LINEAR_MIPMAP_NEAREST), MipMapNearestLinear( + GL10.GL_NEAREST_MIPMAP_LINEAR), MipMapLinearLinear(GL10.GL_LINEAR_MIPMAP_LINEAR); final int glEnum; - - TextureFilter(int glEnum) { + + TextureFilter (int glEnum) { this.glEnum = glEnum; } - - public boolean isMipMap() { + + public boolean isMipMap () { return glEnum != GL10.GL_NEAREST && glEnum != GL10.GL_LINEAR; } - - public int getGLEnum() { + + public int getGLEnum () { return glEnum; - } + } } public enum TextureWrap { - ClampToEdge(GL10.GL_CLAMP_TO_EDGE), - Repeat(GL10.GL_REPEAT); - + ClampToEdge(GL10.GL_CLAMP_TO_EDGE), Repeat(GL10.GL_REPEAT); + final int glEnum; - - TextureWrap(int glEnum) { + + TextureWrap (int glEnum) { this.glEnum = glEnum; } - - public int getGLEnum() { + + public int getGLEnum () { return glEnum; } } - + private static final IntBuffer buffer = BufferUtils.newIntBuffer(1); - + TextureFilter minFilter = TextureFilter.Nearest; TextureFilter magFilter = TextureFilter.Nearest; TextureWrap uWrap = TextureWrap.ClampToEdge; TextureWrap vWrap = TextureWrap.ClampToEdge; int glHandle; TextureData data; - - public Texture(String internalPath) { + + public Texture (String internalPath) { this(new FileTextureData(Gdx.files.internal(internalPath), null, null, false)); } - - public Texture(FileHandle file) { + + public Texture (FileHandle file) { this(new FileTextureData(file, null, null, false)); } - - public Texture(FileHandle file, boolean useMipMaps) { + + public Texture (FileHandle file, boolean useMipMaps) { this(new FileTextureData(file, null, null, useMipMaps)); } - - public Texture(FileHandle file, Format format, boolean useMipMaps) { + + public Texture (FileHandle file, Format format, boolean useMipMaps) { this(new FileTextureData(file, null, format, useMipMaps)); } - - public Texture(Pixmap pixmap) { + + public Texture (Pixmap pixmap) { this(new PixmapTextureData(pixmap, null, false, false)); } - - public Texture(Pixmap pixmap, boolean useMipMaps) { + + public Texture (Pixmap pixmap, boolean useMipMaps) { this(new PixmapTextureData(pixmap, null, useMipMaps, false)); } - - public Texture(Pixmap pixmap, Format format, boolean useMipMaps) { + + public Texture (Pixmap pixmap, Format format, boolean useMipMaps) { this(new PixmapTextureData(pixmap, format, useMipMaps, false)); } - - public Texture(int width, int height, Format format) { + + public Texture (int width, int height, Format format) { this(new PixmapTextureData(new Pixmap(width, height, format), null, false, true)); } - - public Texture(TextureData data) { + + public Texture (TextureData data) { glHandle = createGLHandle(); load(data); - if(data.isManaged()) addManagedTexture(Gdx.app, this); + if (data.isManaged()) addManagedTexture(Gdx.app, this); } - - public static int createGLHandle() { + + public static int createGLHandle () { buffer.position(0); buffer.limit(buffer.capacity()); Gdx.gl.glGenTextures(1, buffer); - return buffer.get(0); + return buffer.get(0); } - - public void load(TextureData data) { - if(this.data != null && data.isManaged() != this.data.isManaged()) throw new GdxRuntimeException("New data must have the same managed status as the old data"); + + public void load (TextureData data) { + if (this.data != null && data.isManaged() != this.data.isManaged()) + throw new GdxRuntimeException("New data must have the same managed status as the old data"); this.data = data; - - if(data.getType() == TextureDataType.Pixmap) { + + if (data.getType() == TextureDataType.Pixmap) { Pixmap pixmap = data.getPixmap(); uploadImageData(pixmap); - if(data.disposePixmap()) pixmap.dispose(); + if (data.disposePixmap()) pixmap.dispose(); setFilter(minFilter, magFilter); setWrap(uWrap, vWrap); } - - if(data.getType() == TextureDataType.Compressed) { + + if (data.getType() == TextureDataType.Compressed) { Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); data.uploadCompressedData(); setFilter(minFilter, magFilter); setWrap(uWrap, vWrap); } } - - private void uploadImageData(Pixmap pixmap) { - if(enforcePotImages && Gdx.gl20 == null && (!MathUtils.isPowerOfTwo(data.getWidth()) || !MathUtils.isPowerOfTwo(data.getHeight()))) + + private void uploadImageData (Pixmap pixmap) { + if (enforcePotImages && Gdx.gl20 == null + && (!MathUtils.isPowerOfTwo(data.getWidth()) || !MathUtils.isPowerOfTwo(data.getHeight()))) throw new GdxRuntimeException("texture width and height must be powers of two"); - + boolean disposePixmap = false; - if(data.getFormat() != pixmap.getFormat()) { - Pixmap tmp = new Pixmap(pixmap.getWidth(), pixmap.getHeight(), data.getFormat()); + if (data.getFormat() != pixmap.getFormat()) { + Pixmap tmp = new Pixmap(pixmap.getWidth(), pixmap.getHeight(), data.getFormat()); Blending blend = Pixmap.getBlending(); Pixmap.setBlending(Blending.None); tmp.drawPixmap(pixmap, 0, 0, 0, 0, pixmap.getWidth(), pixmap.getHeight()); @@ -198,113 +193,95 @@ private void uploadImageData(Pixmap pixmap) { pixmap = tmp; disposePixmap = true; } - - Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); - if(data.useMipMaps()) { - MipMapGenerator.generateMipMap(pixmap, pixmap.getWidth(), pixmap.getHeight(), disposePixmap); + + Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); + if (data.useMipMaps()) { + MipMapGenerator.generateMipMap(pixmap, pixmap.getWidth(), pixmap.getHeight(), disposePixmap); } else { - Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); - if(disposePixmap) pixmap.dispose(); + Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + if (disposePixmap) pixmap.dispose(); } } - - /** - * Used internally to reload after context loss. - * Creates a new GL handle then calls {@link #load(TextureData)}. - */ - private void reload() { - if(!data.isManaged()) throw new GdxRuntimeException("Tried to reload unmanaged Texture"); + + /** Used internally to reload after context loss. Creates a new GL handle then calls {@link #load(TextureData)}. */ + private void reload () { + if (!data.isManaged()) throw new GdxRuntimeException("Tried to reload unmanaged Texture"); createGLHandle(); load(data); } - - /** - * Binds this texture. The texture will be bound to the currently active texture unit specified via - * {@link GLCommon#glActiveTexture(int)}. - */ + + /** Binds this texture. The texture will be bound to the currently active texture unit specified via + * {@link GLCommon#glActiveTexture(int)}. */ public void bind () { Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); } - /** - * Binds the texture to the given texture unit. Sets the currently active texture unit via + /** Binds the texture to the given texture unit. Sets the currently active texture unit via * {@link GLCommon#glActiveTexture(int)}. - * @param unit the unit (0 to MAX_TEXTURE_UNITS). - */ - public void bind(int unit) { + * @param unit the unit (0 to MAX_TEXTURE_UNITS). */ + public void bind (int unit) { Gdx.gl.glActiveTexture(GL10.GL_TEXTURE0 + unit); Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); } - - /** - * Draws the given {@link Pixmap} to the texture at position x, y. No clipping is performed so you have to make sure that you + + /** Draws the given {@link Pixmap} to the texture at position x, y. No clipping is performed so you have to make sure that you * draw only inside the texture region. Note that this will only draw to mipmap level 0! * * @param pixmap The Pixmap * @param x The x coordinate in pixels - * @param y The y coordinate in pixels - */ + * @param y The y coordinate in pixels */ public void draw (Pixmap pixmap, int x, int y) { - if(data.isManaged()) throw new GdxRuntimeException("can't draw to a managed texture"); - - Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); - Gdx.gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, x, y, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + if (data.isManaged()) throw new GdxRuntimeException("can't draw to a managed texture"); + + Gdx.gl.glBindTexture(GL10.GL_TEXTURE_2D, glHandle); + Gdx.gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, x, y, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(), + pixmap.getGLType(), pixmap.getPixels()); } - /** - * - * @return the width of the texture in pixels - */ + /** @return the width of the texture in pixels */ public int getWidth () { return data.getWidth(); } - /** - * - * @return the height of the texture in pixels - */ + /** @return the height of the texture in pixels */ public int getHeight () { return data.getHeight(); } - public TextureFilter getMinFilter() { + public TextureFilter getMinFilter () { return minFilter; } - - public TextureFilter getMagFilter() { + + public TextureFilter getMagFilter () { return magFilter; } - - public TextureWrap getUWrap() { + + public TextureWrap getUWrap () { return uWrap; } - - public TextureWrap getVWrap() { + + public TextureWrap getVWrap () { return vWrap; } - - public TextureData getTextureData() { + + public TextureData getTextureData () { return data; } - - /** - * @return whether this texture is managed or not. - */ + + /** @return whether this texture is managed or not. */ public boolean isManaged () { return data.isManaged(); } - + public int getTextureObjectHandle () { return glHandle; } - /** - * Sets the {@link TextureWrap} for this texture on the u and v axis. This will bind - * this texture! + /** Sets the {@link TextureWrap} for this texture on the u and v axis. This will bind this texture! * * @param u the u wrap - * @param v the v wrap - */ + * @param v the v wrap */ public void setWrap (TextureWrap u, TextureWrap v) { this.uWrap = u; this.vWrap = v; @@ -312,67 +289,59 @@ public void setWrap (TextureWrap u, TextureWrap v) { Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, u.getGLEnum()); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, v.getGLEnum()); } - - public void setFilter(TextureFilter minFilter, TextureFilter magFilter) { + + public void setFilter (TextureFilter minFilter, TextureFilter magFilter) { this.minFilter = minFilter; this.magFilter = magFilter; bind(); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter.getGLEnum()); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter.getGLEnum()); } - - /** - * Disposes all resources associated with the texture - */ + + /** Disposes all resources associated with the texture */ public void dispose () { buffer.put(0, glHandle); Gdx.gl.glDeleteTextures(1, buffer); - if(data.isManaged()) { - if(managedTextures.get(Gdx.app) != null) managedTextures.get(Gdx.app).remove(this); + if (data.isManaged()) { + if (managedTextures.get(Gdx.app) != null) managedTextures.get(Gdx.app).remove(this); } } - - /** - * @param enforcePotImages whether to enforce power of two images in OpenGL ES 1.0 or not. - */ + + /** @param enforcePotImages whether to enforce power of two images in OpenGL ES 1.0 or not. */ static public void setEnforcePotImages (boolean enforcePotImages) { Texture.enforcePotImages = enforcePotImages; } - - private static void addManagedTexture(Application app, Texture texture) { + + private static void addManagedTexture (Application app, Texture texture) { List managedTexureList = managedTextures.get(app); - if(managedTexureList == null) managedTexureList = new ArrayList(); + if (managedTexureList == null) managedTexureList = new ArrayList(); managedTexureList.add(texture); managedTextures.put(app, managedTexureList); } - - /** - * Clears all managed textures. This is an internal method. Do not use it! - */ + + /** Clears all managed textures. This is an internal method. Do not use it! */ public static void clearAllTextures (Application app) { managedTextures.remove(app); } - - /** - * Invalidate all managed textures. This is an internal method. Do not use it! - */ + + /** Invalidate all managed textures. This is an internal method. Do not use it! */ public static void invalidateAllTextures (Application app) { List managedTexureList = managedTextures.get(app); - if(managedTexureList == null) return; - - if(assetManager == null) { - for (int i = 0; i < managedTexureList.size(); i++) { - Texture texture = managedTexureList.get(i); - texture.reload(); + if (managedTexureList == null) return; + + if (assetManager == null) { + for (int i = 0; i < managedTexureList.size(); i++) { + Texture texture = managedTexureList.get(i); + texture.reload(); } } else { List textures = new ArrayList(managedTexureList); managedTexureList.clear(); - for(Texture texture: textures) { + for (Texture texture : textures) { String fileName = assetManager.getAssetFileName(texture); - if(fileName == null) { + if (fileName == null) { texture.reload(); - } else { + } else { TextureParameter params = new TextureParameter(); params.format = texture.getTextureData().getFormat(); params.genMipMaps = texture.getTextureData().useMipMaps(); @@ -385,27 +354,23 @@ public static void invalidateAllTextures (Application app) { } } } - - /** - * Sets the {@link AssetManager}. When the context is lost, textures managed - * by the asset manager are reloaded by the manager on a separate thread (provided - * that a suitable {@link AssetLoader} is registered with the manager). Textures - * not managed by the AssetManager are reloaded via the usual means on the - * rendering thread. - * @param manager the asset manager. - */ - public static void setAssetManager(AssetManager manager) { + + /** Sets the {@link AssetManager}. When the context is lost, textures managed by the asset manager are reloaded by the manager + * on a separate thread (provided that a suitable {@link AssetLoader} is registered with the manager). Textures not managed by + * the AssetManager are reloaded via the usual means on the rendering thread. + * @param manager the asset manager. */ + public static void setAssetManager (AssetManager manager) { Texture.assetManager = manager; } - public static String getManagedStatus() { + public static String getManagedStatus () { StringBuilder builder = new StringBuilder(); builder.append("Managed textures/app: { "); - for(Application app: managedTextures.keySet()) { + for (Application app : managedTextures.keySet()) { builder.append(managedTextures.get(app).size()); builder.append(" "); } builder.append("}"); return builder.toString(); } -} \ No newline at end of file +} diff --git a/gdx/src/com/badlogic/gdx/graphics/TextureData.java b/gdx/src/com/badlogic/gdx/graphics/TextureData.java index e7cff82d80a..86e77b97889 100644 --- a/gdx/src/com/badlogic/gdx/graphics/TextureData.java +++ b/gdx/src/com/badlogic/gdx/graphics/TextureData.java @@ -13,35 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.graphics; -import java.nio.ByteBuffer; +package com.badlogic.gdx.graphics; import com.badlogic.gdx.graphics.Pixmap.Format; - -/** - * Loads image data for a texture. Used with - * {@link Texture}, this allows custom - * image loading for managed textures. If the OpenGL context is lost, the TextureData will be asked to load again when the context - * is restored. The TextureData doesn't necessary need to keep the image data in memory between loads. - */ +/** Loads image data for a texture. Used with {@link Texture}, this allows custom image loading for managed textures. If the OpenGL + * context is lost, the TextureData will be asked to load again when the context is restored. The TextureData doesn't necessary + * need to keep the image data in memory between loads. */ public interface TextureData { public enum TextureDataType { - Pixmap, - Compressed + Pixmap, Compressed } - public TextureDataType getType(); - - public Pixmap getPixmap(); - public boolean disposePixmap(); - - public void uploadCompressedData(); - - public int getWidth(); - public int getHeight(); - public Format getFormat(); - public boolean useMipMaps(); - public boolean isManaged(); + public TextureDataType getType (); + + public Pixmap getPixmap (); + + public boolean disposePixmap (); + + public void uploadCompressedData (); + + public int getWidth (); + + public int getHeight (); + + public Format getFormat (); + + public boolean useMipMaps (); + + public boolean isManaged (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/TextureDict.java b/gdx/src/com/badlogic/gdx/graphics/TextureDict.java index 8731a397afa..53d0adda197 100644 --- a/gdx/src/com/badlogic/gdx/graphics/TextureDict.java +++ b/gdx/src/com/badlogic/gdx/graphics/TextureDict.java @@ -13,90 +13,68 @@ * 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.Files.FileType; +import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.utils.ObjectMap; -/** -*

        -* A texture dictionary is used to track the usage of your textures and supply a single point of access for texture resources. -* It stores {@link TextureRef}s by their path. If you need to load the same texture in different parts of your application -* it will only be loaded into memory once by the dictionary. -*

        -* -* @author Dave Clayton -* -*/ +/**

        + * A texture dictionary is used to track the usage of your textures and supply a single point of access for texture resources. It + * stores {@link TextureRef}s by their path. If you need to load the same texture in different parts of your application it will + * only be loaded into memory once by the dictionary. + *

        + * + * @author Dave Clayton */ public class TextureDict { - + private static ObjectMap sDictionary = new ObjectMap(); - /** - * Loads a new texture into the dictionary as a reference counted {@link TextureRef}. - * @param path - * the path to the texture image. - * @return the {@TextureRef} representing the texture. - */ - public static TextureRef loadTexture(String path) - { - return loadTexture(path, - TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); + /** Loads a new texture into the dictionary as a reference counted {@link TextureRef}. + * @param path the path to the texture image. + * @return the {@TextureRef} representing the texture. */ + public static TextureRef loadTexture (String path) { + return loadTexture(path, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); } - - /** - * Loads a new texture into the dictionary as a reference counted {@link TextureRef}. - * @param path - * the path to the texture image. - * @param minFilter - * minFilter {@link TextureFilter}. - * @param magFilter - * magFilter {@link TextureFilter}. - * @param uwrap - * u-wrapping. - * @param vwrap - * v-wrapping. - * @return the {@TextureRef} representing the texture. - */ - public static TextureRef loadTexture(String path, - TextureFilter minFilter, TextureFilter magFilter, TextureWrap uwrap, TextureWrap vwrap) - { - if(sDictionary.containsKey(path)) - { + + /** Loads a new texture into the dictionary as a reference counted {@link TextureRef}. + * @param path the path to the texture image. + * @param minFilter minFilter {@link TextureFilter}. + * @param magFilter magFilter {@link TextureFilter}. + * @param uwrap u-wrapping. + * @param vwrap v-wrapping. + * @return the {@TextureRef} representing the texture. */ + public static TextureRef loadTexture (String path, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uwrap, + TextureWrap vwrap) { + if (sDictionary.containsKey(path)) { TextureRef ref = sDictionary.get(path); ref.addRef(); return ref; } // load new texture FileHandle texFile = Gdx.app.getFiles().getFileHandle(path, FileType.Internal); - Texture newTex = new Texture(texFile, minFilter.isMipMap() || magFilter.isMipMap()?true:false); + Texture newTex = new Texture(texFile, minFilter.isMipMap() || magFilter.isMipMap() ? true : false); newTex.setFilter(minFilter, magFilter); - newTex.setWrap(uwrap, vwrap); + newTex.setWrap(uwrap, vwrap); TextureRef ref = new TextureRef(path, newTex); sDictionary.put(path, ref); return ref; } - - /** - * Removes a texture from the dictionary. In general you should probably not use this - use {@link TextureRef#unload()} instead. - * @param path to the texture. - */ - public static void removeTexture(String path) - { + + /** Removes a texture from the dictionary. In general you should probably not use this - use {@link TextureRef#unload()} + * instead. + * @param path to the texture. */ + public static void removeTexture (String path) { sDictionary.remove(path); } - - /** - * Unloads all of the currently managed textures. - */ - public static void unloadAll() - { - for(TextureRef tex : sDictionary.values()) - { + + /** Unloads all of the currently managed textures. */ + public static void unloadAll () { + for (TextureRef tex : sDictionary.values()) { tex.dispose(); } sDictionary.clear(); diff --git a/gdx/src/com/badlogic/gdx/graphics/TextureRef.java b/gdx/src/com/badlogic/gdx/graphics/TextureRef.java index c1678b48bfb..3a1f0d92a08 100644 --- a/gdx/src/com/badlogic/gdx/graphics/TextureRef.java +++ b/gdx/src/com/badlogic/gdx/graphics/TextureRef.java @@ -13,79 +13,57 @@ * 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 reference counted wrapper for a {@link Texture}. TextureRefs are managed by the {@link TextureDict}. -*

        -* -* @author Dave Clayton -* -*/ +/**

        + * A reference counted wrapper for a {@link Texture}. TextureRefs are managed by the {@link TextureDict}. + *

        + * + * @author Dave Clayton */ public class TextureRef { public String Name; private int mRefCount; private Texture mTexture; - /** - * Create a new TextureRef with the given name and texture. - * @param name - * The texture's name, typically its filesystem path. - * @param texture - * The texture it reference counts. - */ - public TextureRef(String name, Texture texture) - { + /** Create a new TextureRef with the given name and texture. + * @param name The texture's name, typically its filesystem path. + * @param texture The texture it reference counts. */ + public TextureRef (String name, Texture texture) { Name = name; mTexture = texture; mRefCount = 1; } - - /** - * Adds a reference to the texture. - */ - public void addRef() - { + + /** Adds a reference to the texture. */ + public void addRef () { mRefCount++; } - - /** - * Removes a reference to the texture. If the internal reference count reaches 0, the texture is disposed. - * @return the new reference count. - */ - public int unload() - { - if(--mRefCount == 0) - { + + /** Removes a reference to the texture. If the internal reference count reaches 0, the texture is disposed. + * @return the new reference count. */ + public int unload () { + if (--mRefCount == 0) { mTexture.dispose(); mTexture = null; - // Note: This doesn't seem the best way to do this, but it works. Re-factoring welcome :) + // Note: This doesn't seem the best way to do this, but it works. Re-factoring welcome :) TextureDict.removeTexture(Name); } return mRefCount; } - - public void dispose() - { + + public void dispose () { mTexture.dispose(); } - /** - * Binds the texture in OpenGL. - */ - public void bind() - { + /** Binds the texture in OpenGL. */ + public void bind () { mTexture.bind(); } - - /** - * Gets the wrapped texture. - * @return the texture. - */ - public Texture get() - { + + /** Gets the wrapped texture. + * @return the texture. */ + public Texture get () { return mTexture; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java b/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java index f233ec3f779..44a91f1a171 100644 --- a/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java +++ b/gdx/src/com/badlogic/gdx/graphics/VertexAttribute.java @@ -13,20 +13,18 @@ * 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; import com.badlogic.gdx.graphics.glutils.ShaderProgram; -/** - * A single vertex attribute defined by its {@link Usage}, its number of components and its shader alias. The Usage is needed for +/** 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 - * - */ + * @author mzechner */ public final class VertexAttribute { /** the attribute {@link Usage} **/ public final int usage; @@ -37,14 +35,12 @@ public final class VertexAttribute { /** the alias for the attribute used in a {@link ShaderProgram} **/ 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 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. - */ + * @param alias the alias used in a shader for this attribute. Can be changed after construction. */ public VertexAttribute (int usage, int numComponents, String alias) { this.usage = usage; this.numComponents = numComponents; diff --git a/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java b/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java index 00cb3a0b2b4..104bc90b2c5 100644 --- a/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java +++ b/gdx/src/com/badlogic/gdx/graphics/VertexAttributes.java @@ -13,22 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + 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 +/** 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 - * - */ + * @author mzechner */ public final class VertexAttributes { - /** - * The usage of a vertex attribute. - * - * @author mzechner + /** The usage of a vertex attribute. * - */ + * @author mzechner */ public static final class Usage { public static final int Position = 0; public static final int Color = 1; @@ -44,9 +39,7 @@ public static final class Usage { /** 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"); @@ -101,24 +94,20 @@ private void checkValidity () { if (pos == false) throw new IllegalArgumentException("no position attribute was specified"); } - /** - * @return the number of attributes - */ + /** @return the number of attributes */ public int size () { return attributes.length; } - /** - * @param index the index - * @return the VertexAttribute at the given index - */ + /** @param index the index + * @return the VertexAttribute at the given index */ public VertexAttribute get (int index) { return attributes[index]; } - - public String toString() { + + public String toString () { StringBuilder builder = new StringBuilder(); - for(int i = 0; i < attributes.length; i++) { + for (int i = 0; i < attributes.length; i++) { builder.append(attributes[i].alias); builder.append(", "); builder.append(attributes[i].usage); diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/Animation.java b/gdx/src/com/badlogic/gdx/graphics/g2d/Animation.java index 5a305a39799..2789b17a605 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/Animation.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/Animation.java @@ -13,49 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d; -/** - *

        An Animation stores a list of {@link TextureRegion}s representing an - * animated sequence, e.g. for running or jumping. Each region of an - * Animation is called a key frame, multiple key frames make up the - * animation.

        +/**

        + * An Animation stores a list of {@link TextureRegion}s representing an animated sequence, e.g. for running or jumping. Each + * region of an Animation is called a key frame, multiple key frames make up the animation. + *

        * - * @author mzechner - * - */ -public class Animation { - final TextureRegion[] keyFrames; - public float frameDuration; - - /** - * Constructor, storing the frame duration and key frames. - * - * @param frameDuration the time between frames in seconds. - * @param keyFrames the {@link TextureRegion}s representing the frames. - */ - public Animation(float frameDuration, TextureRegion ... keyFrames) { - this.frameDuration = frameDuration; - this.keyFrames = keyFrames; - } - - /** - * Returns a {@link TextureRegion} based on the so called state time. - * This is the amount of seconds an object has spent in the state this - * Animation instance represents, e.g. running, jumping and so on. The - * mode specifies whether the animation is looping or not. - * @param stateTime the time spent in the state represented by this animation. - * @param looping whether the animation is looping or not. - * @return the TextureRegion representing the frame of animation for the given state time. - */ - public TextureRegion getKeyFrame(float stateTime, boolean looping) { - int frameNumber = (int)(stateTime / frameDuration); - - if(!looping) { - frameNumber = Math.min(keyFrames.length-1, frameNumber); - } else { - frameNumber = frameNumber % keyFrames.length; - } - return keyFrames[frameNumber]; - } + * @author mzechner */ +public class Animation { + final TextureRegion[] keyFrames; + public float frameDuration; + + /** Constructor, storing the frame duration and key frames. + * + * @param frameDuration the time between frames in seconds. + * @param keyFrames the {@link TextureRegion}s representing the frames. */ + public Animation (float frameDuration, TextureRegion... keyFrames) { + this.frameDuration = frameDuration; + this.keyFrames = keyFrames; + } + + /** Returns a {@link TextureRegion} based on the so called state time. This is the amount of seconds an object has spent in the + * state this Animation instance represents, e.g. running, jumping and so on. The mode specifies whether the animation is + * looping or not. + * @param stateTime the time spent in the state represented by this animation. + * @param looping whether the animation is looping or not. + * @return the TextureRegion representing the frame of animation for the given state time. */ + public TextureRegion getKeyFrame (float stateTime, boolean looping) { + int frameNumber = (int)(stateTime / frameDuration); + + if (!looping) { + frameNumber = Math.min(keyFrames.length - 1, frameNumber); + } else { + frameNumber = frameNumber % keyFrames.length; + } + return keyFrames[frameNumber]; + } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java index acdd5f3e66f..0d473488bad 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFont.java @@ -37,8 +37,7 @@ import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.NumberUtils; -/** - * Renders bitmap fonts. The font consists of 2 files: an image file or {@link TextureRegion} containing the glyphs and a file in +/** Renders bitmap fonts. The font consists of 2 files: an image file or {@link TextureRegion} containing the glyphs and a file in * the AngleCode BMFont text format that describes where each glyph is on the image. Currently only a single image of glyphs is * supported.
        *
        @@ -51,16 +50,15 @@ *
        * The code is based on Matthias Mann's TWL BitmapFont class. Thanks for sharing, Matthias! :) * @author Nathan Sweet - * @author Matthias Mann - */ + * @author Matthias Mann */ public class BitmapFont implements Disposable { static private final int LOG2_PAGE_SIZE = 9; static private final int PAGE_SIZE = 1 << LOG2_PAGE_SIZE; static private final int PAGES = 0x10000 / PAGE_SIZE; static final char[] xChars = {'x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z'}; - static final char[] capChars = {'M', 'N', 'B', 'D', 'C', 'E', 'F', 'K', 'A', 'G', 'H', 'I', 'J', 'L', 'O', 'P', 'Q', - 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; + static final char[] capChars = {'M', 'N', 'B', 'D', 'C', 'E', 'F', 'K', 'A', 'G', 'H', 'I', 'J', 'L', 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; TextureRegion region; private final TextBounds textBounds = new TextBounds(); @@ -79,12 +77,12 @@ public static class BitmapFontData { float descent; float down; float scaleX = 1, scaleY = 1; - + final Glyph[][] glyphs = new Glyph[PAGES][]; float spaceWidth; float xHeight = 1; - - public BitmapFontData(FileHandle fontFile, boolean flip) { + + public BitmapFontData (FileHandle fontFile, boolean flip) { this.flipped = flip; BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.read()), 512); try { @@ -111,7 +109,7 @@ public BitmapFontData(FileHandle fontFile, boolean flip) { } else { imgFilename = pageLine[2].substring(5, pageLine[2].length()); } - imgFile = fontFile.parent().child(imgFilename).path().replaceAll("\\\\", "/"); + imgFile = fontFile.parent().child(imgFilename).path().replaceAll("\\\\", "/"); descent = 0; while (true) { @@ -126,9 +124,9 @@ public BitmapFontData(FileHandle fontFile, boolean flip) { tokens.nextToken(); tokens.nextToken(); int ch = Integer.parseInt(tokens.nextToken()); - if (ch <= Character.MAX_VALUE) + if (ch <= Character.MAX_VALUE) setGlyph(ch, glyph); - else + else continue; tokens.nextToken(); glyph.srcX = Integer.parseInt(tokens.nextToken()); @@ -146,7 +144,7 @@ public BitmapFontData(FileHandle fontFile, boolean flip) { else glyph.yoffset = -(glyph.height + Integer.parseInt(tokens.nextToken())); tokens.nextToken(); - glyph.xadvance = Integer.parseInt(tokens.nextToken()); + glyph.xadvance = Integer.parseInt(tokens.nextToken()); descent = Math.min(baseLine + glyph.yoffset, descent); } @@ -208,13 +206,13 @@ public BitmapFontData(FileHandle fontFile, boolean flip) { } } } - + private void setGlyph (int ch, Glyph glyph) { Glyph[] page = glyphs[ch / PAGE_SIZE]; if (page == null) glyphs[ch / PAGE_SIZE] = page = new Glyph[PAGE_SIZE]; page[ch & PAGE_SIZE - 1] = glyph; } - + private Glyph getFirstGlyph () { for (Glyph[] page : this.glyphs) { if (page == null) continue; @@ -225,93 +223,81 @@ private Glyph getFirstGlyph () { } throw new GdxRuntimeException("No glyphs found!"); } - + public Glyph getGlyph (char ch) { Glyph[] page = glyphs[ch / PAGE_SIZE]; if (page != null) return page[ch & PAGE_SIZE - 1]; return null; } - - public String getImageFile() { + + public String getImageFile () { return imgFile; } } - - /** - * Creates a BitmapFont using the default 15pt Arial font included in the libgdx JAR file. This is convenient to easily display - * text without bothering with generating a bitmap font. - */ + + /** Creates a BitmapFont using the default 15pt Arial font included in the libgdx JAR file. This is convenient to easily display + * text without bothering with generating a bitmap font. */ public BitmapFont () { this(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"), Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"), false, true); } - /** - * Creates a BitmapFont using the default 15pt Arial font included in the libgdx JAR file. This is convenient to easily display + /** Creates a BitmapFont using the default 15pt Arial font included in the libgdx JAR file. This is convenient to easily display * text without bothering with generating a bitmap font. - * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. - */ + * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */ public BitmapFont (boolean flip) { this(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"), Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"), flip, true); } - /** - * Creates a BitmapFont with the glyphs relative to the specified region. + /** Creates a BitmapFont with the glyphs relative to the specified region. * @param region The texture region containing the glyphs. The glyphs must be relative to the lower left corner (ie, the region * should not be flipped). - * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. - */ + * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */ public BitmapFont (FileHandle fontFile, TextureRegion region, boolean flip) { this(new BitmapFontData(fontFile, flip), region, true); } - /** - * Creates a BitmapFont from a BMFont file. The image file name is read from the BMFont file and the image is loaded from the + /** Creates a BitmapFont from a BMFont file. The image file name is read from the BMFont file and the image is loaded from the * same directory. - * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. - */ + * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */ public BitmapFont (FileHandle fontFile, boolean flip) { this(new BitmapFontData(fontFile, flip), null, true); } - /** - * Creates a BitmapFont from a BMFont file, using the specified image for glyphs. Any image specified in the BMFont file is + /** Creates a BitmapFont from a BMFont file, using the specified image for glyphs. Any image specified in the BMFont file is * ignored. - * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. - */ + * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. */ public BitmapFont (FileHandle fontFile, FileHandle imageFile, boolean flip) { this(fontFile, imageFile, flip, true); } - /** - * Creates a BitmapFont from a BMFont file, using the specified image for glyphs. Any image specified in the BMFont file is + /** Creates a BitmapFont from a BMFont file, using the specified image for glyphs. Any image specified in the BMFont file is * ignored. * @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner. - * @param integer If true, rendering positions will be at integer values to avoid filtering artifacts.s - */ + * @param integer If true, rendering positions will be at integer values to avoid filtering artifacts.s */ public BitmapFont (FileHandle fontFile, FileHandle imageFile, boolean flip, boolean integer) { this(new BitmapFontData(fontFile, flip), new TextureRegion(new Texture(imageFile, false)), integer); } - - public BitmapFont(BitmapFontData data, TextureRegion region, boolean integer) { - this.region = region == null? new TextureRegion(new Texture(Gdx.files.internal(data.imgFile), false)): region; + + public BitmapFont (BitmapFontData data, TextureRegion region, boolean integer) { + this.region = region == null ? new TextureRegion(new Texture(Gdx.files.internal(data.imgFile), false)) : region; this.flipped = data.flipped; this.integer = integer; this.data = data; load(data); } - private void load(BitmapFontData data) { + private void load (BitmapFontData data) { float invTexWidth = 1.0f / region.getTexture().getWidth(); float invTexHeight = 1.0f / region.getTexture().getHeight(); float u = region.u; float v = region.v; - - for(Glyph[] page : data.glyphs) { - if(page == null) continue; - for(Glyph glyph : page) { - if(glyph == null) continue; + + for (Glyph[] page : data.glyphs) { + if (page == null) continue; + for (Glyph glyph : page) { + if (glyph == null) continue; glyph.u = u + glyph.srcX * invTexWidth; glyph.u2 = u + (glyph.srcX + glyph.width) * invTexWidth; if (data.flipped) { @@ -325,26 +311,22 @@ private void load(BitmapFontData data) { } } - /** - * Draws a string at the specified position. + /** Draws a string at the specified position. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}). * @return The bounds of the rendered string (the height is the distance from y to the baseline). Note the same TextBounds - * instance is used for all methods that return TextBounds. - */ + * instance is used for all methods that return TextBounds. */ public TextBounds draw (SpriteBatch spriteBatch, CharSequence str, float x, float y) { return draw(spriteBatch, str, x, y, 0, str.length()); } - /** - * Draws a substring at the specified position. + /** Draws a substring at the specified position. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}). * @param start The first character of the string to draw. * @param end The last character of the string to draw (exclusive). * @return The bounds of the rendered string (the height is the distance from y to the baseline). Note the same TextBounds - * instance is used for all methods that return TextBounds. - */ + * instance is used for all methods that return TextBounds. */ public TextBounds draw (SpriteBatch spriteBatch, CharSequence str, float x, float y, int start, int end) { float batchColor = spriteBatch.color; spriteBatch.setColor(color); @@ -444,25 +426,21 @@ public TextBounds draw (SpriteBatch spriteBatch, CharSequence str, float x, floa return textBounds; } - /** - * Draws a string, which may contain newlines (\n), at the specified position. + /** Draws a string, which may contain newlines (\n), at the specified position. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}). * @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the - * same TextBounds instance is used for all methods that return TextBounds. - */ + * same TextBounds instance is used for all methods that return TextBounds. */ public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str, float x, float y) { return drawMultiLine(spriteBatch, str, x, y, 0, HAlignment.LEFT); } - /** - * Draws a string, which may contain newlines (\n), at the specified position and alignment. Each line is aligned horizontally + /** Draws a string, which may contain newlines (\n), at the specified position and alignment. Each line is aligned horizontally * within a rectangle of the specified width. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}). * @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the - * same TextBounds instance is used for all methods that return TextBounds. - */ + * same TextBounds instance is used for all methods that return TextBounds. */ public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str, float x, float y, float alignmentWidth, HAlignment alignment) { float batchColor = spriteBatch.color; @@ -492,26 +470,22 @@ public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str, floa return textBounds; } - /** - * Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it + /** Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it * within a rectangle of the specified width. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}). * @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the - * same TextBounds instance is used for all methods that return TextBounds. - */ + * same TextBounds instance is used for all methods that return TextBounds. */ public TextBounds drawWrapped (SpriteBatch spriteBatch, CharSequence str, float x, float y, float wrapWidth) { return drawWrapped(spriteBatch, str, x, y, wrapWidth, HAlignment.LEFT); } - /** - * Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it + /** Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it * within a rectangle of the specified width, and aligned horizontally within that rectangle. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}). * @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the - * same TextBounds instance is used for all methods that return TextBounds. - */ + * same TextBounds instance is used for all methods that return TextBounds. */ public TextBounds drawWrapped (SpriteBatch spriteBatch, CharSequence str, float x, float y, float wrapWidth, HAlignment alignment) { float batchColor = spriteBatch.color; @@ -558,22 +532,18 @@ public TextBounds drawWrapped (SpriteBatch spriteBatch, CharSequence str, float return textBounds; } - /** - * Returns the size of the specified string. The height is the distance from the top of most capital letters in the font (the + /** Returns the size of the specified string. The height is the distance from the top of most capital letters in the font (the * {@link #getCapHeight() cap height}) to the baseline. Note the same TextBounds instance is used for all methods that return - * TextBounds. - */ + * TextBounds. */ public TextBounds getBounds (CharSequence str) { return getBounds(str, 0, str.length()); } - /** - * Returns the size of the specified substring. The height is the distance from the top of most capital letters in the font + /** Returns the size of the specified substring. The height is the distance from the top of most capital letters in the font * (the {@link #getCapHeight() cap height}) to the baseline. Note the same TextBounds instance is used for all methods that * return TextBounds. * @param start The first character of the string. - * @param end The last character of the string (exclusive). - */ + * @param end The last character of the string (exclusive). */ public TextBounds getBounds (CharSequence str, int start, int end) { int width = 0; Glyph lastGlyph = null; @@ -598,11 +568,9 @@ public TextBounds getBounds (CharSequence str, int start, int end) { return textBounds; } - /** - * Returns the size of the specified string, which may contain newlines. The height is the distance from the top of most + /** Returns the size of the specified string, which may contain newlines. The height is the distance from the top of most * capital letters in the font (the {@link #getCapHeight() cap height}) to the baseline of the last line of text. Note the same - * TextBounds instance is used for all methods that return TextBounds. - */ + * TextBounds instance is used for all methods that return TextBounds. */ public TextBounds getMultiLineBounds (CharSequence str) { int start = 0; float maxWidth = 0; @@ -620,12 +588,10 @@ public TextBounds getMultiLineBounds (CharSequence str) { return textBounds; } - /** - * Returns the size of the specified string, which may contain newlines and is wrapped to keep it within a rectangle of the + /** Returns the size of the specified string, which may contain newlines and is wrapped to keep it within a rectangle of the * specified width. The height is the distance from the top of most capital letters in the font (the {@link #getCapHeight() cap * height}) to the baseline of the last line of text. Note the same TextBounds instance is used for all methods that return - * TextBounds. - */ + * TextBounds. */ public TextBounds getWrappedBounds (CharSequence str, float wrapWidth) { int start = 0; int numLines = 0; @@ -661,13 +627,11 @@ public TextBounds getWrappedBounds (CharSequence str, float wrapWidth) { return textBounds; } - /** - * Computes the glyph advances for the given character sequence and stores them in the provided {@link FloatArray}. The + /** Computes the glyph advances for the given character sequence and stores them in the provided {@link FloatArray}. The * FloatArray is cleared. This will add an additional element at the end. * @param str the character sequence * @param glyphAdvances the glyph advances output array. - * @param glyphPositions the glyph positions output array. - */ + * @param glyphPositions the glyph positions output array. */ public void computeGlyphAdvancesAndPositions (CharSequence str, FloatArray glyphAdvances, FloatArray glyphPositions) { glyphAdvances.clear(); glyphPositions.clear(); @@ -707,11 +671,9 @@ public void computeGlyphAdvancesAndPositions (CharSequence str, FloatArray glyph } } - /** - * Returns the number of glyphs from the substring that can be rendered in the specified width. + /** Returns the number of glyphs from the substring that can be rendered in the specified width. * @param start The first character of the string. - * @param end The last character of the string (exclusive). - */ + * @param end The last character of the string (exclusive). */ public int computeVisibleGlyphs (CharSequence str, int start, int end, float availableWidth) { int index = start; int width = 0; @@ -752,10 +714,8 @@ public void setColor (float r, float g, float b, float a) { color = NumberUtils.intBitsToFloat((intBits & 0xfeffffff)); } - /** - * Returns the color of this font. Changing the returned color will have no affect, {@link #setColor(Color)} or - * {@link #setColor(float, float, float, float)} must be used. - */ + /** Returns the color of this font. Changing the returned color will have no affect, {@link #setColor(Color)} or + * {@link #setColor(float, float, float, float)} must be used. */ public Color getColor () { int intBits = NumberUtils.floatToRawIntBits(color); Color color = this.tempColor; @@ -777,19 +737,15 @@ public void setScale (float scaleX, float scaleY) { data.scaleY = scaleY; } - /** - * Scales the font by the specified amount in both directions.
        + /** Scales the font by the specified amount in both directions.
        *
        * Note that smoother scaling can be achieved if the texture backing the BitmapFont is using {@link TextureFilter#Linear}. The - * default is Nearest, so use a BitmapFont constructor that takes a {@link TextureRegion}. - */ + * default is Nearest, so use a BitmapFont constructor that takes a {@link TextureRegion}. */ public void setScale (float scaleXY) { setScale(scaleXY, scaleXY); } - /** - * Sets the font's scale relative to the current scale. - */ + /** Sets the font's scale relative to the current scale. */ public void scale (float amount) { setScale(data.scaleX + amount, data.scaleY + amount); } @@ -806,67 +762,49 @@ public TextureRegion getRegion () { return region; } - /** - * Returns the line height, which is the distance from one line of text to the next. - */ + /** Returns the line height, which is the distance from one line of text to the next. */ public float getLineHeight () { return data.lineHeight; } - /** - * Returns the width of the space character. - */ + /** Returns the width of the space character. */ public float getSpaceWidth () { return data.spaceWidth; } - /** - * Returns the x-height, which is the distance from the top of most lowercase characters to the baseline. - */ + /** Returns the x-height, which is the distance from the top of most lowercase characters to the baseline. */ public float getXHeight () { return data.xHeight; } - /** - * Returns the cap height, which is the distance from the top of most uppercase characters to the baseline. Since the drawing - * position is the cap height of the first line, the cap height can be used to get the location of the baseline. - */ + /** Returns the cap height, which is the distance from the top of most uppercase characters to the baseline. Since the drawing + * position is the cap height of the first line, the cap height can be used to get the location of the baseline. */ public float getCapHeight () { return data.capHeight; } - /** - * Returns the ascent, which is the distance from the cap height to the top of the tallest glyph. - */ + /** Returns the ascent, which is the distance from the cap height to the top of the tallest glyph. */ public float getAscent () { return data.ascent; } - /** - * Returns the descent, which is the distance from the bottom of the glyph 'g' to the baseline. This number is negative. - */ + /** Returns the descent, which is the distance from the bottom of the glyph 'g' to the baseline. This number is negative. */ public float getDescent () { return data.descent; } - /** - * Returns true if this BitmapFont has been flipped for use with a y-down coordinate system. - */ + /** Returns true if this BitmapFont has been flipped for use with a y-down coordinate system. */ public boolean isFlipped () { return flipped; } - /** - * Disposes the texture used by this BitmapFont's region. - */ + /** Disposes the texture used by this BitmapFont's region. */ public void dispose () { region.getTexture().dispose(); } - /** - * Makes the specified glyphs fixed width. This can be useful to make the numbers in a font fixed width. Eg, when horizontally - * centering a score or loading percentage text, it will not jump around as different numbers are shown. - */ + /** Makes the specified glyphs fixed width. This can be useful to make the numbers in a font fixed width. Eg, when horizontally + * centering a score or loading percentage text, it will not jump around as different numbers are shown. */ public void setFixedWidthGlyphs (CharSequence glyphs) { int maxAdvance = 0; for (int index = 0, end = glyphs.length(); index < end; index++) { @@ -935,25 +873,19 @@ static public enum HAlignment { LEFT, CENTER, RIGHT } - /** - * @param character - * @return whether the given character is contained in this font. - */ + /** @param character + * @return whether the given character is contained in this font. */ public boolean containsCharacter (char character) { return data.getGlyph(character) != null; } - /** - * Specifies whether to use integer positions or not. Default is to use them so filtering doesn't kick in as badly. - * @param use - */ + /** Specifies whether to use integer positions or not. Default is to use them so filtering doesn't kick in as badly. + * @param use */ public void setUseIntegerPositions (boolean use) { this.integer = use; } - /** - * @return whether this font uses integer positions for drawing. - */ + /** @return whether this font uses integer positions for drawing. */ public boolean usesIntegerPositions () { return integer; } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java index 17ab68a3142..53dee7aedca 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.graphics.Color; @@ -22,12 +23,10 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.NumberUtils; -/** - * Caches glyph geometry for a BitmapFont, providing a fast way to render static text. This saves needing to compute the location +/** Caches glyph geometry for a BitmapFont, providing a fast way to render static text. This saves needing to compute the location * of each glyph each frame. * @author Nathan Sweet - * @author Matthias Mann - */ + * @author Matthias Mann */ public class BitmapFontCache implements Disposable { private final BitmapFont font; private float[] vertices = new float[0]; @@ -39,36 +38,30 @@ public class BitmapFontCache implements Disposable { private boolean integer = true; public BitmapFontCache (BitmapFont font) { - this(font, true); + this(font, true); } - - /** - * Creates a new BitmapFontCache + + /** Creates a new BitmapFontCache * @param font the font to use - * @param integer whether to use integer positions and sizes. - */ + * @param integer whether to use integer positions and sizes. */ public BitmapFontCache (BitmapFont font, boolean integer) { this.font = font; this.integer = integer; } - /** - * Sets the position of the text, relative to the position when the cached text was created. + /** Sets the position of the text, relative to the position when the cached text was created. * @param x The x coordinate - * @param y The y coodinate - */ + * @param y The y coodinate */ public void setPosition (float x, float y) { translate(x - this.x, y - this.y); } - /** - * Sets the position of the text, relative to its current position. + /** Sets the position of the text, relative to its current position. * @param xAmount The amount in x to move the text - * @param yAmount The amount in y to move the text - */ + * @param yAmount The amount in y to move the text */ public void translate (float xAmount, float yAmount) { if (xAmount == 0 && yAmount == 0) return; - if(integer) { + if (integer) { xAmount = (int)xAmount; yAmount = (int)yAmount; } @@ -198,75 +191,71 @@ private void addGlyph (Glyph glyph, float x, float y, float width, float height) final float v2 = glyph.v2; final float[] vertices = this.vertices; - if(!integer) { + if (!integer) { vertices[idx++] = x; vertices[idx++] = y; vertices[idx++] = color; vertices[idx++] = u; vertices[idx++] = v; - + vertices[idx++] = x; vertices[idx++] = y2; vertices[idx++] = color; vertices[idx++] = u; vertices[idx++] = v2; - + vertices[idx++] = x2; vertices[idx++] = y2; vertices[idx++] = color; vertices[idx++] = u2; vertices[idx++] = v2; - + vertices[idx++] = x2; vertices[idx++] = y; vertices[idx++] = color; vertices[idx++] = u2; vertices[idx++] = v; - } else { + } else { vertices[idx++] = (int)x; vertices[idx++] = (int)y; vertices[idx++] = color; vertices[idx++] = u; vertices[idx++] = v; - + vertices[idx++] = (int)x; vertices[idx++] = (int)y2; vertices[idx++] = color; vertices[idx++] = u; vertices[idx++] = v2; - + vertices[idx++] = (int)x2; vertices[idx++] = (int)y2; vertices[idx++] = color; vertices[idx++] = u2; vertices[idx++] = v2; - + vertices[idx++] = (int)x2; vertices[idx++] = (int)y; vertices[idx++] = color; vertices[idx++] = u2; - vertices[idx++] = v; + vertices[idx++] = v; } } - /** - * Caches a string with the specified position. + /** Caches a string with the specified position. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}). - * @return The bounds of the cached string (the height is the distance from y to the baseline). - */ + * @return The bounds of the cached string (the height is the distance from y to the baseline). */ public TextBounds setText (CharSequence str, float x, float y) { return setText(str, x, y, 0, str.length()); } - /** - * Caches a substring with the specified position. + /** Caches a substring with the specified position. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}). * @param start The first character of the string to draw. * @param end The last character of the string to draw (exclusive). - * @return The bounds of the cached string (the height is the distance from y to the baseline). - */ + * @return The bounds of the cached string (the height is the distance from y to the baseline). */ public TextBounds setText (CharSequence str, float x, float y, int start, int end) { reset(end - start); y += font.data.ascent; @@ -275,23 +264,19 @@ public TextBounds setText (CharSequence str, float x, float y, int start, int en return textBounds; } - /** - * Caches a string, which may contain newlines (\n), with the specified position. + /** Caches a string, which may contain newlines (\n), with the specified position. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}). - * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). - */ + * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */ public TextBounds setMultiLineText (CharSequence str, float x, float y) { return setMultiLineText(str, x, y, 0, HAlignment.LEFT); } - /** - * Caches a string, which may contain newlines (\n), with the specified position and alignment. Each line is aligned + /** Caches a string, which may contain newlines (\n), with the specified position and alignment. Each line is aligned * horizontally within a rectangle of the specified width. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}). - * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). - */ + * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */ public TextBounds setMultiLineText (CharSequence str, float x, float y, float alignmentWidth, HAlignment alignment) { BitmapFont font = this.font; @@ -324,24 +309,20 @@ public TextBounds setMultiLineText (CharSequence str, float x, float y, float al return textBounds; } - /** - * Caches a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it + /** Caches a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it * within a rectangle of the specified width. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}). - * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). - */ + * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */ public TextBounds setWrappedText (CharSequence str, float x, float y, float wrapWidth) { return setWrappedText(str, x, y, wrapWidth, HAlignment.LEFT); } - /** - * Caches a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it + /** Caches a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it * within a rectangle of the specified width, and aligned horizontally within that rectangle. * @param x The x position for the left most character. * @param y The y position for the top of most capital letters in the font (the {@link BitmapFont#getCapHeight() cap height}). - * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). - */ + * @return The bounds of the cached string (the height is the distance from y to the baseline of the last line). */ public TextBounds setWrappedText (CharSequence str, float x, float y, float wrapWidth, HAlignment alignment) { BitmapFont font = this.font; @@ -381,24 +362,18 @@ public TextBounds setWrappedText (CharSequence str, float x, float y, float wrap return textBounds; } - /** - * Returns the size of the cached string. The height is the distance from the top of most capital letters in the font (the - * {@link BitmapFont#getCapHeight() cap height}) to the baseline of the last line of text. - */ + /** Returns the size of the cached string. The height is the distance from the top of most capital letters in the font (the + * {@link BitmapFont#getCapHeight() cap height}) to the baseline of the last line of text. */ public TextBounds getBounds () { return textBounds; } - /** - * Returns the x position of the cached string, relative to the position when the string was cached. - */ + /** Returns the x position of the cached string, relative to the position when the string was cached. */ public float getX () { return x; } - /** - * Returns the y position of the cached string, relative to the position when the string was cached. - */ + /** Returns the y position of the cached string, relative to the position when the string was cached. */ public float getY () { return y; } @@ -407,26 +382,19 @@ public BitmapFont getFont () { return font; } - /** - * Disposes the underlying BitmapFont of this cache. - */ + /** Disposes the underlying BitmapFont of this cache. */ public void dispose () { font.dispose(); } - - /** - * Specifies whether to use integer positions or not. Default is to use - * them so filtering doesn't kick in as badly. - * @param use - */ - public void setUseIntegerPositions(boolean use) { + + /** Specifies whether to use integer positions or not. Default is to use them so filtering doesn't kick in as badly. + * @param use */ + public void setUseIntegerPositions (boolean use) { this.integer = use; } - - /** - * @return whether this font uses integer positions for drawing. - */ - public boolean usesIntegerPositions() { + + /** @return whether this font uses integer positions for drawing. */ + public boolean usesIntegerPositions () { return integer; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/EmptyNinePatch.java b/gdx/src/com/badlogic/gdx/graphics/g2d/EmptyNinePatch.java index db1a353084e..ed357c7906a 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/EmptyNinePatch.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/EmptyNinePatch.java @@ -4,9 +4,7 @@ import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture; -/** - * Empty ninepatch for controls that require a ninepatch. - */ +/** Empty ninepatch for controls that require a ninepatch. */ public class EmptyNinePatch extends NinePatch { static private TextureRegion[] emptyPatches; static private EmptyNinePatch instance; diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/Gdx2DPixmap.java b/gdx/src/com/badlogic/gdx/graphics/g2d/Gdx2DPixmap.java index 57e3684b0f9..c6aa3387a14 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/Gdx2DPixmap.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/Gdx2DPixmap.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d; import java.io.ByteArrayOutputStream; @@ -24,11 +25,8 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Experimental. Do not use! - * @author mzechner - * - */ +/** Experimental. Do not use! + * @author mzechner */ public class Gdx2DPixmap implements Disposable { public static final int GDX2D_FORMAT_ALPHA = 1; public static final int GDX2D_FORMAT_LUMINANCE_ALPHA = 2; @@ -36,157 +34,164 @@ public class Gdx2DPixmap implements Disposable { public static final int GDX2D_FORMAT_RGBA8888 = 4; public static final int GDX2D_FORMAT_RGB565 = 5; public static final int GDX2D_FORMAT_RGBA4444 = 6; - + public static final int GDX2D_SCALE_NEAREST = 0; public static final int GDX2D_SCALE_LINEAR = 1; - + public static final int GDX2D_BLEND_NONE = 0; public static final int GDX2D_BLEND_SRC_OVER = 1; - + final long basePtr; final int width; final int height; - final int format; + final int format; final ByteBuffer pixelPtr; - static final long[] nativeData = new long[4]; - + static final long[] nativeData = new long[4]; + static { setBlend(GDX2D_BLEND_SRC_OVER); setScale(GDX2D_SCALE_LINEAR); } - - public Gdx2DPixmap(byte[] encodedData, int offset, int len, int requestedFormat) throws IOException { + + public Gdx2DPixmap (byte[] encodedData, int offset, int len, int requestedFormat) throws IOException { pixelPtr = load(nativeData, encodedData, offset, len, requestedFormat); - if(pixelPtr == null) - throw new IOException("couldn't load pixmap"); - + if (pixelPtr == null) throw new IOException("couldn't load pixmap"); + basePtr = nativeData[0]; width = (int)nativeData[1]; height = (int)nativeData[2]; - format = (int)nativeData[3]; + format = (int)nativeData[3]; } - - public Gdx2DPixmap(InputStream in, int requestedFormat) throws IOException { + + public Gdx2DPixmap (InputStream in, int requestedFormat) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int readBytes = 0; - - while((readBytes = in.read(buffer)) != -1) { + + while ((readBytes = in.read(buffer)) != -1) { bytes.write(buffer, 0, readBytes); } - + buffer = bytes.toByteArray(); pixelPtr = load(nativeData, buffer, 0, buffer.length, requestedFormat); - if(pixelPtr == null) - throw new IOException("couldn't load pixmap"); - + if (pixelPtr == null) throw new IOException("couldn't load pixmap"); + basePtr = nativeData[0]; width = (int)nativeData[1]; height = (int)nativeData[2]; - format = (int)nativeData[3]; + format = (int)nativeData[3]; } - - public Gdx2DPixmap(int width, int height, int format) throws IllegalArgumentException { + + public Gdx2DPixmap (int width, int height, int format) throws IllegalArgumentException { pixelPtr = newPixmap(nativeData, width, height, format); - if(pixelPtr == null) - throw new IllegalArgumentException("couldn't load pixmap"); - + if (pixelPtr == null) throw new IllegalArgumentException("couldn't load pixmap"); + this.basePtr = nativeData[0]; this.width = (int)nativeData[1]; this.height = (int)nativeData[2]; this.format = (int)nativeData[3]; } - - public Gdx2DPixmap(ByteBuffer buffer, long[] nativeData) { + + public Gdx2DPixmap (ByteBuffer buffer, long[] nativeData) { pixelPtr = buffer; - if(pixelPtr == null) - throw new IllegalArgumentException("couldn't load pixmap"); - + if (pixelPtr == null) throw new IllegalArgumentException("couldn't load pixmap"); + System.arraycopy(nativeData, 0, Gdx2DPixmap.nativeData, 0, 4); this.basePtr = nativeData[0]; this.width = (int)nativeData[1]; this.height = (int)nativeData[2]; - this.format = (int)nativeData[3]; + this.format = (int)nativeData[3]; } - public void dispose() { + public void dispose () { free(basePtr); } - - public void clear(int color) { + + public void clear (int color) { clear(basePtr, color); } - - public void setPixel(int x, int y, int color) { + + public void setPixel (int x, int y, int color) { setPixel(basePtr, x, y, color); } - - public int getPixel(int x, int y) { + + public int getPixel (int x, int y) { return getPixel(basePtr, x, y); } - - public void drawLine(int x, int y, int x2, int y2, int color) { + + public void drawLine (int x, int y, int x2, int y2, int color) { drawLine(basePtr, x, y, x2, y2, color); } - - public void drawRect(int x, int y, int width, int height, int color) { + + public void drawRect (int x, int y, int width, int height, int color) { drawRect(basePtr, x, y, width, height, color); } - - public void drawCircle(int x, int y, int radius, int color) { + + public void drawCircle (int x, int y, int radius, int color) { drawCircle(basePtr, x, y, radius, color); } - - public void fillRect(int x, int y, int width, int height, int color) { + + public void fillRect (int x, int y, int width, int height, int color) { fillRect(basePtr, x, y, width, height, color); } - - public void fillCircle(int x, int y, int radius, int color) { + + public void fillCircle (int x, int y, int radius, int color) { fillCircle(basePtr, x, y, radius, color); } - - public void drawPixmap(Gdx2DPixmap src, int srcX, int srcY, int dstX, int dstY, int width, int height) { + + public void drawPixmap (Gdx2DPixmap src, int srcX, int srcY, int dstX, int dstY, int width, int height) { drawPixmap(src.basePtr, basePtr, srcX, srcY, width, height, dstX, dstY, width, height); } - - public void drawPixmap(Gdx2DPixmap src, - int srcX, int srcY, int srcWidth, int srcHeight, - int dstX, int dstY, int dstWidth, int dstHeight) { + + public void drawPixmap (Gdx2DPixmap src, int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, + int dstHeight) { drawPixmap(src.basePtr, basePtr, srcX, srcY, srcWidth, srcHeight, dstX, dstY, dstWidth, dstHeight); } - - - public static Gdx2DPixmap newPixmap(InputStream in, int requestedFormat) { + + public static Gdx2DPixmap newPixmap (InputStream in, int requestedFormat) { try { return new Gdx2DPixmap(in, requestedFormat); - } catch(IOException e) { + } catch (IOException e) { return null; } } - - public static Gdx2DPixmap newPixmap(int width, int height, int format) { + + public static Gdx2DPixmap newPixmap (int width, int height, int format) { try { return new Gdx2DPixmap(width, height, format); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { return null; } - } - - private static native ByteBuffer load(long[] nativeData, byte[] buffer, int offset, int len, int requestedFormat); - private static native ByteBuffer newPixmap(long[] nativeData, int width, int height, int format); - private static native void free(long basePtr); - private static native void clear(long pixmap, int color); - private static native void setPixel(long pixmap, int x, int y, int color); - private static native int getPixel(long pixmap, int x, int y); - private static native void drawLine(long pixmap, int x, int y, int x2, int y2, int color); - private static native void drawRect(long pixmap, int x, int y, int width, int height, int color); - private static native void drawCircle(long pixmap, int x, int y, int radius, int color); - private static native void fillRect(long pixmap, int x, int y, int width, int height, int color); - private static native void fillCircle(long pixmap, int x, int y, int radius, int color); - private static native void drawPixmap(long src, long dst, int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight); - - public static native void setBlend(int blend); - public static native void setScale(int scale); + } + + private static native ByteBuffer load (long[] nativeData, byte[] buffer, int offset, int len, int requestedFormat); + + private static native ByteBuffer newPixmap (long[] nativeData, int width, int height, int format); + + private static native void free (long basePtr); + + private static native void clear (long pixmap, int color); + + private static native void setPixel (long pixmap, int x, int y, int color); + + private static native int getPixel (long pixmap, int x, int y); + + private static native void drawLine (long pixmap, int x, int y, int x2, int y2, int color); + + private static native void drawRect (long pixmap, int x, int y, int width, int height, int color); + + private static native void drawCircle (long pixmap, int x, int y, int radius, int color); + + private static native void fillRect (long pixmap, int x, int y, int width, int height, int color); + + private static native void fillCircle (long pixmap, int x, int y, int radius, int color); + + private static native void drawPixmap (long src, long dst, int srcX, int srcY, int srcWidth, int srcHeight, int dstX, + int dstY, int dstWidth, int dstHeight); + + public static native void setBlend (int blend); + + public static native void setScale (int scale); public ByteBuffer getPixels () { return pixelPtr; @@ -195,17 +200,17 @@ public ByteBuffer getPixels () { public int getHeight () { return height; } - + public int getWidth () { return width; } - - public int getFormat() { + + public int getFormat () { return format; } - - public int getGLInternalFormat() { - switch(format) { + + public int getGLInternalFormat () { + switch (format) { case GDX2D_FORMAT_ALPHA: return GL10.GL_ALPHA; case GDX2D_FORMAT_LUMINANCE_ALPHA: @@ -219,15 +224,15 @@ public int getGLInternalFormat() { default: throw new GdxRuntimeException("unknown format: " + format); } - } - - public int getGLFormat() { + } + + public int getGLFormat () { return getGLInternalFormat(); } - - public int getGLType() { - switch(format) { - case GDX2D_FORMAT_ALPHA: + + public int getGLType () { + switch (format) { + case GDX2D_FORMAT_ALPHA: case GDX2D_FORMAT_LUMINANCE_ALPHA: case GDX2D_FORMAT_RGB888: case GDX2D_FORMAT_RGBA8888: @@ -237,20 +242,20 @@ public int getGLType() { case GDX2D_FORMAT_RGBA4444: return GL10.GL_UNSIGNED_SHORT_4_4_4_4; default: - throw new GdxRuntimeException("unknown format: " + format); + throw new GdxRuntimeException("unknown format: " + format); } } public String getFormatString () { - switch(format) { - case GDX2D_FORMAT_ALPHA: + switch (format) { + case GDX2D_FORMAT_ALPHA: return "alpha"; case GDX2D_FORMAT_LUMINANCE_ALPHA: return "luminance alpha"; case GDX2D_FORMAT_RGB888: return "rgb888"; case GDX2D_FORMAT_RGBA8888: - return "rgba8888"; + return "rgba8888"; case GDX2D_FORMAT_RGB565: return "rgb565"; case GDX2D_FORMAT_RGBA4444: diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/NinePatch.java b/gdx/src/com/badlogic/gdx/graphics/g2d/NinePatch.java index 3145bdbe9d6..2273b77b829 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/NinePatch.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/NinePatch.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.graphics.Texture; @@ -13,102 +14,102 @@ public class NinePatch { public static final int BOTTOM_LEFT = 6; public static final int BOTTOM_CENTER = 7; public static final int BOTTOM_RIGHT = 8; - - final TextureRegion[] patches; - - public NinePatch(Texture texture, int left, int right, int top, int bottom) { + + final TextureRegion[] patches; + + public NinePatch (Texture texture, int left, int right, int top, int bottom) { this(new TextureRegion(texture), left, right, top, bottom); } - public NinePatch(TextureRegion region, int left, int right, int top, int bottom) { + public NinePatch (TextureRegion region, int left, int right, int top, int bottom) { int middleWidth = region.getRegionWidth() - left - right; int middleHeight = region.getRegionHeight() - top - bottom; - this.patches = new TextureRegion[] { - new TextureRegion(region, 0, 0, left, top), - new TextureRegion(region, left, 0, middleWidth, top), - new TextureRegion(region, left + middleWidth, 0, right, top), - new TextureRegion(region, 0, top, left, middleHeight), - new TextureRegion(region, left, top, middleWidth, middleHeight), + this.patches = new TextureRegion[] {new TextureRegion(region, 0, 0, left, top), + new TextureRegion(region, left, 0, middleWidth, top), new TextureRegion(region, left + middleWidth, 0, right, top), + new TextureRegion(region, 0, top, left, middleHeight), new TextureRegion(region, left, top, middleWidth, middleHeight), new TextureRegion(region, left + middleWidth, top, right, middleHeight), new TextureRegion(region, 0, top + middleHeight, left, bottom), new TextureRegion(region, left, top + middleHeight, middleWidth, bottom), - new TextureRegion(region, left + middleWidth, top + middleHeight, right, bottom), - }; + new TextureRegion(region, left + middleWidth, top + middleHeight, right, bottom),}; } - - public NinePatch(TextureRegion ... patches) { - if(patches.length != 9) throw new IllegalArgumentException("NinePatch needs nine TextureRegions"); + + public NinePatch (TextureRegion... patches) { + if (patches.length != 9) throw new IllegalArgumentException("NinePatch needs nine TextureRegions"); this.patches = patches; checkValidity(); } - - private void checkValidity() { - if(patches[BOTTOM_LEFT].getRegionWidth() != patches[TOP_LEFT].getRegionWidth() || - patches[BOTTOM_LEFT].getRegionWidth() != patches[MIDDLE_LEFT].getRegionWidth()) { + + private void checkValidity () { + if (patches[BOTTOM_LEFT].getRegionWidth() != patches[TOP_LEFT].getRegionWidth() + || patches[BOTTOM_LEFT].getRegionWidth() != patches[MIDDLE_LEFT].getRegionWidth()) { throw new GdxRuntimeException("Left side patches must have the same width"); } - - if(patches[BOTTOM_RIGHT].getRegionWidth() != patches[TOP_RIGHT].getRegionWidth() || - patches[BOTTOM_RIGHT].getRegionWidth() != patches[MIDDLE_RIGHT].getRegionWidth()) { + + if (patches[BOTTOM_RIGHT].getRegionWidth() != patches[TOP_RIGHT].getRegionWidth() + || patches[BOTTOM_RIGHT].getRegionWidth() != patches[MIDDLE_RIGHT].getRegionWidth()) { throw new GdxRuntimeException("Right side patches must have the same width"); } - - if(patches[BOTTOM_LEFT].getRegionHeight() != patches[BOTTOM_CENTER].getRegionHeight() || - patches[BOTTOM_LEFT].getRegionHeight() != patches[BOTTOM_RIGHT].getRegionHeight()) { + + if (patches[BOTTOM_LEFT].getRegionHeight() != patches[BOTTOM_CENTER].getRegionHeight() + || patches[BOTTOM_LEFT].getRegionHeight() != patches[BOTTOM_RIGHT].getRegionHeight()) { throw new GdxRuntimeException("Bottom patches must have the same height"); } - - if(patches[TOP_LEFT].getRegionHeight() != patches[TOP_CENTER].getRegionHeight() || - patches[TOP_LEFT].getRegionHeight() != patches[TOP_RIGHT].getRegionHeight()) { + + if (patches[TOP_LEFT].getRegionHeight() != patches[TOP_CENTER].getRegionHeight() + || patches[TOP_LEFT].getRegionHeight() != patches[TOP_RIGHT].getRegionHeight()) { throw new GdxRuntimeException("Top patches must have the same height"); } } - - public void draw(SpriteBatch batch, float x, float y, float width, float height) { + + public void draw (SpriteBatch batch, float x, float y, float width, float height) { float widthTopBottom = width - (patches[TOP_LEFT].getRegionWidth() + patches[TOP_RIGHT].getRegionWidth()); - float heightLeftRight = height - (patches[TOP_LEFT].getRegionHeight() + patches[BOTTOM_LEFT].getRegionHeight()); - float widthCenter = widthTopBottom; - + float heightLeftRight = height - (patches[TOP_LEFT].getRegionHeight() + patches[BOTTOM_LEFT].getRegionHeight()); + float widthCenter = widthTopBottom; + // bottom patches batch.draw(patches[BOTTOM_LEFT], x, y, patches[BOTTOM_LEFT].getRegionWidth(), patches[BOTTOM_LEFT].getRegionHeight()); - batch.draw(patches[BOTTOM_CENTER], x + patches[BOTTOM_LEFT].getRegionWidth(), y, widthCenter, patches[BOTTOM_CENTER].getRegionHeight()); - batch.draw(patches[BOTTOM_RIGHT], x + patches[BOTTOM_LEFT].getRegionWidth() + widthTopBottom, y, patches[BOTTOM_RIGHT].getRegionWidth(), patches[BOTTOM_RIGHT].getRegionHeight()); - - y += patches[BOTTOM_LEFT].getRegionHeight(); + batch.draw(patches[BOTTOM_CENTER], x + patches[BOTTOM_LEFT].getRegionWidth(), y, widthCenter, + patches[BOTTOM_CENTER].getRegionHeight()); + batch.draw(patches[BOTTOM_RIGHT], x + patches[BOTTOM_LEFT].getRegionWidth() + widthTopBottom, y, + patches[BOTTOM_RIGHT].getRegionWidth(), patches[BOTTOM_RIGHT].getRegionHeight()); + + y += patches[BOTTOM_LEFT].getRegionHeight(); // center patches batch.draw(patches[MIDDLE_LEFT], x, y, patches[MIDDLE_LEFT].getRegionWidth(), heightLeftRight); batch.draw(patches[MIDDLE_CENTER], x + patches[MIDDLE_LEFT].getRegionWidth(), y, widthCenter, heightLeftRight); - batch.draw(patches[MIDDLE_RIGHT], x + patches[MIDDLE_LEFT].getRegionWidth() + widthTopBottom, y, patches[MIDDLE_RIGHT].getRegionWidth(), heightLeftRight); - - + batch.draw(patches[MIDDLE_RIGHT], x + patches[MIDDLE_LEFT].getRegionWidth() + widthTopBottom, y, + patches[MIDDLE_RIGHT].getRegionWidth(), heightLeftRight); + // top patches y += heightLeftRight; batch.draw(patches[TOP_LEFT], x, y, patches[TOP_LEFT].getRegionWidth(), patches[TOP_LEFT].getRegionHeight()); - batch.draw(patches[TOP_CENTER], x + patches[TOP_LEFT].getRegionWidth(), y, widthCenter, patches[TOP_CENTER].getRegionHeight()); - batch.draw(patches[TOP_RIGHT], x + patches[TOP_LEFT].getRegionWidth() + widthTopBottom, y, patches[TOP_RIGHT].getRegionWidth(), patches[TOP_RIGHT].getRegionHeight()); + batch.draw(patches[TOP_CENTER], x + patches[TOP_LEFT].getRegionWidth(), y, widthCenter, + patches[TOP_CENTER].getRegionHeight()); + batch.draw(patches[TOP_RIGHT], x + patches[TOP_LEFT].getRegionWidth() + widthTopBottom, y, + patches[TOP_RIGHT].getRegionWidth(), patches[TOP_RIGHT].getRegionHeight()); } - - public float getLeftWidth() { + + public float getLeftWidth () { return patches[TOP_LEFT].getRegionWidth(); } - - public float getRightWidth() { + + public float getRightWidth () { return patches[TOP_RIGHT].getRegionWidth(); } - - public float getTopHeight() { + + public float getTopHeight () { return patches[TOP_RIGHT].getRegionHeight(); } - - public float getBottomHeight() { + + public float getBottomHeight () { return patches[BOTTOM_RIGHT].getRegionHeight(); } - public float getTotalHeight() { + public float getTotalHeight () { return getTopHeight() + getBottomHeight() + patches[MIDDLE_LEFT].getRegionHeight(); } - public float getTotalWidth() { + public float getTotalWidth () { return getLeftWidth() + getRightWidth() + patches[MIDDLE_CENTER].getRegionWidth(); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEffect.java b/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEffect.java index 9d85a12c6ca..7494ca2e75b 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEffect.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEffect.java @@ -52,12 +52,12 @@ public void update (float delta) { for (int i = 0, n = emitters.size; i < n; i++) emitters.get(i).update(delta); } - + public void draw (SpriteBatch spriteBatch) { for (int i = 0, n = emitters.size; i < n; i++) emitters.get(i).draw(spriteBatch); } - + public void draw (SpriteBatch spriteBatch, float delta) { for (int i = 0, n = emitters.size; i < n; i++) emitters.get(i).draw(spriteBatch, delta); @@ -100,9 +100,7 @@ public Array getEmitters () { return emitters; } - /** - * Returns the emitter with the specified name, or null. - */ + /** Returns the emitter with the specified name, or null. */ public ParticleEmitter findEmitter (String name) { for (int i = 0, n = emitters.size; i < n; i++) { ParticleEmitter emitter = emitters.get(i); @@ -195,9 +193,7 @@ protected Texture loadTexture (FileHandle file) { return new Texture(file, false); } - /** - * Disposes the texture for each sprite for each ParticleEmitter. - */ + /** Disposes the texture for each sprite for each ParticleEmitter. */ public void dispose () { for (int i = 0, n = emitters.size; i < n; i++) { ParticleEmitter emitter = emitters.get(i); diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java b/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java index b9ff9b03c3d..9e8f8be72db 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleEmitter.java @@ -233,10 +233,8 @@ public void draw (SpriteBatch spriteBatch) { if (additive) spriteBatch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); } - /** - * Updates and draws the particles. This is slightly more efficient than calling {@link #update(float)} and - * {@link #draw(SpriteBatch)} separately. - */ + /** Updates and draws the particles. This is slightly more efficient than calling {@link #update(float)} and + * {@link #draw(SpriteBatch)} separately. */ public void draw (SpriteBatch spriteBatch, float delta) { accumulator += Math.min(delta * 1000, 250); if (accumulator < 1) { @@ -575,10 +573,8 @@ public void setSprite (Sprite sprite) { } } - /** - * Ignores the {@link #setContinuous(boolean) continuous} setting until the emitter is started again. This allows the emitter - * to stop smoothly. - */ + /** Ignores the {@link #setContinuous(boolean) continuous} setting until the emitter is started again. This allows the emitter + * to stop smoothly. */ public void allowCompletion () { allowCompletion = true; durationTimer = duration; diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/Sprite.java b/gdx/src/com/badlogic/gdx/graphics/g2d/Sprite.java index a02f3b6f974..fd7b6430057 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/Sprite.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/Sprite.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.graphics.Color; @@ -21,16 +22,14 @@ import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.NumberUtils; -/** - * Holds the geometry, color, and texture information for drawing 2D sprites using {@link SpriteBatch}. A Sprite has a position +/** Holds the geometry, color, and texture information for drawing 2D sprites using {@link SpriteBatch}. A Sprite has a position * and a size given as width and height. The position is relative to the origin of the coordinate system specified via * {@link SpriteBatch#begin()} and the respective matrices. A Sprite is always rectangular and its position (x, y) are located in - * the bottom left corner of that rectangle. A Sprite also has an origin around which rotations and scaling are performed (that is, - * the origin is not modified by rotation and scaling). The - * origin is given relative to the bottom left corner of the Sprite, its position. + * the bottom left corner of that rectangle. A Sprite also has an origin around which rotations and scaling are performed (that + * is, the origin is not modified by rotation and scaling). The origin is given relative to the bottom left corner of the Sprite, + * its position. * @author mzechner - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class Sprite extends TextureRegion { static final int VERTEX_SIZE = 2 + 1 + 2; static final int SPRITE_SIZE = 4 * VERTEX_SIZE; @@ -45,35 +44,27 @@ public class Sprite extends TextureRegion { private boolean dirty = true; private Rectangle bounds = new Rectangle(); - /** - * Creates an uninitialized sprite. The sprite will need a texture, texture region, bounds, and color set before it can be - * drawn. - */ + /** Creates an uninitialized sprite. The sprite will need a texture, texture region, bounds, and color set before it can be + * drawn. */ public Sprite () { setColor(1, 1, 1, 1); } - /** - * Creates a sprite with width, height, and texture region equal to the size of the texture. - */ + /** Creates a sprite with width, height, and texture region equal to the size of the texture. */ public Sprite (Texture texture) { this(texture, 0, 0, texture.getWidth(), texture.getHeight()); } - /** - * Creates a sprite with width, height, and texture region equal to the specified size. The texture region's upper left corner + /** Creates a sprite with width, height, and texture region equal to the specified size. The texture region's upper left corner * will be 0,0. * @param srcWidth The width of the texture region. May be negative to flip the sprite when drawn. - * @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn. - */ + * @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn. */ public Sprite (Texture texture, int srcWidth, int srcHeight) { this(texture, 0, 0, srcWidth, srcHeight); } - /** - * Creates a sprite with width, height, and texture region equal to the specified size. * @param srcWidth The width of the + /** Creates a sprite with width, height, and texture region equal to the specified size. * @param srcWidth The width of the * texture region. May be negative to flip the sprite when drawn. - * @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn. - */ + * @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn. */ public Sprite (Texture texture, int srcX, int srcY, int srcWidth, int srcHeight) { if (texture == null) throw new IllegalArgumentException("texture cannot be null."); this.texture = texture; @@ -91,12 +82,10 @@ public Sprite (TextureRegion region) { setOrigin(width / 2, height / 2); } - /** - * Creates a sprite with width, height, and texture region equal to the specified size, relative to specified sprite's texture + /** Creates a sprite with width, height, and texture region equal to the specified size, relative to specified sprite's texture * region. * @param srcWidth The width of the texture region. May be negative to flip the sprite when drawn. - * @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn. - */ + * @param srcHeight The height of the texture region. May be negative to flip the sprite when drawn. */ public Sprite (TextureRegion region, int srcX, int srcY, int srcWidth, int srcHeight) { setRegion(region, srcX, srcY, srcWidth, srcHeight); setColor(1, 1, 1, 1); @@ -104,9 +93,7 @@ public Sprite (TextureRegion region, int srcX, int srcY, int srcWidth, int srcHe setOrigin(width / 2, height / 2); } - /** - * Creates a sprite that is a copy in every way of the specified sprite. - */ + /** Creates a sprite that is a copy in every way of the specified sprite. */ public Sprite (Sprite sprite) { set(sprite); } @@ -127,10 +114,8 @@ public void set (Sprite sprite) { dirty = sprite.dirty; } - /** - * Sets the position and size of the sprite when drawn, before scaling and rotation are applied. If origin, rotation, or scale - * are changed, it is slightly more efficient to set the bounds after those operations. - */ + /** Sets the position and size of the sprite when drawn, before scaling and rotation are applied. If origin, rotation, or scale + * are changed, it is slightly more efficient to set the bounds after those operations. */ public void setBounds (float x, float y, float width, float height) { this.x = x; this.y = y; @@ -157,11 +142,9 @@ public void setBounds (float x, float y, float width, float height) { if (rotation != 0 || scaleX != 1 || scaleY != 1) dirty = true; } - /** - * Sets the size of the sprite when drawn, before scaling and rotation are applied. If origin, rotation, or scale are changed, + /** Sets the size of the sprite when drawn, before scaling and rotation are applied. If origin, rotation, or scale are changed, * it is slightly more efficient to set the size after those operations. If both position and size are to be changed, it is - * better to use {@link #setBounds(float, float, float, float)}. - */ + * better to use {@link #setBounds(float, float, float, float)}. */ public void setSize (float width, float height) { this.width = width; this.height = height; @@ -186,19 +169,15 @@ public void setSize (float width, float height) { if (rotation != 0 || scaleX != 1 || scaleY != 1) dirty = true; } - /** - * Sets the position where the sprite will be drawn. If origin, rotation, or scale are changed, it is slightly more efficient + /** Sets the position where the sprite will be drawn. If origin, rotation, or scale are changed, it is slightly more efficient * to set the position after those operations. If both position and size are to be changed, it is better to use - * {@link #setBounds(float, float, float, float)}. - */ + * {@link #setBounds(float, float, float, float)}. */ public void setPosition (float x, float y) { translate(x - this.x, y - this.y); } - /** - * Sets the position relative to the current position where the sprite will be drawn. If origin, rotation, or scale are - * changed, it is slightly more efficient to translate after those operations. - */ + /** Sets the position relative to the current position where the sprite will be drawn. If origin, rotation, or scale are + * changed, it is slightly more efficient to translate after those operations. */ public void translate (float xAmount, float yAmount) { x += xAmount; y += yAmount; @@ -238,9 +217,7 @@ public void setColor (float r, float g, float b, float a) { vertices[C4] = color; } - /** - * Sets the origin in relation to the sprite's position for scaling and rotation. - */ + /** Sets the origin in relation to the sprite's position for scaling and rotation. */ public void setOrigin (float originX, float originY) { this.originX = originX; this.originY = originY; @@ -252,18 +229,14 @@ public void setRotation (float degrees) { dirty = true; } - /** - * Sets the sprite's rotation relative to the current rotation. - */ + /** Sets the sprite's rotation relative to the current rotation. */ public void rotate (float degrees) { rotation += degrees; dirty = true; } - /** - * Rotates this sprite 90 degrees in-place by rotating the texture coordinates. This rotation is unaffected by - * {@link #setRotation(float)} and {@link #rotate(float)}. - */ + /** Rotates this sprite 90 degrees in-place by rotating the texture coordinates. This rotation is unaffected by + * {@link #setRotation(float)} and {@link #rotate(float)}. */ public void rotate90 (boolean clockwise) { float[] vertices = this.vertices; @@ -306,18 +279,14 @@ public void setScale (float scaleX, float scaleY) { dirty = true; } - /** - * Sets the sprite's scale relative to the current scale. - */ + /** Sets the sprite's scale relative to the current scale. */ public void scale (float amount) { this.scaleX += amount; this.scaleY += amount; dirty = true; } - /** - * Returns the packed vertices, colors, and texture coordinates for this sprite. - */ + /** Returns the packed vertices, colors, and texture coordinates for this sprite. */ public float[] getVertices () { if (dirty) { dirty = false; @@ -385,51 +354,48 @@ public float[] getVertices () { } return vertices; } - - /** - * Returns the bounding axis aligned {@link Rectangle} that - * bounds this sprite. The rectangles x and y coordinates - * describe its bottom left corner. + + /** Returns the bounding axis aligned {@link Rectangle} that bounds this sprite. The rectangles x and y coordinates describe its + * bottom left corner. * - * @return the bounding Rectangle - */ - public Rectangle getBoundingRectangle() { + * @return the bounding Rectangle */ + public Rectangle getBoundingRectangle () { final float[] vertices = getVertices(); - + float minx = vertices[X1]; float miny = vertices[Y1]; float maxx = vertices[X1]; float maxy = vertices[Y1]; - - minx = minx > vertices[X2]? vertices[X2]: minx; - minx = minx > vertices[X3]? vertices[X3]: minx; - minx = minx > vertices[X4]? vertices[X4]: minx; - - maxx = maxx < vertices[X2]? vertices[X2]: maxx; - maxx = maxx < vertices[X3]? vertices[X3]: maxx; - maxx = maxx < vertices[X4]? vertices[X4]: maxx; - - miny = miny > vertices[Y2]? vertices[Y2]: miny; - miny = miny > vertices[Y3]? vertices[Y3]: miny; - miny = miny > vertices[Y4]? vertices[Y4]: miny; - - maxy = maxy < vertices[Y2]? vertices[Y2]: maxy; - maxy = maxy < vertices[Y3]? vertices[Y3]: maxy; - maxy = maxy < vertices[Y4]? vertices[Y4]: maxy; - + + minx = minx > vertices[X2] ? vertices[X2] : minx; + minx = minx > vertices[X3] ? vertices[X3] : minx; + minx = minx > vertices[X4] ? vertices[X4] : minx; + + maxx = maxx < vertices[X2] ? vertices[X2] : maxx; + maxx = maxx < vertices[X3] ? vertices[X3] : maxx; + maxx = maxx < vertices[X4] ? vertices[X4] : maxx; + + miny = miny > vertices[Y2] ? vertices[Y2] : miny; + miny = miny > vertices[Y3] ? vertices[Y3] : miny; + miny = miny > vertices[Y4] ? vertices[Y4] : miny; + + maxy = maxy < vertices[Y2] ? vertices[Y2] : maxy; + maxy = maxy < vertices[Y3] ? vertices[Y3] : maxy; + maxy = maxy < vertices[Y4] ? vertices[Y4] : maxy; + bounds.x = minx; bounds.y = miny; bounds.width = maxx - minx; bounds.height = maxy - miny; - + return bounds; } public void draw (SpriteBatch spriteBatch) { spriteBatch.draw(texture, getVertices(), 0, SPRITE_SIZE); } - - public void draw(SpriteBatch spriteBatch, float alphaModulation) { + + public void draw (SpriteBatch spriteBatch, float alphaModulation) { Color color = getColor(); float oldAlpha = color.a; color.a *= alphaModulation; @@ -475,10 +441,8 @@ public float getScaleY () { return scaleY; } - /** - * Returns the color of this sprite. Changing the returned color will have no affect, {@link #setColor(Color)} or - * {@link #setColor(float, float, float, float)} must be used. - */ + /** Returns the color of this sprite. Changing the returned color will have no affect, {@link #setColor(Color)} or + * {@link #setColor(float, float, float, float)} must be used. */ public Color getColor () { float floatBits = vertices[C1]; int intBits = NumberUtils.floatToRawIntBits(vertices[C1]); diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteBatch.java b/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteBatch.java index 210039c2bfc..8f35c08ebe6 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteBatch.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteBatch.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.Gdx; @@ -33,8 +34,7 @@ import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.NumberUtils; -/** - *

        +/**

        * 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. *

        @@ -70,9 +70,7 @@ * A SpriteBatch has to be disposed if it is no longer used. *

        * - * @author mzechner - * - */ + * @author mzechner */ public class SpriteBatch implements Disposable { private Mesh mesh; private Mesh[] buffers; @@ -107,17 +105,14 @@ public class SpriteBatch implements Disposable { public int maxSpritesInBatch = 0; private ShaderProgram customShader = null; - /** - * Constructs a new SpriteBatch. Sets the projection matrix to an orthographic projection with y-axis point upwards, x-axis + /** 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 bottom left corner of the screen. The projection will be pixel perfect with - * respect to the screen resolution. - */ + * respect to the screen resolution. */ 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 bottom left corner of the screen. The projection will be pixel perfect with * respect to the screen resolution. @@ -127,13 +122,12 @@ public SpriteBatch () { * The size parameter specifies the maximum size of a single batch in number of sprites *

        * - * @param size the batch size in number of sprites - */ + * @param size the batch size in number of sprites */ public SpriteBatch (int size) { this.buffers = new Mesh[1]; this.buffers[0] = new Mesh(VertexDataType.VertexArray, false, size * 4, size * 6, new VertexAttribute(Usage.Position, 2, - ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), new VertexAttribute(Usage.TextureCoordinates, 2, - ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); + ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), + new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); @@ -156,8 +150,7 @@ public SpriteBatch (int size) { if (Gdx.graphics.isGL20Available()) createShader(); } - /** - *

        + /**

        * 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 bottom left corner of the screen. The projection will be pixel perfect with * respect to the screen resolution. @@ -168,14 +161,14 @@ public SpriteBatch (int size) { *

        * * @param size the batch size in number of sprites - * @param buffers the number of buffers to use. only makes sense with VBOs. This is an expert function. - */ + * @param buffers the number of buffers to use. only makes sense with VBOs. This is an expert function. */ public SpriteBatch (int size, int buffers) { this.buffers = new Mesh[buffers]; for (int i = 0; i < buffers; i++) { - this.buffers[i] = new Mesh(false, size * 4, size * 6, new VertexAttribute(Usage.Position, 2, ShaderProgram.POSITION_ATTRIBUTE), - new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); + this.buffers[i] = new Mesh(false, size * 4, size * 6, new VertexAttribute(Usage.Position, 2, + ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), + new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); } projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); @@ -230,18 +223,16 @@ private void createShader () { if (shader.isCompiled() == false) throw new IllegalArgumentException("couldn't compile shader: " + shader.getLog()); } - /** - * Sets up the SpriteBatch for drawing. This will disable depth buffer writting. It enables - * blending and texturing. If you have more texture units enabled than the first one you have to disable them before - * calling this. Uses a screen coordinate system by default where everything is given in pixels. You can specify your own - * projection and modelview matrices via {@link #setProjectionMatrix(Matrix4)} and {@link #setTransformMatrix(Matrix4)}. - */ + /** Sets up the SpriteBatch for drawing. This will disable depth buffer writting. It enables blending and texturing. If you have + * more texture units enabled than the first one you have to disable them before calling this. Uses a screen coordinate system + * by default where everything is given in pixels. You can specify your own projection and modelview matrices via + * {@link #setProjectionMatrix(Matrix4)} and {@link #setTransformMatrix(Matrix4)}. */ public void begin () { if (drawing) throw new IllegalStateException("you have to call SpriteBatch.end() first"); renderCalls = 0; if (Gdx.graphics.isGL20Available() == false) { - GL10 gl = Gdx.gl10; + GL10 gl = Gdx.gl10; gl.glDepthMask(false); gl.glEnable(GL10.GL_TEXTURE_2D); @@ -253,11 +244,11 @@ public void begin () { } else { combinedMatrix.set(projectionMatrix).mul(transformMatrix); - GL20 gl = Gdx.gl20; + GL20 gl = Gdx.gl20; gl.glDepthMask(false); gl.glEnable(GL20.GL_TEXTURE_2D); - if(customShader != null) { + if (customShader != null) { customShader.begin(); customShader.setUniformMatrix("u_proj", projectionMatrix); customShader.setUniformMatrix("u_trans", transformMatrix); @@ -273,58 +264,48 @@ public void begin () { idx = 0; lastTexture = null; drawing = true; - } + } - /** - * Finishes off rendering. Enables depth writes, disables blending and texturing. Must always be called after a call to {@link #begin()} - */ + /** Finishes off rendering. Enables depth writes, disables blending and texturing. Must always be called after a call to + * {@link #begin()} */ public void end () { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before end."); if (idx > 0) renderMesh(); lastTexture = null; idx = 0; drawing = false; - + GLCommon gl = Gdx.gl; gl.glDepthMask(true); - if(isBlendingEnabled()) - gl.glDisable(GL10.GL_BLEND); + if (isBlendingEnabled()) gl.glDisable(GL10.GL_BLEND); gl.glDisable(GL10.GL_TEXTURE_2D); if (Gdx.graphics.isGL20Available()) { - if(customShader != null) + if (customShader != null) customShader.end(); else - shader.end(); + shader.end(); } } - /** - * Sets the color used to tint images when they are added to the SpriteBatch. Default is {@link Color#WHITE}. - */ + /** Sets the color used to tint images when they are added to the SpriteBatch. Default is {@link Color#WHITE}. */ public void setColor (Color tint) { color = tint.toFloatBits(); } - /** - * @see #setColor(Color) - */ + /** @see #setColor(Color) */ public void setColor (float r, float g, float b, float a) { int intBits = (int)(255 * a) << 24 | (int)(255 * b) << 16 | (int)(255 * g) << 8 | (int)(255 * r); color = NumberUtils.intBitsToFloat(intBits & 0xfeffffff); } - /** - * @see #setColor(Color) - * @see Color#toFloatBits() - */ + /** @see #setColor(Color) + * @see Color#toFloatBits() */ public void setColor (float color) { this.color = color; } - /** - * @return the rendering color of this SpriteBatch. Manipulating the returned instance has no effect. - */ + /** @return the rendering color of this SpriteBatch. Manipulating the returned instance has no effect. */ public Color getColor () { int intBits = NumberUtils.floatToRawIntBits(color); Color color = this.tempColor; @@ -335,8 +316,7 @@ public Color getColor () { return color; } - /** - * Draws a rectangle with the bottom left corner at x,y having the given width and height in pixels. The rectangle is offset by + /** Draws a rectangle with the bottom 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 @@ -357,8 +337,7 @@ public Color getColor () { * @param srcWidth the source with in texels * @param srcHeight the source height in texels * @param flipX whether to flip the sprite horizontally - * @param flipY whether to flip the sprite vertically - */ + * @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, boolean flipX, boolean flipY) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -486,8 +465,7 @@ public void draw (Texture texture, float x, float y, float originX, float origin vertices[idx++] = v; } - /** - * Draws a rectangle with the bottom left corner at x,y having the given width and height in pixels. The portion of the + /** Draws a rectangle with the bottom 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. FlipX * and flipY specify whether the texture portion should be fliped horizontally or vertically. * @@ -501,8 +479,7 @@ public void draw (Texture texture, float x, float y, float originX, float origin * @param srcWidth the source with in texels * @param srcHeight the source height in texels * @param flipX whether to flip the sprite horizontally - * @param flipY whether to flip the sprite vertically - */ + * @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, boolean flipX, boolean flipY) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -558,8 +535,7 @@ public void draw (Texture texture, float x, float y, float width, float height, vertices[idx++] = v; } - /** - * Draws a rectangle with the bottom left corner at x,y having the given width and height in pixels. The portion of the + /** Draws a rectangle with the bottom 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. * * @param texture the Texture @@ -568,8 +544,7 @@ public void draw (Texture texture, float x, float y, float width, float height, * @param srcX the x-coordinate in texel space * @param srcY the y-coordinate in texel space * @param srcWidth the source with in texels - * @param srcHeight the source height in texels - */ + * @param srcHeight the source height in texels */ public void draw (Texture texture, float x, float y, int srcX, int srcY, int srcWidth, int srcHeight) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -612,8 +587,7 @@ public void draw (Texture texture, float x, float y, int srcX, int srcY, int src vertices[idx++] = v; } - /** - * Draws a rectangle with the bottom left corner at x,y having the given width and height in pixels. The portion of the + /** Draws a rectangle with the bottom left corner at x,y having the given width and height in pixels. The portion of the * {@link Texture} given by u, v and u2, v2 are used. These coordinates and sizes are given in texture size percentage. The * rectangle will have the given tint {@link Color}. * @@ -621,8 +595,7 @@ public void draw (Texture texture, float x, float y, int srcX, int srcY, int src * @param x the x-coordinate in screen space * @param y the y-coordinate in screen space * @param width the width in pixels - * @param height the height in pixels - */ + * @param height the height in pixels */ public void draw (Texture texture, float x, float y, float width, float height, float u, float v, float u2, float v2) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -661,12 +634,10 @@ public void draw (Texture texture, float x, float y, float width, float height, vertices[idx++] = v; } - /** - * Draws a rectangle with the bottom left corner at x,y having the width and height of the texture. + /** Draws a rectangle with the bottom left corner at x,y having the width and height of the texture. * @param texture the Texture * @param x the x-coordinate in screen space - * @param y the y-coordinate in screen space - */ + * @param y the y-coordinate in screen space */ public void draw (Texture texture, float x, float y) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -704,13 +675,11 @@ public void draw (Texture texture, float x, float y) { vertices[idx++] = 1; vertices[idx++] = 1; } - - /** - * Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. - */ + + /** Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. */ public void draw (Texture texture, float x, float y, float width, float height) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); - + if (texture != lastTexture) { renderMesh(); lastTexture = texture; @@ -751,10 +720,8 @@ public void draw (Texture texture, float x, float y, float width, float height) vertices[idx++] = v; } - /** - * Draws a rectangle using the given vertices. There must be 4 vertices, each made up of 5 elements in this order: x, y, color, - * u, v. - */ + /** Draws a rectangle using the given vertices. There must be 4 vertices, each made up of 5 elements in this order: x, y, color, + * u, v. */ public void draw (Texture texture, float[] spriteVertices, int offset, int length) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -769,16 +736,12 @@ public void draw (Texture texture, float[] spriteVertices, int offset, int lengt idx += length; } - /** - * Draws a rectangle with the bottom left corner at x,y having the width and height of the region. - */ + /** Draws a rectangle with the bottom left corner at x,y having the width and height of the region. */ public void draw (TextureRegion region, float x, float y) { draw(region, x, y, Math.abs(region.getRegionWidth()), Math.abs(region.getRegionHeight())); } - /** - * Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. - */ + /** Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. */ public void draw (TextureRegion region, float x, float y, float width, float height) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -823,12 +786,10 @@ public void draw (TextureRegion region, float x, float y, float width, float hei vertices[idx++] = v; } - /** - * Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. The + /** Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. 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. - */ + * originX, originY. */ public void draw (TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -946,12 +907,10 @@ public void draw (TextureRegion region, float x, float y, float originX, float o vertices[idx++] = v; } - /** - * Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. The + /** Draws a rectangle with the bottom left corner at x,y and stretching the region to cover the given width and height. 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. - */ + * originX, originY. */ public void draw (TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, boolean clockwise) { if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw."); @@ -1085,9 +1044,7 @@ public void draw (TextureRegion region, float x, float y, float originX, float o vertices[idx++] = v4; } - /** - * Causes any pending sprites to be rendered, without ending the SpriteBatch. - */ + /** Causes any pending sprites to be rendered, without ending the SpriteBatch. */ public void flush () { renderMesh(); } @@ -1111,7 +1068,7 @@ private void renderMesh () { gl20.glBlendFunc(blendSrcFunc, blendDstFunc); } - if(customShader != null) + if (customShader != null) mesh.render(customShader, GL10.GL_TRIANGLES, 0, spritesInBatch * 6); else mesh.render(shader, GL10.GL_TRIANGLES, 0, spritesInBatch * 6); @@ -1132,101 +1089,83 @@ private void renderMesh () { mesh = buffers[currBufferIdx]; } - /** - * Disables blending for drawing sprites. Does not disable blending for text rendering - */ + /** Disables blending for drawing sprites. Does not disable blending for text rendering */ public void disableBlending () { renderMesh(); blendingDisabled = true; } - /** - * Enables blending for sprites - */ + /** Enables blending for sprites */ public void enableBlending () { renderMesh(); blendingDisabled = false; } - /** - * Sets the blending function to be used when rendering sprites. + /** Sets the blending function to be used when rendering sprites. * * @param srcFunc the source function, e.g. GL11.GL_SRC_ALPHA - * @param dstFunc the destination function, e.g. GL11.GL_ONE_MINUS_SRC_ALPHA - */ + * @param dstFunc the destination function, e.g. GL11.GL_ONE_MINUS_SRC_ALPHA */ public void setBlendFunction (int srcFunc, int dstFunc) { renderMesh(); blendSrcFunc = srcFunc; blendDstFunc = dstFunc; } - /** - * Disposes all resources associated with this SpriteBatch - */ + /** Disposes all resources associated with this SpriteBatch */ public void dispose () { for (int i = 0; i < buffers.length; i++) buffers[i].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 - */ + * @return the currently set projection matrix */ 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 - */ + * @return the currently set transform matrix */ 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 - */ + * @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); } - /** - * 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 transform the transform matrix - */ + * @param transform the transform matrix */ public void setTransformMatrix (Matrix4 transform) { if (drawing) throw new GdxRuntimeException("Can't set the matrix within begin()/end() block"); transformMatrix.set(transform); } - - /** - * Sets the shader to be used in a GLES 2.0 environment. Vertex position attribute is called "a_position", the texture coordinates attribute is called called "a_texCoords0", the - * color attribute is called "a_color". See {@link ShaderProgram#POSITION_ATTRIBUTE}, {@link ShaderProgram#COLOR_ATTRIBUTE} and {@link ShaderProgram#TEXCOORD_ATTRIBUTE} which gets - * "0" appened to indicate the use of the first texture unit. - * The projection matrix is uploaded via a mat4 uniform called "u_proj", the transform matrix is uploaded via a uniform called "u_trans", the combined - * transform and projection matrx is is uploaded via a mat4 uniform called "u_projTrans". The texture sampler is passed via a uniform called "u_texture". + + /** Sets the shader to be used in a GLES 2.0 environment. Vertex position attribute is called "a_position", the texture + * coordinates attribute is called called "a_texCoords0", the color attribute is called "a_color". See + * {@link ShaderProgram#POSITION_ATTRIBUTE}, {@link ShaderProgram#COLOR_ATTRIBUTE} and {@link ShaderProgram#TEXCOORD_ATTRIBUTE} + * which gets "0" appened to indicate the use of the first texture unit. The projection matrix is uploaded via a mat4 uniform + * called "u_proj", the transform matrix is uploaded via a uniform called "u_trans", the combined transform and projection + * matrx is is uploaded via a mat4 uniform called "u_projTrans". The texture sampler is passed via a uniform called + * "u_texture". * * Call this method with a null argument to use the default shader. * - * @param shader the {@link ShaderProgram} or null to use the default shader. - */ - public void setShader(ShaderProgram shader) { - customShader = shader; + * @param shader the {@link ShaderProgram} or null to use the default shader. */ + public void setShader (ShaderProgram shader) { + customShader = shader; } - /** - * @return whether blending for sprites is enabled - */ + /** @return whether blending for sprites is enabled */ public boolean isBlendingEnabled () { return !blendingDisabled; } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteCache.java b/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteCache.java index 6f67ebdaca1..f222de84478 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteCache.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteCache.java @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.graphics.g2d; -import static com.badlogic.gdx.graphics.g2d.Sprite.SPRITE_SIZE; -import static com.badlogic.gdx.graphics.g2d.Sprite.VERTEX_SIZE; +package com.badlogic.gdx.graphics.g2d; import java.nio.FloatBuffer; import java.util.ArrayList; @@ -37,8 +35,9 @@ import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.NumberUtils; -/** - * Draws 2D images, optimized for geometry that does not change. Sprites and/or textures are cached and given an ID, which can +import static com.badlogic.gdx.graphics.g2d.Sprite.*; + +/** Draws 2D images, optimized for geometry that does not change. Sprites and/or textures are cached and given an ID, which can * later be used for drawing. The size, color, and texture region for each cached image cannot be modified. This information is * stored in video memory and does not have to be sent to the GPU each time it is drawn.
        *
        @@ -65,8 +64,7 @@ * SpriteCache works with OpenGL ES 1.x and 2.0. For 2.0, it uses its own custom shader to draw.
        *
        * SpriteCache must be disposed once it is no longer needed. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class SpriteCache implements Disposable { static private final float[] tempVertices = new float[VERTEX_SIZE * 6]; @@ -87,34 +85,28 @@ public class SpriteCache implements Disposable { private Color tempColor = new Color(1, 1, 1, 1); private ShaderProgram customShader = null; - - /** - * Creates a cache that uses indexed geometry and can contain up to 1000 images. - */ + + /** Creates a cache that uses indexed geometry and can contain up to 1000 images. */ public SpriteCache () { this(1000, false); } - /** - * Creates a cache with the specified size, using a default shader if OpenGL ES 2.0 is being used. + /** Creates a cache with the specified size, using a default shader if OpenGL ES 2.0 is being used. * @param size The maximum number of images this cache can hold. The memory required to hold the images is allocated up front. - * @param useIndices If true, indexed geometry will be used. - */ + * @param useIndices If true, indexed geometry will be used. */ public SpriteCache (int size, boolean useIndices) { this(size, createDefaultShader(), useIndices); } - /** - * Creates a cache with the specified size and OpenGL ES 2.0 shader. + /** Creates a cache with the specified size and OpenGL ES 2.0 shader. * @param size The maximum number of images this cache can hold. The memory required to hold the images is allocated up front. - * @param useIndices If true, indexed geometry will be used. - */ + * @param useIndices If true, indexed geometry will be used. */ public SpriteCache (int size, ShaderProgram shader, boolean useIndices) { this.shader = shader; mesh = new Mesh(true, size * (useIndices ? 4 : 6), useIndices ? size * 6 : 0, new VertexAttribute(Usage.Position, 2, - ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), new VertexAttribute(Usage.TextureCoordinates, 2, - ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); + ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), + new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); mesh.setAutoBind(false); if (useIndices) { @@ -135,25 +127,19 @@ public SpriteCache (int size, ShaderProgram shader, boolean useIndices) { projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } - /** - * Sets the color used to tint images when they are added to the SpriteCache. Default is {@link Color#WHITE}. - */ + /** Sets the color used to tint images when they are added to the SpriteCache. Default is {@link Color#WHITE}. */ public void setColor (Color tint) { color = tint.toFloatBits(); } - /** - * @see #setColor(Color) - */ + /** @see #setColor(Color) */ public void setColor (float r, float g, float b, float a) { int intBits = (int)(255 * a) << 24 | (int)(255 * b) << 16 | (int)(255 * g) << 8 | (int)(255 * r); color = NumberUtils.intBitsToFloat(intBits & 0xfeffffff); } - /** - * @see #setColor(Color) - * @see Color#toFloatBits() - */ + /** @see #setColor(Color) + * @see Color#toFloatBits() */ public void setColor (float color) { this.color = color; } @@ -168,9 +154,7 @@ public Color getColor () { return color; } - /** - * Starts the definition of a new cache, allowing the add and {@link #endCache()} methods to be called. - */ + /** Starts the definition of a new cache, allowing the add and {@link #endCache()} methods to be called. */ public void beginCache () { if (currentCache != null) throw new IllegalStateException("endCache must be called before begin."); int verticesPerImage = mesh.getNumIndices() > 0 ? 4 : 6; @@ -179,11 +163,9 @@ public void beginCache () { mesh.getVerticesBuffer().compact(); } - /** - * Starts the redefinition of an existing cache, allowing the add and {@link #endCache()} methods to be called. If this is not + /** Starts the redefinition of an existing cache, allowing the add and {@link #endCache()} methods to be called. If this is not * the last cache created, it cannot have more entries added to it than when it was first created. To do that, use - * {@link #clear()} and then {@link #begin()}. - */ + * {@link #clear()} and then {@link #begin()}. */ public void beginCache (int cacheID) { if (currentCache != null) throw new IllegalStateException("endCache must be called before begin."); if (cacheID == caches.size() - 1) { @@ -195,9 +177,7 @@ public void beginCache (int cacheID) { mesh.getVerticesBuffer().position(currentCache.offset); } - /** - * Ends the definition of a cache, returning the cache ID to be used with {@link #draw(int)}. - */ + /** Ends the definition of a cache, returning the cache ID to be used with {@link #draw(int)}. */ public int endCache () { if (currentCache == null) throw new IllegalStateException("beginCache must be called before endCache."); @@ -241,19 +221,15 @@ public int endCache () { return cache.id; } - /** - * Invalidates all cache IDs and resets the SpriteCache so new caches can be added. - */ + /** Invalidates all cache IDs and resets the SpriteCache so new caches can be added. */ public void clear () { caches.clear(); mesh.getVerticesBuffer().clear().flip(); } - /** - * Adds the specified vertices to the cache. Each vertex should have 5 elements, one for each of the attributes: x, y, color, + /** Adds the specified vertices to the cache. Each vertex should have 5 elements, one for each of the attributes: x, y, color, * u, and v. If indexed geometry is used, each image should be specified as 4 vertices, otherwise each image should be - * specified as 6 vertices. - */ + * specified as 6 vertices. */ public void add (Texture texture, float[] vertices, int offset, int length) { if (currentCache == null) throw new IllegalStateException("beginCache must be called before add."); @@ -269,9 +245,7 @@ public void add (Texture texture, float[] vertices, int offset, int length) { mesh.getVerticesBuffer().put(vertices, offset, length); } - /** - * Adds the specified texture to the cache. - */ + /** Adds the specified texture to the cache. */ public void add (Texture texture, float x, float y) { final float fx2 = x + texture.getWidth(); final float fy2 = y + texture.getHeight(); @@ -323,9 +297,7 @@ public void add (Texture texture, float x, float y) { } } - /** - * Adds the specified texture to the cache. - */ + /** Adds the specified texture to the cache. */ public void add (Texture texture, float x, float y, int srcWidth, int srcHeight, float u, float v, float u2, float v2, float color) { final float fx2 = x + srcWidth; @@ -378,9 +350,7 @@ public void add (Texture texture, float x, float y, int srcWidth, int srcHeight, } } - /** - * Adds the specified texture to the cache. - */ + /** Adds the specified texture to the cache. */ public void add (Texture texture, float x, float y, int srcX, int srcY, int srcWidth, int srcHeight) { float invTexWidth = 1.0f / texture.getWidth(); float invTexHeight = 1.0f / texture.getHeight(); @@ -438,9 +408,7 @@ public void add (Texture texture, float x, float y, int srcX, int srcY, int srcW } } - /** - * Adds the specified texture to the cache. - */ + /** Adds the specified texture to the cache. */ public void add (Texture texture, float x, float y, float width, float height, int srcX, int srcY, int srcWidth, int srcHeight, boolean flipX, boolean flipY) { @@ -511,9 +479,7 @@ public void add (Texture texture, float x, float y, float width, float height, i } } - /** - * Adds the specified texture to the cache. - */ + /** Adds the specified texture to the cache. */ public void add (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, boolean flipX, boolean flipY) { @@ -657,16 +623,12 @@ public void add (Texture texture, float x, float y, float originX, float originY } } - /** - * Adds the specified region to the cache. - */ + /** Adds the specified region to the cache. */ public void add (TextureRegion region, float x, float y) { add(region, x, y, region.getRegionWidth(), region.getRegionHeight()); } - /** - * Adds the specified region to the cache. - */ + /** Adds the specified region to the cache. */ public void add (TextureRegion region, float x, float y, float width, float height) { final float fx2 = x + width; final float fy2 = y + height; @@ -722,9 +684,7 @@ public void add (TextureRegion region, float x, float y, float width, float heig } } - /** - * Adds the specified region to the cache. - */ + /** Adds the specified region to the cache. */ public void add (TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation) { @@ -854,9 +814,7 @@ public void add (TextureRegion region, float x, float y, float originX, float or } } - /** - * Adds the specified sprite to the cache. - */ + /** Adds the specified sprite to the cache. */ public void add (Sprite sprite) { if (mesh.getNumIndices() > 0) { add(sprite.getTexture(), sprite.getVertices(), 0, SPRITE_SIZE); @@ -871,9 +829,7 @@ public void add (Sprite sprite) { add(sprite.getTexture(), tempVertices, 0, 30); } - /** - * Prepares the OpenGL state for SpriteCache rendering. - */ + /** Prepares the OpenGL state for SpriteCache rendering. */ public void begin () { if (drawing) throw new IllegalStateException("end must be called before begin."); @@ -891,11 +847,11 @@ public void begin () { } else { combinedMatrix.set(projectionMatrix).mul(transformMatrix); - GL20 gl = Gdx.gl20; + GL20 gl = Gdx.gl20; gl.glDepthMask(false); gl.glEnable(GL20.GL_TEXTURE_2D); - if(customShader != null) { + if (customShader != null) { customShader.begin(); customShader.setUniformMatrix("u_proj", projectionMatrix); customShader.setUniformMatrix("u_trans", transformMatrix); @@ -905,16 +861,14 @@ public void begin () { shader.begin(); shader.setUniformMatrix("u_projectionViewMatrix", combinedMatrix); shader.setUniformi("u_texture", 0); - } + } mesh.bind(shader); } drawing = true; } - /** - * Completes rendering for this SpriteCache.f - */ + /** Completes rendering for this SpriteCache.f */ public void end () { if (!drawing) throw new IllegalStateException("begin must be called before end."); drawing = false; @@ -933,9 +887,7 @@ public void end () { } } - /** - * Draws all the images defined for the specified cache ID. - */ + /** Draws all the images defined for the specified cache ID. */ public void draw (int cacheID) { if (!drawing) throw new IllegalStateException("SpriteCache.begin must be called before draw."); @@ -947,8 +899,10 @@ public void draw (int cacheID) { for (int i = 0, n = textures.length; i < n; i++) { int count = counts[i]; textures[i].bind(); - if(customShader != null) mesh.render(customShader, GL10.GL_TRIANGLES, offset, count); - else mesh.render(shader, GL10.GL_TRIANGLES, offset, count); + if (customShader != null) + mesh.render(customShader, GL10.GL_TRIANGLES, offset, count); + else + mesh.render(shader, GL10.GL_TRIANGLES, offset, count); offset += count; } } else { @@ -961,11 +915,9 @@ public void draw (int cacheID) { } } - /** - * Draws a subset of images defined for the specified cache ID. + /** Draws a subset of images defined for the specified cache ID. * @param offset The first image to render. - * @param length The number of images from the first image (inclusive) to render. - */ + * @param length The number of images from the first image (inclusive) to render. */ public void draw (int cacheID, int offset, int length) { if (!drawing) throw new IllegalStateException("SpriteCache.begin must be called before draw."); @@ -983,8 +935,10 @@ public void draw (int cacheID, int offset, int length) { count = length; } else length -= count; - if(customShader != null) mesh.render(customShader, GL10.GL_TRIANGLES, offset, count); - else mesh.render(shader, GL10.GL_TRIANGLES, offset, count); + if (customShader != null) + mesh.render(customShader, GL10.GL_TRIANGLES, offset, count); + else + mesh.render(shader, GL10.GL_TRIANGLES, offset, count); offset += count; } } else { @@ -1002,9 +956,7 @@ public void draw (int cacheID, int offset, int length) { } } - /** - * Releases all resources held by this SpriteCache. - */ + /** Releases all resources held by this SpriteCache. */ public void dispose () { mesh.dispose(); if (shader != null) shader.dispose(); @@ -1044,44 +996,43 @@ public Cache (int id, int offset) { static ShaderProgram createDefaultShader () { if (!Gdx.graphics.isGL20Available()) return null; String vertexShader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" // - + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" // - + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" // - + "uniform mat4 u_projectionViewMatrix;\n" // - + "varying vec4 v_color;\n" // - + "varying vec2 v_texCoords;\n" // - + "\n" // - + "void main()\n" // - + "{\n" // - + " v_color = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" // - + " v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" // - + " gl_Position = u_projectionViewMatrix * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" // - + "}\n"; - String fragmentShader = "#ifdef GL_ES\n" // - + "precision mediump float;\n" // - + "#endif\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" // - + "}"; + + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" // + + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" // + + "uniform mat4 u_projectionViewMatrix;\n" // + + "varying vec4 v_color;\n" // + + "varying vec2 v_texCoords;\n" // + + "\n" // + + "void main()\n" // + + "{\n" // + + " v_color = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" // + + " v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" // + + " gl_Position = u_projectionViewMatrix * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" // + + "}\n"; + String fragmentShader = "#ifdef GL_ES\n" // + + "precision mediump float;\n" // + + "#endif\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" // + + "}"; ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShader); if (shader.isCompiled() == false) throw new IllegalArgumentException("Error compiling shader: " + shader.getLog()); return shader; } - - /** - * Sets the shader to be used in a GLES 2.0 environment. Vertex position attribute is called "a_position", the texture coordinates attribute is called called "a_texCoords", the - * color attribute is called "a_color". - * The projection matrix is uploaded via a mat4 uniform called "u_proj", the transform matrix is uploaded via a uniform called "u_trans", the combined - * transform and projection matrx is is uploaded via a mat4 uniform called "u_projTrans". The texture sampler is passed via a uniform called "u_texture". + + /** Sets the shader to be used in a GLES 2.0 environment. Vertex position attribute is called "a_position", the texture + * coordinates attribute is called called "a_texCoords", the color attribute is called "a_color". The projection matrix is + * uploaded via a mat4 uniform called "u_proj", the transform matrix is uploaded via a uniform called "u_trans", the combined + * transform and projection matrx is is uploaded via a mat4 uniform called "u_projTrans". The texture sampler is passed via a + * uniform called "u_texture". * * Call this method with a null argument to use the default shader. * - * @param shader the {@link ShaderProgram} or null to use the default shader. - */ - public void setShader(ShaderProgram shader) { - customShader = shader; + * @param shader the {@link ShaderProgram} or null to use the default shader. */ + public void setShader (ShaderProgram shader) { + customShader = shader; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java index 6cc24d0bba3..1b77963c363 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureAtlas.java @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.graphics.g2d; -import static com.badlogic.gdx.graphics.Texture.TextureWrap.ClampToEdge; -import static com.badlogic.gdx.graphics.Texture.TextureWrap.Repeat; +package com.badlogic.gdx.graphics.g2d; import java.io.BufferedReader; import java.io.IOException; @@ -34,29 +32,26 @@ 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.TextureData; import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData.Page; import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData.Region; -import com.badlogic.gdx.graphics.glutils.FileTextureData; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.ObjectMap; -/** - * Loads images from texture atlases created by TexturePacker.
        +import static com.badlogic.gdx.graphics.Texture.TextureWrap.*; + +/** Loads images from texture atlases created by TexturePacker.
        *
        * A TextureAtlas must be disposed to free up the resources consumed by the backing textures. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class TextureAtlas implements Disposable { static final String[] tuple = new String[2]; private final HashSet textures = new HashSet(4); private final ArrayList regions = new ArrayList(); - - - public static class TextureAtlasData { + + public static class TextureAtlasData { public static class Page { public final FileHandle textureFile; public Texture texture; // FIXME THIS IS FUCKING UGLY AS IT IS OPTIONAL FOR TEXTUREATLASLOADER UGH.e @@ -66,8 +61,9 @@ public static class Page { public final TextureFilter magFilter; public final TextureWrap uWrap; public final TextureWrap vWrap; - - public Page(FileHandle handle, boolean useMipMaps, Format format, TextureFilter minFilter, TextureFilter magFilter, TextureWrap uWrap, TextureWrap vWrap) { + + public Page (FileHandle handle, boolean useMipMaps, Format format, TextureFilter minFilter, TextureFilter magFilter, + TextureWrap uWrap, TextureWrap vWrap) { this.textureFile = handle; this.useMipMaps = useMipMaps; this.format = format; @@ -77,7 +73,7 @@ public Page(FileHandle handle, boolean useMipMaps, Format format, TextureFilter this.vWrap = vWrap; } } - + public static class Region { public Page page; public int index; @@ -95,11 +91,11 @@ public static class Region { public int height; public boolean flip; } - + final Array pages = new Array(); final Array regions = new Array(); - - public TextureAtlasData(FileHandle packFile, FileHandle imagesDir, boolean flip) { + + public TextureAtlasData (FileHandle packFile, FileHandle imagesDir, boolean flip) { PriorityQueue sortedRegions = new PriorityQueue(16, indexComparator); BufferedReader reader = new BufferedReader(new InputStreamReader(packFile.read()), 64); @@ -176,46 +172,38 @@ else if (direction.equals("xy")) { } catch (IOException ignored) { } } - + int n = sortedRegions.size(); for (int i = 0; i < n; i++) regions.add(sortedRegions.poll()); } - - public Array getPages() { + + public Array getPages () { return pages; } - - public Array getRegion() { + + public Array getRegion () { return regions; } } - /** - * Creates an empty atlas to which regions can be added. - */ + /** Creates an empty atlas to which regions can be added. */ public TextureAtlas () { } - /** - * Loads the specified pack file using {@link FileType#Internal}, using the parent directory of the pack file to find the page - * images. - */ + /** Loads the specified pack file using {@link FileType#Internal}, using the parent directory of the pack file to find the page + * images. */ public TextureAtlas (String internalPackFile) { this(Gdx.files.internal(internalPackFile)); } - /** - * Loads the specified pack file, using the parent directory of the pack file to find the page images. - */ + /** Loads the specified pack file, using the parent directory of the pack file to find the page images. */ public TextureAtlas (FileHandle packFile) { this(packFile, packFile.parent()); } - /** - * @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner. - * @see #TextureAtlas(FileHandle) - */ + /** @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner. + * @see #TextureAtlas(FileHandle) */ public TextureAtlas (FileHandle packFile, boolean flip) { this(packFile, packFile.parent(), flip); } @@ -224,22 +212,20 @@ public TextureAtlas (FileHandle packFile, FileHandle imagesDir) { this(packFile, imagesDir, false); } - /** - * @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner. - */ + /** @param flip If true, all regions loaded will be flipped for use with a perspective where 0,0 is the upper left corner. */ public TextureAtlas (FileHandle packFile, FileHandle imagesDir, boolean flip) { this(new TextureAtlasData(packFile, imagesDir, flip)); } - - public TextureAtlas(TextureAtlasData data) { + + public TextureAtlas (TextureAtlasData data) { load(data); } - - private void load(TextureAtlasData data) { + + private void load (TextureAtlasData data) { ObjectMap pageToTexture = new ObjectMap(); - for(Page page: data.pages) { + for (Page page : data.pages) { Texture texture = null; - if(page.texture == null) { + if (page.texture == null) { texture = new Texture(page.textureFile, page.format, page.useMipMaps); texture.setFilter(page.minFilter, page.magFilter); texture.setWrap(page.uWrap, page.vWrap); @@ -251,9 +237,10 @@ private void load(TextureAtlasData data) { textures.add(texture); pageToTexture.put(page, texture); } - - for(Region region: data.regions) { - AtlasRegion atlasRegion = new AtlasRegion(pageToTexture.get(region.page), region.left, region.top, region.width, region.height); + + for (Region region : data.regions) { + AtlasRegion atlasRegion = new AtlasRegion(pageToTexture.get(region.page), region.left, region.top, region.width, + region.height); atlasRegion.index = region.index; atlasRegion.name = region.name; atlasRegion.offsetX = region.offsetX; @@ -267,9 +254,7 @@ private void load(TextureAtlasData data) { } } - /** - * Adds a region to the atlas. The specified texture will be disposed when the atlas is disposed. - */ + /** Adds a region to the atlas. The specified texture will be disposed when the atlas is disposed. */ public AtlasRegion addRegion (String name, Texture texture, int x, int y, int width, int height) { textures.add(texture); AtlasRegion region = new AtlasRegion(texture, x, y, width, height); @@ -281,37 +266,29 @@ public AtlasRegion addRegion (String name, Texture texture, int x, int y, int wi return region; } - /** - * Adds a region to the atlas. The texture for the specified region will be disposed when the atlas is disposed. - */ + /** Adds a region to the atlas. The texture for the specified region will be disposed when the atlas is disposed. */ public AtlasRegion addRegion (String name, TextureRegion textureRegion) { return addRegion(name, textureRegion.texture, textureRegion.getRegionX(), textureRegion.getRegionY(), textureRegion.getRegionWidth(), textureRegion.getRegionHeight()); } - /** - * Returns all regions in the atlas. - */ + /** Returns all regions in the atlas. */ public List getRegions () { return regions; } - /** - * Returns the first region found with the specified name. This method uses string comparison to find the region, so the result + /** Returns the first region found with the specified name. This method uses string comparison to find the region, so the result * should be cached rather than calling this method multiple times. - * @return The region, or null. - */ + * @return The region, or null. */ public AtlasRegion findRegion (String name) { for (int i = 0, n = regions.size(); i < n; i++) if (regions.get(i).name.equals(name)) return regions.get(i); return null; } - /** - * Returns the first region found with the specified name and index. This method uses string comparison to find the region, so + /** Returns the first region found with the specified name and index. This method uses string comparison to find the region, so * the result should be cached rather than calling this method multiple times. - * @return The region, or null. - */ + * @return The region, or null. */ public AtlasRegion findRegion (String name, int index) { for (int i = 0, n = regions.size(); i < n; i++) { AtlasRegion region = regions.get(i); @@ -322,10 +299,8 @@ public AtlasRegion findRegion (String name, int index) { return null; } - /** - * Returns all regions with the specified name, ordered by smallest to largest {@link AtlasRegion#index index}. This method - * uses string comparison to find the regions, so the result should be cached rather than calling this method multiple times. - */ + /** Returns all regions with the specified name, ordered by smallest to largest {@link AtlasRegion#index index}. This method + * uses string comparison to find the regions, so the result should be cached rather than calling this method multiple times. */ public List findRegions (String name) { ArrayList matched = new ArrayList(); for (int i = 0, n = regions.size(); i < n; i++) { @@ -335,11 +310,9 @@ public List findRegions (String name) { return matched; } - /** - * Returns all regions in the atlas as sprites. This method creates a new sprite for each region, so the result should be + /** Returns all regions in the atlas as sprites. This method creates a new sprite for each region, so the result should be * stored rather than calling this method multiple times. - * @see #createSprite(String) - */ + * @see #createSprite(String) */ public List createSprites () { ArrayList sprites = new ArrayList(regions.size()); for (int i = 0, n = regions.size(); i < n; i++) @@ -347,24 +320,20 @@ public List createSprites () { return sprites; } - /** - * Returns the first region found with the specified name as a sprite. If whitespace was stripped from the region when it was + /** Returns the first region found with the specified name as a sprite. If whitespace was stripped from the region when it was * packed, the sprite is automatically positioned as if whitespace had not been stripped. This method uses string comparison to * find the region and constructs a new sprite, so the result should be cached rather than calling this method multiple times. - * @return The sprite, or null. - */ + * @return The sprite, or null. */ public Sprite createSprite (String name) { for (int i = 0, n = regions.size(); i < n; i++) if (regions.get(i).name.equals(name)) return newSprite(regions.get(i)); return null; } - /** - * Returns the first region found with the specified name and index as a sprite. This method uses string comparison to find the + /** Returns the first region found with the specified name and index as a sprite. This method uses string comparison to find the * region and constructs a new sprite, so the result should be cached rather than calling this method multiple times. * @return The sprite, or null. - * @see #createSprite(String) - */ + * @see #createSprite(String) */ public Sprite createSprite (String name, int index) { for (int i = 0, n = regions.size(); i < n; i++) { AtlasRegion region = regions.get(i); @@ -375,12 +344,10 @@ public Sprite createSprite (String name, int index) { return null; } - /** - * Returns all regions with the specified name as sprites, ordered by smallest to largest {@link AtlasRegion#index index}. This + /** Returns all regions with the specified name as sprites, ordered by smallest to largest {@link AtlasRegion#index index}. This * method uses string comparison to find the regions and constructs new sprites, so the result should be cached rather than * calling this method multiple times. - * @see #createSprite(String) - */ + * @see #createSprite(String) */ public List createSprites (String name) { ArrayList matched = new ArrayList(); for (int i = 0, n = regions.size(); i < n; i++) { @@ -399,10 +366,8 @@ private Sprite newSprite (AtlasRegion region) { return new AtlasSprite(region); } - /** - * Releases all resources associated with this TextureAtlas instance. This releases all the textures backing all TextureRegions - * and Sprites, which should no longer be used after calling dispose. - */ + /** Releases all resources associated with this TextureAtlas instance. This releases all the textures backing all TextureRegions + * and Sprites, which should no longer be used after calling dispose. */ public void dispose () { for (Texture texture : textures) texture.dispose(); @@ -435,59 +400,39 @@ static void readTuple (BufferedReader reader) throws IOException { tuple[1] = line.substring(comma + 1).trim(); } - /** - * Describes the region of a packed image and provides information about the original image before it was packed. - */ + /** Describes the region of a packed image and provides information about the original image before it was packed. */ static public class AtlasRegion extends TextureRegion { - /** - * The number at the end of the original image file name, or -1 if none.
        + /** The number at the end of the original image file name, or -1 if none.
        *
        * When sprites are packed, if the original file name ends with a number, it is stored as the index and is not considered as * part of the sprite's name. This is useful for keeping animation frames in order. - * @see TextureAtlas#findRegions(String) - */ + * @see TextureAtlas#findRegions(String) */ public int index; - /** - * The name of the original image file, up to the first underscore. Underscores denote special instructions to the texture - * packer. - */ + /** The name of the original image file, up to the first underscore. Underscores denote special instructions to the texture + * packer. */ public String name; - /** - * The offset from the left of the original image to the left of the packed image, after whitespace was removed for packing. - */ + /** The offset from the left of the original image to the left of the packed image, after whitespace was removed for packing. */ public float offsetX; - /** - * The offset from the bottom of the original image to the bottom of the packed image, after whitespace was removed for - * packing. - */ + /** The offset from the bottom of the original image to the bottom of the packed image, after whitespace was removed for + * packing. */ public float offsetY; - /** - * The width of the image, after whitespace was removed for packing. - */ + /** The width of the image, after whitespace was removed for packing. */ public int packedWidth; - /** - * The height of the image, after whitespace was removed for packing. - */ + /** The height of the image, after whitespace was removed for packing. */ public int packedHeight; - /** - * The width of the image, before whitespace was removed for packing. - */ + /** The width of the image, before whitespace was removed for packing. */ public int originalWidth; - /** - * The height of the image, before whitespace was removed for packing. - */ + /** The height of the image, before whitespace was removed for packing. */ public int originalHeight; - /** - * If true, the region has been rotated 90 degrees counter clockwise. - */ + /** If true, the region has been rotated 90 degrees counter clockwise. */ public boolean rotate; public AtlasRegion (Texture texture, int x, int y, int width, int height) { @@ -512,10 +457,8 @@ public AtlasRegion (AtlasRegion region) { setRegionHeight(packedHeight); } - /** - * Flips the region, adjusting the offset so the image appears to be flipped as if no whitespace has been removed for - * packing. - */ + /** Flips the region, adjusting the offset so the image appears to be flipped as if no whitespace has been removed for + * packing. */ public void flip (boolean x, boolean y) { super.flip(x, y); if (x) offsetX = originalWidth - offsetX - packedWidth; @@ -523,10 +466,8 @@ public void flip (boolean x, boolean y) { } } - /** - * A sprite that, if whitespace was stripped from the region when it was packed, is automatically positioned as if whitespace - * had not been stripped. - */ + /** A sprite that, if whitespace was stripped from the region when it was packed, is automatically positioned as if whitespace + * had not been stripped. */ static public class AtlasSprite extends Sprite { final AtlasRegion region; diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureRegion.java b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureRegion.java index 95847a11a19..4a43ebfa5d9 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/TextureRegion.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/TextureRegion.java @@ -13,39 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.graphics.Texture; -/** - * Defines a rectangular area of a texture. The coordinate system used has its origin in the upper left corner with the x-axis +/** Defines a rectangular area of a texture. The coordinate system used has its origin in the upper left corner with the x-axis * pointing to the right and the y axis pointing downwards. * @author mzechner - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class TextureRegion { Texture texture; float u, v; float u2, v2; - /** - * Constructs a region with no texture and no coordinates defined. - */ + /** Constructs a region with no texture and no coordinates defined. */ public TextureRegion () { } - /** - * Constructs a region the size of the specified texture. - */ + /** Constructs a region the size of the specified texture. */ public TextureRegion (Texture texture) { this.texture = texture; setRegion(0, 0, texture.getWidth(), texture.getHeight()); } - /** - * @param width The width of the texture region. May be negative to flip the sprite when drawn. - * @param height The height of the texture region. May be negative to flip the sprite when drawn. - */ + /** @param width The width of the texture region. May be negative to flip the sprite when drawn. + * @param height The height of the texture region. May be negative to flip the sprite when drawn. */ public TextureRegion (Texture texture, int x, int y, int width, int height) { this.texture = texture; setRegion(x, y, width, height); @@ -56,34 +49,26 @@ public TextureRegion (Texture texture, float u, float v, float u2, float v2) { setRegion(u, v, u2, v2); } - /** - * Constructs a region with the same texture and coordinates of the specified region. - */ + /** Constructs a region with the same texture and coordinates of the specified region. */ public TextureRegion (TextureRegion region) { setRegion(region); } - /** - * Constructs a region with the same texture as the specified region and sets the coordinates relative to the specified region. + /** Constructs a region with the same texture as the specified region and sets the coordinates relative to the specified region. * @param width The width of the texture region. May be negative to flip the sprite when drawn. - * @param height The height of the texture region. May be negative to flip the sprite when drawn. - */ + * @param height The height of the texture region. May be negative to flip the sprite when drawn. */ public TextureRegion (TextureRegion region, int x, int y, int width, int height) { setRegion(region, x, y, width, height); } - /** - * Sets the texture and sets the coordinates to the size of the specified texture. - */ + /** Sets the texture and sets the coordinates to the size of the specified texture. */ public void setRegion (Texture texture) { this.texture = texture; setRegion(0, 0, texture.getWidth(), texture.getHeight()); } - /** - * @param width The width of the texture region. May be negative to flip the sprite when drawn. - * @param height The height of the texture region. May be negative to flip the sprite when drawn. - */ + /** @param width The width of the texture region. May be negative to flip the sprite when drawn. + * @param height The height of the texture region. May be negative to flip the sprite when drawn. */ public void setRegion (int x, int y, int width, int height) { float invTexWidth = 1f / texture.getWidth(); float invTexHeight = 1f / texture.getHeight(); @@ -97,17 +82,13 @@ public void setRegion (float u, float v, float u2, float v2) { this.v2 = v2; } - /** - * Sets the texture and coordinates to the specified region. - */ + /** Sets the texture and coordinates to the specified region. */ public void setRegion (TextureRegion region) { texture = region.texture; setRegion(region.u, region.v, region.u2, region.v2); } - /** - * Sets the texture to that of the specified region and sets the coordinates relative to the specified region. - */ + /** Sets the texture to that of the specified region and sets the coordinates relative to the specified region. */ public void setRegion (TextureRegion region, int x, int y, int width, int height) { texture = region.texture; setRegion(region.getRegionX() + x, region.getRegionY() + y, width, height); @@ -169,9 +150,7 @@ public void setRegionY (int y) { setV(y / (float)texture.getHeight()); } - /** - * Returns the region's width. May be negative if the texture region is flipped horizontally. - */ + /** Returns the region's width. May be negative if the texture region is flipped horizontally. */ public int getRegionWidth () { return (int)((u2 - u) * texture.getWidth()); } @@ -180,9 +159,7 @@ public void setRegionWidth (int width) { setU2(u + width / (float)texture.getWidth()); } - /** - * Returns the region's height. May be negative if the texture region is flipped horizontally. - */ + /** Returns the region's height. May be negative if the texture region is flipped horizontally. */ public int getRegionHeight () { return (int)((v2 - v) * texture.getHeight()); } @@ -201,15 +178,13 @@ public void flip (boolean x, boolean y) { float temp = v; v = v2; v2 = temp; - } + } } - /** - * Offsets the region relative to the current region. Generally the region's size should be the entire size of the texture in + /** Offsets the region relative to the current region. Generally the region's size should be the entire size of the texture in * the direction(s) it is scrolled. * @param xAmount The percentage to offset horizontally. - * @param yAmount The percentage to offset vertically. This is done in texture space, so up is negative. - */ + * @param yAmount The percentage to offset vertically. This is done in texture space, so up is negative. */ public void scroll (float xAmount, float yAmount) { if (xAmount != 0) { float width = (u2 - u) * texture.getWidth(); @@ -222,64 +197,54 @@ public void scroll (float xAmount, float yAmount) { v2 = v + height / texture.getHeight(); } } - - /** - * Helper function to create tiles out of this TextureRegion - * starting from the top left corner going to the left and - * ending at the bottom right corner. Only complete tiles will - * be returned so if the region's width or height are not a - * multiple of the tile width and height not all of the - * region will be used. + + /** Helper function to create tiles out of this TextureRegion starting from the top left corner going to the left and ending at + * the bottom right corner. Only complete tiles will be returned so if the region's width or height are not a multiple of the + * tile width and height not all of the region will be used. * * @param tileWidth a tile's width in pixels * @param tileHeight a tile's height in pixels - * @return a 2D array of TextureRegions indexed by [row][column]. - */ - public TextureRegion[][] split(int tileWidth, int tileHeight) { + * @return a 2D array of TextureRegions indexed by [row][column]. */ + public TextureRegion[][] split (int tileWidth, int tileHeight) { int x = getRegionX(); int y = getRegionY(); int width = getRegionWidth(); int height = getRegionHeight(); - - if(width < 0) { + + if (width < 0) { x = x - width; width = -width; } - - if(height < 0) { + + if (height < 0) { y = y - height; height = -height; } - + int rows = height / tileHeight; - int cols = width / tileWidth; - + int cols = width / tileWidth; + int startX = x; - TextureRegion[][] tiles = new TextureRegion[rows][cols]; - for(int row = 0; row < rows; row++, y += tileHeight) { + TextureRegion[][] tiles = new TextureRegion[rows][cols]; + for (int row = 0; row < rows; row++, y += tileHeight) { x = startX; - for(int col = 0; col < cols; col++, x += tileWidth) { + for (int col = 0; col < cols; col++, x += tileWidth) { tiles[row][col] = new TextureRegion(texture, x, y, tileWidth, tileHeight); } } - + return tiles; } - - /** - * Helper function to create tiles out of the given {@link Texture} - * starting from the top left corner going to the left and - * ending at the bottom right corner. Only complete tiles will - * be returned so if the texture's width or height are not a - * multiple of the tile width and height not all of the - * texture will be used. + + /** Helper function to create tiles out of the given {@link Texture} starting from the top left corner going to the left and + * ending at the bottom right corner. Only complete tiles will be returned so if the texture's width or height are not a + * multiple of the tile width and height not all of the texture will be used. * * @param texture the Texture * @param tileWidth a tile's width in pixels * @param tileHeight a tile's height in pixels - * @return a 2D array of TextureRegions indexed by [row][column]. - */ - public static TextureRegion[][] split(Texture texture, int tileWidth, int tileHeight) { + * @return a 2D array of TextureRegions indexed by [row][column]. */ + public static TextureRegion[][] split (Texture texture, int tileWidth, int tileHeight) { TextureRegion region = new TextureRegion(texture); return region.split(tileWidth, tileHeight); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java index f5ac6bd40a4..02a9af185bf 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d.tiled; import com.badlogic.gdx.files.FileHandle; @@ -21,56 +22,54 @@ import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; -/** - * Contains an atlas of tiles by tile id for use with {@link TileMapRenderer} - * It does not need to be loaded with packed files. Just plain textures. - * @author Tomas Lazaro - */ +/** Contains an atlas of tiles by tile id for use with {@link TileMapRenderer} It does not need to be loaded with packed files. + * Just plain textures. + * @author Tomas Lazaro */ public class SimpleTileAtlas extends TileAtlas { - /** - * Creates a TileAtlas for use with {@link TileMapRenderer}. - * @param map The tiled map - * @param inputDir The directory containing all needed textures in the map - */ - public SimpleTileAtlas(TiledMap map, FileHandle inputDir) { - for (TileSet set : map.tileSets) { - Pixmap pixmap = new Pixmap(inputDir.child(set.imageName)); + /** Creates a TileAtlas for use with {@link TileMapRenderer}. + * @param map The tiled map + * @param inputDir The directory containing all needed textures in the map */ + public SimpleTileAtlas (TiledMap map, FileHandle inputDir) { + for (TileSet set : map.tileSets) { + Pixmap pixmap = new Pixmap(inputDir.child(set.imageName)); + + int originalWidth = pixmap.getWidth(); + int originalHeight = pixmap.getHeight(); + + Pixmap result = pixmap; + if (!MathUtils.isPowerOfTwo(originalWidth) || !MathUtils.isPowerOfTwo(originalHeight)) { + final int width = MathUtils.nextPowerOfTwo(originalWidth); + final int height = MathUtils.nextPowerOfTwo(originalHeight); - int originalWidth = pixmap.getWidth(); - int originalHeight = pixmap.getHeight(); - - Pixmap result = pixmap; - if (!MathUtils.isPowerOfTwo(originalWidth) || !MathUtils.isPowerOfTwo(originalHeight)) { - final int width = MathUtils.nextPowerOfTwo(originalWidth); - final int height = MathUtils.nextPowerOfTwo(originalHeight); + result = new Pixmap(width, height, pixmap.getFormat()); + result.drawPixmap(pixmap, 0, 0, 0, 0, width, height); + } + Texture texture = new Texture(result); - result = new Pixmap(width, height, pixmap.getFormat()); - result.drawPixmap(pixmap, 0, 0, 0, 0, width, height); - } - Texture texture = new Texture(result); + int idx = 0; + TextureRegion[][] regions = split(texture, originalWidth, originalHeight, map.tileWidth, map.tileHeight, set.spacing, + set.margin); + for (int y = 0; y < regions[0].length; y++) { + for (int x = 0; x < regions.length; x++) { + regionsMap.put(idx++ + set.firstgid, regions[x][y]); + } + } + } + } - int idx = 0; - TextureRegion[][] regions = split(texture, originalWidth, originalHeight, map.tileWidth, map.tileHeight, set.spacing, set.margin); - for (int y = 0; y < regions[0].length; y++) { - for (int x = 0; x < regions.length; x++) { - regionsMap.put(idx++ + set.firstgid, regions[x][y]); - } - } - } - } - - private static TextureRegion[][] split(Texture texture, int totalWidth, int totalHeight, int width, int height, int spacing, int margin) { - // TODO add padding support - int xSlices = (totalWidth - margin) / (width + spacing); - int ySlices = (totalHeight - margin) / (height + spacing); + private static TextureRegion[][] split (Texture texture, int totalWidth, int totalHeight, int width, int height, int spacing, + int margin) { + // TODO add padding support + int xSlices = (totalWidth - margin) / (width + spacing); + int ySlices = (totalHeight - margin) / (height + spacing); - TextureRegion[][] res = new TextureRegion[xSlices][ySlices]; - for (int x = 0; x < xSlices; x++) { - for (int y = 0; y < ySlices; y++) { - res[x][y] = new TextureRegion(texture, margin + x * (width + spacing), margin + y * (height + spacing), width, height); - } - } - return res; - } + TextureRegion[][] res = new TextureRegion[xSlices][ySlices]; + for (int x = 0; x < xSlices; x++) { + for (int y = 0; y < ySlices; y++) { + res[x][y] = new TextureRegion(texture, margin + x * (width + spacing), margin + y * (height + spacing), width, height); + } + } + return res; + } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileAtlas.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileAtlas.java index 17382c3cb3c..b5e0647a456 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileAtlas.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileAtlas.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d.tiled; import java.util.HashSet; @@ -27,107 +28,97 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.IntMap; -/** - * Contains an atlas of tiles by tile id for use with {@link TileMapRenderer} - * @author David Fraska - */ +/** Contains an atlas of tiles by tile id for use with {@link TileMapRenderer} + * @author David Fraska */ public class TileAtlas implements Disposable { - protected IntMap regionsMap = new IntMap(); - protected final HashSet textures = new HashSet(1); - - /** - * Protected constructor to allow different implementations - */ - protected TileAtlas() { - } - - /** - * Creates a TileAtlas for use with {@link TileMapRenderer}. Run the map through TiledMapPacker to create the files required. - * @param map The tiled map - * @param inputDir The directory containing all the files created by TiledMapPacker - * */ - public TileAtlas(TiledMap map, FileHandle inputDir) { - // TODO: Create a constructor that doesn't take a tmx map, - for (TileSet set : map.tileSets) { - FileHandle packfile = getRelativeFileHandle(inputDir, removeExtension(set.imageName) + " packfile"); - TextureAtlas textureAtlas = new TextureAtlas(packfile, packfile.parent(), false); - List atlasRegions = textureAtlas.findRegions(removeExtension(removePath(set.imageName))); - - for (AtlasRegion reg : atlasRegions) { - regionsMap.put(reg.index + set.firstgid, reg); - if (!textures.contains(reg.getTexture())) { - textures.add(reg.getTexture()); - } - } - } - } - - /** - * Gets an {@link TextureRegion} for a tile id - * @param id tile id - * @return the {@link TextureRegion} - */ - public TextureRegion getRegion(int id) { - return regionsMap.get(id); - } - - /** - * Releases all resources associated with this TileAtlas instance. This releases all the textures backing all AtlasRegions, - * which should no longer be used after calling dispose. - */ - @Override - public void dispose() { - for (Texture texture : textures) { - texture.dispose(); - } - textures.clear(); - } - - private static String removeExtension(String s) { - int extensionIndex = s.lastIndexOf("."); - if (extensionIndex == -1) { - return s; - } - - return s.substring(0, extensionIndex); - } - - private static String removePath(String s) { - String temp; - - int index = s.lastIndexOf('\\'); - if (index != -1) { - temp = s.substring(index + 1); - } else { - temp = s; - } - - index = temp.lastIndexOf('/'); - if (index != -1) { - return s.substring(index + 1); - } else { - return s; - } - } - - private static FileHandle getRelativeFileHandle(FileHandle path, String relativePath) { - if (relativePath.trim().length() == 0) { - return path; - } - - FileHandle child = path; - - StringTokenizer tokenizer = new StringTokenizer(relativePath, "\\/"); - while (tokenizer.hasMoreTokens()) { - String token = tokenizer.nextToken(); - if (token.equals("..")) { - child = child.parent(); - } else { - child = child.child(token); - } - } - - return child; - } + protected IntMap regionsMap = new IntMap(); + protected final HashSet textures = new HashSet(1); + + /** Protected constructor to allow different implementations */ + protected TileAtlas () { + } + + /** Creates a TileAtlas for use with {@link TileMapRenderer}. Run the map through TiledMapPacker to create the files required. + * @param map The tiled map + * @param inputDir The directory containing all the files created by TiledMapPacker */ + public TileAtlas (TiledMap map, FileHandle inputDir) { + // TODO: Create a constructor that doesn't take a tmx map, + for (TileSet set : map.tileSets) { + FileHandle packfile = getRelativeFileHandle(inputDir, removeExtension(set.imageName) + " packfile"); + TextureAtlas textureAtlas = new TextureAtlas(packfile, packfile.parent(), false); + List atlasRegions = textureAtlas.findRegions(removeExtension(removePath(set.imageName))); + + for (AtlasRegion reg : atlasRegions) { + regionsMap.put(reg.index + set.firstgid, reg); + if (!textures.contains(reg.getTexture())) { + textures.add(reg.getTexture()); + } + } + } + } + + /** Gets an {@link TextureRegion} for a tile id + * @param id tile id + * @return the {@link TextureRegion} */ + public TextureRegion getRegion (int id) { + return regionsMap.get(id); + } + + /** Releases all resources associated with this TileAtlas instance. This releases all the textures backing all AtlasRegions, + * which should no longer be used after calling dispose. */ + @Override + public void dispose () { + for (Texture texture : textures) { + texture.dispose(); + } + textures.clear(); + } + + private static String removeExtension (String s) { + int extensionIndex = s.lastIndexOf("."); + if (extensionIndex == -1) { + return s; + } + + return s.substring(0, extensionIndex); + } + + private static String removePath (String s) { + String temp; + + int index = s.lastIndexOf('\\'); + if (index != -1) { + temp = s.substring(index + 1); + } else { + temp = s; + } + + index = temp.lastIndexOf('/'); + if (index != -1) { + return s.substring(index + 1); + } else { + return s; + } + } + + private static FileHandle getRelativeFileHandle (FileHandle path, String relativePath) { + if (relativePath.trim().length() == 0) { + return path; + } + + FileHandle child = path; + + StringTokenizer tokenizer = new StringTokenizer(relativePath, "\\/"); + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken(); + if (token.equals("..")) { + child = child.parent(); + } else { + child = child.child(token); + } + } + + return child; + } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileMapRenderer.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileMapRenderer.java index 335444d39d7..3b567fcdff9 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileMapRenderer.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileMapRenderer.java @@ -29,10 +29,8 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.IntArray; -/** - * A renderer for Tiled maps backed with a Sprite Cache. - * @author David Fraska - * */ +/** A renderer for Tiled maps backed with a Sprite Cache. + * @author David Fraska */ public class TileMapRenderer implements Disposable { private SpriteCache cache; private int normalCacheId[][][], blendedCacheId[][][]; @@ -45,12 +43,11 @@ public class TileMapRenderer implements Disposable { private int tilesPerBlockX, tilesPerBlockY; private float unitsPerBlockX, unitsPerBlockY; private int[] allLayers; - private boolean isSimpleTileAtlas = false; + private boolean isSimpleTileAtlas = false; private IntArray blendedTiles; - /** - * A renderer for static tile maps backed with a Sprite Cache. + /** A renderer for static tile maps backed with a Sprite Cache. * * This constructor is for convenience when loading TiledMaps. The normal Tiled coordinate system is used when placing tiles. * @@ -63,14 +60,12 @@ public class TileMapRenderer implements Disposable { * @param map A tile map's tile numbers, in the order [layer][row][column] * @param atlas The tile atlas to be used when drawing the map * @param tilesPerBlockX The width of each block to be drawn, in number of tiles - * @param tilesPerBlockY The height of each block to be drawn, in number of tiles - */ + * @param tilesPerBlockY The height of each block to be drawn, in number of tiles */ public TileMapRenderer (TiledMap map, TileAtlas atlas, int tilesPerBlockX, int tilesPerBlockY) { this(map, atlas, tilesPerBlockX, tilesPerBlockY, map.tileWidth, map.tileHeight); } - /** - * A renderer for static tile maps backed with a Sprite Cache. + /** A renderer for static tile maps backed with a Sprite Cache. * * This constructor is for convenience when loading TiledMaps. * @@ -85,15 +80,13 @@ public TileMapRenderer (TiledMap map, TileAtlas atlas, int tilesPerBlockX, int t * @param tilesPerBlockX The width of each block to be drawn, in number of tiles * @param tilesPerBlockY The height of each block to be drawn, in number of tiles * @param unitsPerTileX The number of units per tile in the x direction - * @param unitsPerTileY The number of units per tile in the y direction - */ + * @param unitsPerTileY The number of units per tile in the y direction */ public TileMapRenderer (TiledMap map, TileAtlas atlas, int tilesPerBlockX, int tilesPerBlockY, float unitsPerTileX, float unitsPerTileY) { this(map, atlas, tilesPerBlockX, tilesPerBlockY, unitsPerTileX, unitsPerTileY, null); } - /** - * A renderer for static tile maps backed with a Sprite Cache. + /** A renderer for static tile maps backed with a Sprite Cache. * * This constructor is for convenience when loading TiledMaps. The normal Tiled coordinate system is used when placing tiles. * @@ -105,8 +98,7 @@ public TileMapRenderer (TiledMap map, TileAtlas atlas, int tilesPerBlockX, int t * @param atlas The tile atlas to be used when drawing the map * @param tilesPerBlockX The width of each block to be drawn, in number of tiles * @param tilesPerBlockY The height of each block to be drawn, in number of tiles - * @param shader Shader to use for OpenGL ES 2.0, null uses a default shader. Ignored if using OpenGL ES 1.0. - */ + * @param shader Shader to use for OpenGL ES 2.0, null uses a default shader. Ignored if using OpenGL ES 1.0. */ public TileMapRenderer (TiledMap map, TileAtlas atlas, int tilesPerBlockX, int tilesPerBlockY, ShaderProgram shader) { this(map, atlas, tilesPerBlockX, tilesPerBlockY, map.tileWidth, map.tileHeight, shader); } @@ -138,8 +130,7 @@ public TileMapRenderer (TiledMap map, TileAtlas atlas, int tilesPerBlockX, int t tilesPerBlockY, shader); } - /** - * A renderer for static tile maps backed with a Sprite Cache. + /** A renderer for static tile maps backed with a Sprite Cache. * * The tilesPerBlockX and tilesPerBlockY parameters will need to be adjusted for best performance. Smaller values will cull * more precisely, but result in longer loading times. Larger values result in shorter loading times, but will cull less @@ -155,15 +146,13 @@ public TileMapRenderer (TiledMap map, TileAtlas atlas, int tilesPerBlockX, int t * @param unitsPerTileY The number of units per tile in the y direction * @param blendedTiles Array containing tile numbers that require blending * @param tilesPerBlockX The width of each block to be drawn, in number of tiles - * @param tilesPerBlockY The height of each block to be drawn, in number of tiles - */ + * @param tilesPerBlockY The height of each block to be drawn, in number of tiles */ public TileMapRenderer (int[][][] map, TileAtlas atlas, int tileWidth, int tileHeight, float unitsPerTileX, float unitsPerTileY, IntArray blendedTiles, int tilesPerBlockX, int tilesPerBlockY) { init(map, atlas, tileWidth, tileHeight, unitsPerTileX, unitsPerTileY, blendedTiles, tilesPerBlockX, tilesPerBlockY, null); } - /** - * A renderer for static tile maps backed with a Sprite Cache. + /** A renderer for static tile maps backed with a Sprite Cache. * * The tilesPerBlockX and tilesPerBlockY parameters will need to be adjusted for best performance. Smaller values will cull * more precisely, but result in longer loading times. Larger values result in shorter loading times, but will cull less @@ -178,17 +167,14 @@ public TileMapRenderer (int[][][] map, TileAtlas atlas, int tileWidth, int tileH * @param blendedTiles Array containing tile numbers that require blending * @param tilesPerBlockX The width of each block to be drawn, in number of tiles * @param tilesPerBlockY The height of each block to be drawn, in number of tiles - * @param shader Shader to use for OpenGL ES 2.0, null uses a default shader. Ignored if using OpenGL ES 1.0. - */ + * @param shader Shader to use for OpenGL ES 2.0, null uses a default shader. Ignored if using OpenGL ES 1.0. */ public TileMapRenderer (int[][][] map, TileAtlas atlas, int tileWidth, int tileHeight, float unitsPerTileX, float unitsPerTileY, IntArray blendedTiles, int tilesPerBlockX, int tilesPerBlockY, ShaderProgram shader) { init(map, atlas, tileWidth, tileHeight, unitsPerTileX, unitsPerTileY, blendedTiles, tilesPerBlockX, tilesPerBlockY, shader); } - /** - * Initializer, used to avoid a "Constructor call must be the first statement in a constructor" syntax error when creating a - * map from a TiledMap - * */ + /** Initializer, used to avoid a "Constructor call must be the first statement in a constructor" syntax error when creating a + * map from a TiledMap */ private void init (int[][][] map, TileAtlas atlas, int tileWidth, int tileHeight, float unitsPerTileX, float unitsPerTileY, IntArray blendedTiles, int tilesPerBlockX, int tilesPerBlockY, ShaderProgram shader) { this.atlas = atlas; @@ -200,11 +186,11 @@ private void init (int[][][] map, TileAtlas atlas, int tileWidth, int tileHeight this.blendedTiles = blendedTiles; this.tilesPerBlockX = tilesPerBlockX; this.tilesPerBlockY = tilesPerBlockY; - + unitsPerBlockX = unitsPerTileX * tilesPerBlockX; unitsPerBlockY = unitsPerTileY * tilesPerBlockY; - - isSimpleTileAtlas = atlas instanceof SimpleTileAtlas; + + isSimpleTileAtlas = atlas instanceof SimpleTileAtlas; int layer, row, col; @@ -240,87 +226,76 @@ private void init (int[][][] map, TileAtlas atlas, int tileWidth, int tileHeight normalCacheId[layer][row] = new int[(int)MathUtils.ceil((float)map[layer][row].length / tilesPerBlockX)]; blendedCacheId[layer][row] = new int[(int)MathUtils.ceil((float)map[layer][row].length / tilesPerBlockX)]; for (col = 0; col < normalCacheId[layer][row].length; col++) { - if (isSimpleTileAtlas) { - // Everything considered blended - blendedCacheId[layer][row][col] = addBlock(map[layer], row, col, false); - } else { - normalCacheId[layer][row][col] = addBlock(map[layer], row, col, false); - blendedCacheId[layer][row][col] = addBlock(map[layer], row, col, true); - } + if (isSimpleTileAtlas) { + // Everything considered blended + blendedCacheId[layer][row][col] = addBlock(map[layer], row, col, false); + } else { + normalCacheId[layer][row][col] = addBlock(map[layer], row, col, false); + blendedCacheId[layer][row][col] = addBlock(map[layer], row, col, true); + } + } + } + } + } + + private int addBlock (int[][] layer, int blockRow, int blockCol, boolean blended) { + cache.beginCache(); + + int firstCol = blockCol * tilesPerBlockX; + int firstRow = blockRow * tilesPerBlockY; + int lastCol = firstCol + tilesPerBlockX; + int lastRow = firstRow + tilesPerBlockY; + + for (int row = firstRow; row < lastRow && row < layer.length; row++) { + for (int col = firstCol; col < lastCol && col < layer[row].length; col++) { + int tile = layer[row][col]; + if (tile != 0) { + if (blended == blendedTiles.contains(tile)) { + TextureRegion reg = atlas.getRegion(tile); + if (reg != null) { + if (!isSimpleTileAtlas) { + AtlasRegion region = (AtlasRegion)reg; + cache.add(region, col * unitsPerTileX, (layer.length - row - 1) * unitsPerTileY, (float)region.offsetX + * unitsPerTileX / tileWidth, (float)(region.offsetY) * unitsPerTileY / (float)tileHeight, + region.packedWidth, region.packedHeight, unitsPerTileX / (float)tileWidth, unitsPerTileY + / (float)tileHeight, (region.rotate) ? 90 : 0); + } else { + cache.add(reg, col * unitsPerTileX, (layer.length - row - 1) * unitsPerTileY, 0, 0, reg.getRegionWidth(), + reg.getRegionHeight(), unitsPerTileX / tileWidth, unitsPerTileY / tileHeight, 0); + } + } + } } } } + + return cache.endCache(); } - private int addBlock(int[][] layer, int blockRow, int blockCol, boolean blended) { - cache.beginCache(); - - int firstCol = blockCol * tilesPerBlockX; - int firstRow = blockRow * tilesPerBlockY; - int lastCol = firstCol + tilesPerBlockX; - int lastRow = firstRow + tilesPerBlockY; - - for (int row = firstRow; row < lastRow && row < layer.length; row++) { - for (int col = firstCol; col < lastCol && col < layer[row].length; col++) { - int tile = layer[row][col]; - if (tile != 0) { - if (blended == blendedTiles.contains(tile)) { - TextureRegion reg = atlas.getRegion(tile); - if (reg != null) { - if (!isSimpleTileAtlas) { - AtlasRegion region = (AtlasRegion) reg; - cache.add(region, col * unitsPerTileX, (layer.length - row - 1) * unitsPerTileY, - (float) region.offsetX * unitsPerTileX / tileWidth, (float) (region.offsetY) * unitsPerTileY / (float)tileHeight, - region.packedWidth, region.packedHeight, - unitsPerTileX / (float)tileWidth, unitsPerTileY / (float)tileHeight, - (region.rotate) ? 90 : 0); - } else { - cache.add(reg, col * unitsPerTileX, (layer.length - row - 1) * unitsPerTileY, - 0, 0, - reg.getRegionWidth(), reg.getRegionHeight(), - unitsPerTileX / tileWidth, unitsPerTileY / tileHeight, - 0); - } - } - } - } - } - } - - return cache.endCache(); - } - - /** - * Renders the entire map. Use this function only on very small maps or for debugging purposes. The size of the map is based on - * the first layer and the first row's size. - */ + /** Renders the entire map. Use this function only on very small maps or for debugging purposes. The size of the map is based on + * the first layer and the first row's size. */ public void render () { render(0, 0, (int)getMapWidthUnits(), (int)(getMapHeightUnits())); } - /** - * Renders all layers between the given bounding box in map units. This is the same as calling - * {@link TileMapRenderer#render(float, float, float, float, int[])} with all layers in the layers list. - */ + /** Renders all layers between the given bounding box in map units. This is the same as calling + * {@link TileMapRenderer#render(float, float, float, float, int[])} with all layers in the layers list. */ public void render (float x, float y, float width, float height) { render(x, y, width, height, allLayers); } - /** - * Renders specific layers in the given a camera - * @param cam The camera to use - */ + /** Renders specific layers in the given a camera + * @param cam The camera to use */ public void render (OrthographicCamera cam) { render(cam, allLayers); } Vector3 tmp = new Vector3(); - /** - * Renders specific layers in the given a camera. + + /** Renders specific layers in the given a camera. * @param cam The camera to use * @param layers The list of layers to draw, 0 being the lowest layer. You will get an IndexOutOfBoundsException if a layer - * number is too high. - */ + * number is too high. */ public void render (OrthographicCamera cam, int[] layers) { getProjectionMatrix().set(cam.combined); tmp.set(0, 0, 0); @@ -328,34 +303,28 @@ public void render (OrthographicCamera cam, int[] layers) { render(tmp.x, tmp.y, cam.viewportWidth * cam.zoom, cam.viewportHeight * cam.zoom, layers); } - /** - * Sets the amount of overdraw in the X direction (in units). Use this if an actual tile width is greater than the tileWidth - * specified in the constructor. Use the value actual_tile_width - tileWidth (from the constructor). - */ + /** Sets the amount of overdraw in the X direction (in units). Use this if an actual tile width is greater than the tileWidth + * specified in the constructor. Use the value actual_tile_width - tileWidth (from the constructor). */ public float overdrawX; - /** - * Sets the amount of overdraw in the Y direction (in units). Use this if an actual tile height is greater than the tileHeight - * specified in the constructor. Use the value actual_tile_height - tileHeight (from the constructor). - */ + /** Sets the amount of overdraw in the Y direction (in units). Use this if an actual tile height is greater than the tileHeight + * specified in the constructor. Use the value actual_tile_height - tileHeight (from the constructor). */ public float overdrawY; private int initialRow, initialCol, currentRow, currentCol, lastRow, lastCol, currentLayer; - /** - * Renders specific layers between the given bounding box in map units. + /** Renders specific layers between the given bounding box in map units. * @param x The x coordinate to start drawing * @param y the y coordinate to start drawing * @param width the width of the tiles to draw * @param height the width of the tiles to draw * @param layers The list of layers to draw, 0 being the lowest layer. You will get an IndexOutOfBoundsException if a layer - * number is too high. - */ + * number is too high. */ public void render (float x, float y, float width, float height, int[] layers) { lastRow = (int)((mapHeightUnits - (y - height + overdrawY)) / (unitsPerBlockY)); initialRow = (int)((mapHeightUnits - (y - overdrawY)) / (unitsPerBlockY)); initialRow = (initialRow > 0) ? initialRow : 0; // Clamp initial Row > 0 - + lastCol = (int)((x + width + overdrawX) / (unitsPerBlockX)); initialCol = (int)((x - overdrawX) / (unitsPerBlockX)); initialCol = (initialCol > 0) ? initialCol : 0; // Clamp initial Col > 0 @@ -363,58 +332,60 @@ public void render (float x, float y, float width, float height, int[] layers) { Gdx.gl.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); cache.begin(); - if (isSimpleTileAtlas) { - // Without this special case the top left corner doesn't work properly on mutilayered maps - Gdx.gl.glEnable(GL10.GL_BLEND); - for (currentLayer = 0; currentLayer < layers.length; currentLayer++) { - for (currentRow = initialRow; currentRow <= lastRow && currentRow < getLayerHeightInBlocks(currentLayer); currentRow++) { - for (currentCol = initialCol; currentCol <= lastCol && currentCol < getLayerWidthInBlocks(currentLayer, currentRow); currentCol++) { - cache.draw(blendedCacheId[layers[currentLayer]][currentRow][currentCol]); - } - } - } - } else { - for (currentLayer = 0; currentLayer < layers.length; currentLayer++) { - for (currentRow = initialRow; currentRow <= lastRow && currentRow < getLayerHeightInBlocks(currentLayer); currentRow++) { - for (currentCol = initialCol; currentCol <= lastCol && currentCol < getLayerWidthInBlocks(currentLayer, currentRow); currentCol++) { - Gdx.gl.glDisable(GL10.GL_BLEND); - cache.draw(normalCacheId[layers[currentLayer]][currentRow][currentCol]); - Gdx.gl.glEnable(GL10.GL_BLEND); - cache.draw(blendedCacheId[layers[currentLayer]][currentRow][currentCol]); - } - } - } - } + if (isSimpleTileAtlas) { + // Without this special case the top left corner doesn't work properly on mutilayered maps + Gdx.gl.glEnable(GL10.GL_BLEND); + for (currentLayer = 0; currentLayer < layers.length; currentLayer++) { + for (currentRow = initialRow; currentRow <= lastRow && currentRow < getLayerHeightInBlocks(currentLayer); currentRow++) { + for (currentCol = initialCol; currentCol <= lastCol + && currentCol < getLayerWidthInBlocks(currentLayer, currentRow); currentCol++) { + cache.draw(blendedCacheId[layers[currentLayer]][currentRow][currentCol]); + } + } + } + } else { + for (currentLayer = 0; currentLayer < layers.length; currentLayer++) { + for (currentRow = initialRow; currentRow <= lastRow && currentRow < getLayerHeightInBlocks(currentLayer); currentRow++) { + for (currentCol = initialCol; currentCol <= lastCol + && currentCol < getLayerWidthInBlocks(currentLayer, currentRow); currentCol++) { + Gdx.gl.glDisable(GL10.GL_BLEND); + cache.draw(normalCacheId[layers[currentLayer]][currentRow][currentCol]); + Gdx.gl.glEnable(GL10.GL_BLEND); + cache.draw(blendedCacheId[layers[currentLayer]][currentRow][currentCol]); + } + } + } + } cache.end(); Gdx.gl.glDisable(GL10.GL_BLEND); } private int getLayerWidthInBlocks (int layer, int row) { - int normalCacheWidth = 0; + int normalCacheWidth = 0; if (normalCacheId != null && normalCacheId[layer] != null && normalCacheId[layer][row] != null) { - normalCacheWidth = normalCacheId[layer][row].length; - } - - int blendedCacheWidth = 0; + normalCacheWidth = normalCacheId[layer][row].length; + } + + int blendedCacheWidth = 0; if (blendedCacheId != null && blendedCacheId[layer] != null && blendedCacheId[layer][row] != null) { - blendedCacheWidth = blendedCacheId[layer][row].length; - } - - return Math.max(normalCacheWidth, blendedCacheWidth); + blendedCacheWidth = blendedCacheId[layer][row].length; + } + + return Math.max(normalCacheWidth, blendedCacheWidth); } private int getLayerHeightInBlocks (int layer) { - int normalCacheHeight = 0; + int normalCacheHeight = 0; if (normalCacheId != null && normalCacheId[layer] != null) { - normalCacheHeight = normalCacheId[layer].length; - } - - int blendedCacheHeight = 0; + normalCacheHeight = normalCacheId[layer].length; + } + + int blendedCacheHeight = 0; if (blendedCacheId != null && blendedCacheId[layer] != null) { - blendedCacheHeight = blendedCacheId[layer].length; - } - - return Math.max(normalCacheHeight, blendedCacheHeight); + blendedCacheHeight = blendedCacheId[layer].length; + } + + return Math.max(normalCacheHeight, blendedCacheHeight); } public Matrix4 getProjectionMatrix () { @@ -425,50 +396,38 @@ public Matrix4 getTransformMatrix () { return cache.getTransformMatrix(); } - /** - * Computes the Tiled Map row given a Y coordinate in units - * @param worldY the Y coordinate in units - * */ + /** Computes the Tiled Map row given a Y coordinate in units + * @param worldY the Y coordinate in units */ public int getRow (int worldY) { return (int)(worldY / unitsPerTileY); } - /** - * Computes the Tiled Map column given an X coordinate in units - * @param worldX the X coordinate in units - * */ + /** Computes the Tiled Map column given an X coordinate in units + * @param worldX the X coordinate in units */ public int getCol (int worldX) { return (int)(worldX / unitsPerTileX); } - /** - * Returns the initial drawn block row, for debugging purposes. Use this along with {@link TileMapRenderer#getLastRow()} to - * compute the number of rows drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. - * */ + /** Returns the initial drawn block row, for debugging purposes. Use this along with {@link TileMapRenderer#getLastRow()} to + * compute the number of rows drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. */ public int getInitialRow () { return initialRow; } - /** - * Returns the initial drawn block column, for debugging purposes. Use this along with {@link TileMapRenderer#getLastCol()} to - * compute the number of columns drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. - * */ + /** Returns the initial drawn block column, for debugging purposes. Use this along with {@link TileMapRenderer#getLastCol()} to + * compute the number of columns drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. */ public int getInitialCol () { return initialCol; } - /** - * Returns the final drawn block row, for debugging purposes. Use this along with {@link TileMapRenderer#getInitialRow()} to - * compute the number of rows drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. - * */ + /** Returns the final drawn block row, for debugging purposes. Use this along with {@link TileMapRenderer#getInitialRow()} to + * compute the number of rows drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. */ public int getLastRow () { return lastRow; } - /** - * Returns the final drawn block column, for debugging purposes. Use this along with {@link TileMapRenderer#getInitialCol()} to - * compute the number of columns drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. - * */ + /** Returns the final drawn block column, for debugging purposes. Use this along with {@link TileMapRenderer#getInitialCol()} to + * compute the number of columns drawn in the last call to {@link TileMapRenderer#render(float, float, float, float, int[])}. */ public int getLastCol () { return lastCol; } @@ -498,10 +457,8 @@ private static int parseIntWithDefault (String string, int defaultValue) { } } - /** - * Releases all resources held by this TiledMapRenderer. - * */ - @Override + /** Releases all resources held by this TiledMapRenderer. */ + @Override public void dispose () { cache.dispose(); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileSet.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileSet.java index 4869c983e54..60a84c1b22b 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileSet.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TileSet.java @@ -13,10 +13,8 @@ package com.badlogic.gdx.graphics.g2d.tiled; -/** - * Contains a Tiled Map tile set - * @author David Fraska - * */ +/** Contains a Tiled Map tile set + * @author David Fraska */ public class TileSet { public int firstgid; public int tileWidth; @@ -25,16 +23,12 @@ public class TileSet { public String imageName; public String name; - /** - * Contains a Tiled Map tile set - */ + /** Contains a Tiled Map tile set */ protected TileSet () { } - /** - * Copy constructor - * @param set The set to be copied - */ + /** Copy constructor + * @param set The set to be copied */ protected TileSet (TileSet set) { this.firstgid = set.firstgid; this.tileWidth = set.tileWidth; diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLayer.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLayer.java index b945ee89404..2240340d7c5 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLayer.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLayer.java @@ -13,37 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d.tiled; import java.util.HashMap; -/** - * Contains Tiled map layer information - * @author David Fraska - */ +/** Contains Tiled map layer information + * @author David Fraska */ public class TiledLayer { public String name; /** Contains the layer properties with a key of the property name. */ public HashMap properties = new HashMap(0); - //public final int width, height; + // public final int width, height; /** Contains the tile ids, addressed as [row][column]. */ public int[][] tiles; - /** - * Constructs a new TiledLayer, used by {@link TiledLoader} - * */ + /** Constructs a new TiledLayer, used by {@link TiledLoader} */ TiledLayer () { } - - public int getWidth(){ - if(tiles[0] == null) return 0; + + public int getWidth () { + if (tiles[0] == null) return 0; return tiles[0].length; } - - public int getHeight(){ + + public int getHeight () { return tiles.length; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java index bd8a96e8f0a..1970e9a7a55 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java @@ -27,16 +27,12 @@ import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Xml; -/** - * Loads a Tiled Map from a tmx file - * @author David Fraska - * */ +/** Loads a Tiled Map from a tmx file + * @author David Fraska */ public class TiledLoader { - /** - * Loads a Tiled Map from a tmx file - * @param tmxFile the map's tmx file - * */ + /** Loads a Tiled Map from a tmx file + * @param tmxFile the map's tmx file */ public static TiledMap createMap (FileHandle tmxFile) { final TiledMap map; @@ -68,7 +64,8 @@ class Property { int dataCounter = 0, row, col; - @Override protected void open (String name) { + @Override + protected void open (String name) { currBranch.push(name); if ("layer".equals(name)) { @@ -104,7 +101,8 @@ class Property { } } - @Override protected void attribute (String name, String value) { + @Override + protected void attribute (String name, String value) { String element = currBranch.peek(); if ("layer".equals(element)) { @@ -245,10 +243,9 @@ class Property { if ("gid".equals(name)) { col = dataCounter % currLayerWidth; row = dataCounter / currLayerWidth; - if(row < currLayerHeight){ + if (row < currLayerHeight) { currLayer.tiles[row][col] = Integer.parseInt(value); - } - else{ + } else { Gdx.app.log("TiledLoader", "Warning: extra XML gid values ignored! Your map is likely corrupt!"); } dataCounter++; @@ -274,13 +271,15 @@ class Property { } } - @Override protected void text (String text) { + @Override + protected void text (String text) { if (awaitingData) { dataString = dataString.concat(text); } } - @Override protected void close () { + @Override + protected void close () { String element = currBranch.pop(); if ("layer".equals(element)) { @@ -318,7 +317,7 @@ class Property { // decode and uncompress the data if ("base64".equals(encoding)) { if (dataString == null | "".equals(dataString.trim())) return; - + data = Base64Coder.decode(dataString.trim()); if ("gzip".equals(compression)) { diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledMap.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledMap.java index 1d3caeb8135..c398346a718 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledMap.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledMap.java @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d.tiled; import java.util.ArrayList; import java.util.HashMap; import com.badlogic.gdx.files.FileHandle; -import com.badlogic.gdx.utils.Disposable; -/** - * Contains information from a Tiled Map. Use {@link TiledLoader#createMap(FileHandle)} to fill it. - * @author David Fraska - * */ +/** Contains information from a Tiled Map. Use {@link TiledLoader#createMap(FileHandle)} to fill it. + * @author David Fraska */ public class TiledMap { public ArrayList layers = new ArrayList(4); public ArrayList objectGroups = new ArrayList(1); public ArrayList tileSets = new ArrayList(5); - + /** Stores the map properties with a key of the property name. */ public HashMap properties = new HashMap(2); private ArrayList tileProperties = new ArrayList(0); @@ -38,12 +36,10 @@ public class TiledMap { public String orientation; public int width, height, tileWidth, tileHeight; - /** - * Sets a tile's property. Typically only called by {@link TiledLoader#createMap(FileHandle)} + /** Sets a tile's property. Typically only called by {@link TiledLoader#createMap(FileHandle)} * @param id The tile's id * @param name The property name - * @param value The property value - * */ + * @param value The property value */ public void setTileProperty (int id, String name, String value) { for (TileProperty tp : tileProperties) { if (tp.id == id) { @@ -59,12 +55,10 @@ public void setTileProperty (int id, String name, String value) { tileProperties.add(tempProperty); } - /** - * Gets a tile's property. + /** Gets a tile's property. * @param id The tile's id * @param name The property name - * @return The property value - * */ + * @return The property value */ public String getTileProperty (int id, String name) { for (TileProperty tp : tileProperties) { if (tp.id == id) { diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObject.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObject.java index 462db394634..3e0be893349 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObject.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObject.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d.tiled; import java.util.HashMap; -/** - * Contains a Tiled map object - * @author David Fraska - */ +/** Contains a Tiled map object + * @author David Fraska */ public class TiledObject { public String name, type; public int x, y, width = 0, height = 0, gid = 0; diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObjectGroup.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObjectGroup.java index fdd6d66bb66..f5b82b16ddf 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObjectGroup.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledObjectGroup.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g2d.tiled; import java.util.ArrayList; import java.util.HashMap; -/** - * Contains a Tiled map object group/layer - * @author David Fraska - * */ +/** Contains a Tiled map object group/layer + * @author David Fraska */ public class TiledObjectGroup { public int width, height; public String name; diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/Animation.java b/gdx/src/com/badlogic/gdx/graphics/g3d/Animation.java index 74c81a76f88..c04c0e6cac6 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/Animation.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/Animation.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d; -/** - * Abstract class for an animation. +/** Abstract class for an animation. * - * @author Dave Clayton - * - */ + * @author Dave Clayton */ public abstract class Animation { - public abstract float getLength(); + public abstract float getLength (); - public abstract int getNumFrames(); + public abstract int getNumFrames (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/Animator.java b/gdx/src/com/badlogic/gdx/graphics/g3d/Animator.java index 85c494018b1..38c09391f52 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/Animator.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/Animator.java @@ -13,15 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d; -/** - * Abstract class for a single-track animation controller. Keeps track of the animation position and invokes interpolation on +/** Abstract class for a single-track animation controller. Keeps track of the animation position and invokes interpolation on * concrete classes. * - * @author Dave Clayton - * - */ + * @author Dave Clayton */ public abstract class Animator { protected float mAnimPos = 0.f; protected float mAnimLen = 0.f; @@ -30,24 +28,17 @@ public abstract class Animator { protected int mNextFrameIdx = -1; protected float mFrameDelta = 0.f; protected Animation mCurrentAnim = null; - - public enum WrapMode - { - Loop, - Clamp, - //PingPong, //TODO + + public enum WrapMode { + Loop, Clamp, + // PingPong, //TODO SingleFrame, } - - /** - * Sets the currently playing {@link Animation}. - * @param anim - * The animation to play. - * @param mode - * The animation's {@link WrapMode}. - */ - public void setAnimation(Animation anim, WrapMode mode) - { + + /** Sets the currently playing {@link Animation}. + * @param anim The animation to play. + * @param mode The animation's {@link WrapMode}. */ + public void setAnimation (Animation anim, WrapMode mode) { mCurrentAnim = anim; mWrapMode = mode; @@ -55,97 +46,73 @@ public void setAnimation(Animation anim, WrapMode mode) mCurrentFrameIdx = -1; mNextFrameIdx = -1; - if(mCurrentAnim != null) - { - mAnimLen = mCurrentAnim.getLength(); + if (mCurrentAnim != null) { + mAnimLen = mCurrentAnim.getLength(); } } - - /** - * Gets the currently playing {@link Animation}. - * @return the current animation. - */ - public Animation getCurrentAnimation() - { + + /** Gets the currently playing {@link Animation}. + * @return the current animation. */ + public Animation getCurrentAnimation () { return mCurrentAnim; } - - /** - * Gets the current animation {@link WrapMode}. - * @return the current wrapmode. - */ - public WrapMode getCurrentWrapMode() - { + + /** Gets the current animation {@link WrapMode}. + * @return the current wrapmode. */ + public WrapMode getCurrentWrapMode () { return mWrapMode; } - /** - * Updates the controller. - * @param dt - * Delta time since last frame. - */ - public void update(float dt) - { - if(mCurrentAnim != null) - { - if(mWrapMode != WrapMode.SingleFrame) - { + /** Updates the controller. + * @param dt Delta time since last frame. */ + public void update (float dt) { + if (mCurrentAnim != null) { + if (mWrapMode != WrapMode.SingleFrame) { mAnimPos += dt; - if(mAnimPos > mAnimLen) - { - if(mWrapMode == WrapMode.Loop) - { + if (mAnimPos > mAnimLen) { + if (mWrapMode == WrapMode.Loop) { mAnimPos = 0.f; - } - else if(mWrapMode == WrapMode.Clamp) - { + } else if (mWrapMode == WrapMode.Clamp) { mAnimPos = mAnimLen; } } } // select the frames - float animPos = mAnimPos/mAnimLen; + float animPos = mAnimPos / mAnimLen; int numFrames = mCurrentAnim.getNumFrames(); - - int currentFrameIdx = Math.min(numFrames-1, (int)(animPos*(float)numFrames)); - - if(currentFrameIdx != mCurrentFrameIdx) - { - if(currentFrameIdx < numFrames-1) - { - mNextFrameIdx = currentFrameIdx+1; - } - else - { - switch(mWrapMode) - { + + int currentFrameIdx = Math.min(numFrames - 1, (int)(animPos * (float)numFrames)); + + if (currentFrameIdx != mCurrentFrameIdx) { + if (currentFrameIdx < numFrames - 1) { + mNextFrameIdx = currentFrameIdx + 1; + } else { + switch (mWrapMode) { case Loop: case SingleFrame: - mNextFrameIdx = 0; break; + mNextFrameIdx = 0; + break; case Clamp: - mNextFrameIdx = currentFrameIdx; break; + mNextFrameIdx = currentFrameIdx; + break; } } - + mFrameDelta = 0.f; mCurrentFrameIdx = currentFrameIdx; } mFrameDelta += dt; - + setInterpolationFrames(); - + interpolate(); } } - - /** - * Implementations should set the 'current' and 'next' frames of animation that will be interpolated. - */ - protected abstract void setInterpolationFrames(); - - /** - * Implementations should interpolate between the 'current' and 'next' frames of animation. - */ - protected abstract void interpolate(); + + /** Implementations should set the 'current' and 'next' frames of animation that will be interpolated. */ + protected abstract void setInterpolationFrames (); + + /** Implementations should interpolate between the 'current' and 'next' frames of animation. */ + protected abstract void interpolate (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/Material.java b/gdx/src/com/badlogic/gdx/graphics/g3d/Material.java index 4ae8b7012a4..4312dcc61aa 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/Material.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/Material.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d; import java.io.DataInputStream; @@ -25,13 +26,10 @@ import com.badlogic.gdx.graphics.TextureRef; import com.badlogic.gdx.graphics.glutils.ShaderProgram; -/** - * Holds material data. The data contains texture/shader information and material properties for lighting. Currently the material +/** Holds material data. The data contains texture/shader information and material properties for lighting. Currently the material * also supports partial serialization of its data.
        * - * @author Dave Clayton - * - */ + * @author Dave Clayton */ public class Material { public String Name; public ShaderProgram Shader; @@ -44,69 +42,52 @@ public class Material { public int BlendSourceFactor = 0; public int BlendDestFactor = 0; private static final float tmp[] = new float[4]; - - /** - * Constructs a new material. - * @param name - * The material's name. - */ - public Material(String name) - { + + /** Constructs a new material. + * @param name The material's name. */ + public Material (String name) { Name = name; } - - private void setTmpArray(float r, float g, float b, float a) { + + private void setTmpArray (float r, float g, float b, float a) { tmp[0] = r; tmp[1] = g; tmp[2] = b; tmp[3] = a; } - - /** - * Sends the material properties to the OpenGL state. - * @param face - * Which faces this applies to (e.g. GL10.GL_FRONT). - */ - public void set(int face) - { - //TODO: should probably load shaderprogram here if we're using them + + /** Sends the material properties to the OpenGL state. + * @param face Which faces this applies to (e.g. GL10.GL_FRONT). */ + public void set (int face) { + // TODO: should probably load shaderprogram here if we're using them GL10 gl = Gdx.graphics.getGL10(); - //TODO: caching of last material set using statics to see if we need to set material states again - if(Ambient != null) - { + // TODO: caching of last material set using statics to see if we need to set material states again + if (Ambient != null) { setTmpArray(Ambient.r, Ambient.g, Ambient.b, Ambient.a); gl.glMaterialfv(face, GL10.GL_AMBIENT, tmp, 0); } - if(Diffuse != null) - { + if (Diffuse != null) { setTmpArray(Diffuse.r, Diffuse.g, Diffuse.b, Diffuse.a); gl.glMaterialfv(face, GL10.GL_DIFFUSE, tmp, 0); } - if(BlendSourceFactor > 0) - { + if (BlendSourceFactor > 0) { gl.glBlendFunc(BlendSourceFactor, BlendDestFactor); gl.glEnable(GL10.GL_BLEND); - } - else - { + } else { gl.glDisable(GL10.GL_BLEND); } } - - /** - * Serialization. Experimental. + + /** Serialization. Experimental. * @param i The DataInputStream to serialize from. * @return whether serialization succeeded. - * @throws IOException - */ - public boolean read(DataInputStream i) throws IOException - { + * @throws IOException */ + public boolean read (DataInputStream i) throws IOException { Name = i.readUTF(); TexturePath = i.readUTF(); boolean hasAmbient = i.readBoolean(); - if(hasAmbient) - { + if (hasAmbient) { float r = i.readFloat(); float g = i.readFloat(); float b = i.readFloat(); @@ -114,8 +95,7 @@ public boolean read(DataInputStream i) throws IOException Ambient = new Color(r, g, b, a); } boolean hasDiffuse = i.readBoolean(); - if(hasDiffuse) - { + if (hasDiffuse) { float r = i.readFloat(); float g = i.readFloat(); float b = i.readFloat(); @@ -126,31 +106,26 @@ public boolean read(DataInputStream i) throws IOException BlendDestFactor = i.readInt(); return true; } - - /** - * Serialization. Experimental. + + /** Serialization. Experimental. * @param o The DataOutputStream to serialize to. * @return Whether serialization succeeded. - * @throws IOException - */ - public boolean write(DataOutputStream o) throws IOException - { - //TODO: serialize out shader + * @throws IOException */ + public boolean write (DataOutputStream o) throws IOException { + // TODO: serialize out shader o.writeUTF(Name); // process path - String filename = Texture.Name.substring(Texture.Name.lastIndexOf("\\")+1); + String filename = Texture.Name.substring(Texture.Name.lastIndexOf("\\") + 1); o.writeUTF(filename); o.writeBoolean(Ambient != null); - if(Ambient != null) - { + if (Ambient != null) { o.writeFloat(Ambient.r); o.writeFloat(Ambient.g); o.writeFloat(Ambient.b); o.writeFloat(Ambient.a); } o.writeBoolean(Diffuse != null); - if(Diffuse != null) - { + if (Diffuse != null) { o.writeFloat(Diffuse.r); o.writeFloat(Diffuse.g); o.writeFloat(Diffuse.b); diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/CameraGroupStrategy.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/CameraGroupStrategy.java index 42e30fca5c9..09f40e845f4 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/CameraGroupStrategy.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/CameraGroupStrategy.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.decals; import java.util.Comparator; @@ -10,12 +11,10 @@ import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Pool; -/** - *

        - * Minimalistic grouping strategy that splits decals into opaque and transparent ones enabling and disabling blending - * as needed. Opaque decals are rendered first (decal color is ignored in opacity check).
        - * Use this strategy only if the vast majority of your decals are opaque and the few transparent ones are unlikely - * to overlap. +/**

        + * Minimalistic grouping strategy that splits decals into opaque and transparent ones enabling and disabling blending as needed. + * Opaque decals are rendered first (decal color is ignored in opacity check).
        + * Use this strategy only if the vast majority of your decals are opaque and the few transparent ones are unlikely to overlap. *

        *

        * Can produce invisible artifacts when transparent decals overlap each other. @@ -24,29 +23,42 @@ * States (* = any, EV = entry value - same as value before flush):
        * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * *
        expectsexits onexpectsexits on
        glDepthMasktrueEVglDepthMasktrueEV
        GL_DEPTH_TESTenabledEVGL_DEPTH_TESTenabledEV
        glDepthFuncGL_LESS | GL_LEQUALEVglDepthFuncGL_LESS | GL_LEQUALEV
        GL_BLENDdisabledEV | disabledGL_BLENDdisabledEV | disabled
        glBlendFunc**glBlendFunc**
        GL_TEXTURE_2D*disabledGL_TEXTURE_2D*disabled
        - *

        - */ + *

        */ public class CameraGroupStrategy implements GroupStrategy { private static final int GROUP_OPAQUE = 0; private static final int GROUP_BLEND = 1; @@ -59,7 +71,7 @@ protected Array newObject () { }; Array> usedArrays = new Array>(); ObjectMap> materialGroups = new ObjectMap>(); - + Camera camera; ShaderProgram shader; private final Comparator cameraSorter = new Comparator() { @@ -70,35 +82,35 @@ public int compare (Decal o1, Decal o2) { return (int)Math.signum(dist2 - dist1); } }; - - public CameraGroupStrategy(Camera camera) { + + public CameraGroupStrategy (Camera camera) { this.camera = camera; createDefaultShader(); } - - public void setCamera(Camera camera) { + + public void setCamera (Camera camera) { this.camera = camera; } - - public Camera getCamera() { + + public Camera getCamera () { return camera; } - + @Override - public int decideGroup(Decal decal) { + public int decideGroup (Decal decal) { return decal.getMaterial().isOpaque() ? GROUP_OPAQUE : GROUP_BLEND; } @Override - public void beforeGroup(int group, Array contents) { - if(group == GROUP_BLEND) { + public void beforeGroup (int group, Array contents) { + if (group == GROUP_BLEND) { Gdx.gl.glEnable(GL10.GL_BLEND); contents.sort(cameraSorter); } else { - for(int i = 0, n = contents.size; i < n; i++) { + for (int i = 0, n = contents.size; i < n; i++) { Decal decal = contents.get(i); Array materialGroup = materialGroups.get(decal.material); - if(materialGroup == null) { + if (materialGroup == null) { materialGroup = arrayPool.obtain(); materialGroup.clear(); usedArrays.add(materialGroup); @@ -106,12 +118,12 @@ public void beforeGroup(int group, Array contents) { } materialGroup.add(decal); } - + contents.clear(); - for(Array materialGroup: materialGroups.values()) { + for (Array materialGroup : materialGroups.values()) { contents.addAll(materialGroup); } - + materialGroups.clear(); arrayPool.free(usedArrays); usedArrays.clear(); @@ -119,16 +131,16 @@ public void beforeGroup(int group, Array contents) { } @Override - public void afterGroup(int group) { - if(group == GROUP_BLEND) { + public void afterGroup (int group) { + if (group == GROUP_BLEND) { Gdx.gl.glDisable(GL10.GL_BLEND); } } @Override - public void beforeGroups() { + public void beforeGroups () { Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); - if(shader != null) { + if (shader != null) { shader.begin(); shader.setUniformMatrix("u_projectionViewMatrix", camera.combined); shader.setUniformi("u_texture", 0); @@ -141,15 +153,15 @@ public void beforeGroups() { } @Override - public void afterGroups() { - if(shader != null) { + public void afterGroups () { + if (shader != null) { shader.end(); } Gdx.gl.glDisable(GL10.GL_TEXTURE_2D); } - - private void createDefaultShader() { - if(Gdx.graphics.isGL20Available()) { + + private void createDefaultShader () { + if (Gdx.graphics.isGL20Available()) { String vertexShader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" // + "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" // + "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" // @@ -173,7 +185,7 @@ private void createDefaultShader() { + "{\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()); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/Decal.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/Decal.java index f7084cbf323..22ac87cbe01 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/Decal.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/Decal.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.g3d.decals; import com.badlogic.gdx.graphics.GL10; @@ -6,35 +7,24 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; -/** - *

        - * Represents a sprite in 3d space. Typical 3d transformations such as translation, rotation and scaling are supported. - * The position includes a z component other than setting the depth no manual layering has to be performed, correct - * overlay is guaranteed by using the depth buffer. +/**

        + * Represents a sprite in 3d space. Typical 3d transformations such as translation, rotation and scaling are supported. The + * position includes a z component other than setting the depth no manual layering has to be performed, correct overlay is + * guaranteed by using the depth buffer. *

        - * Decals are handled by the {@link DecalBatch}. - */ + * Decals are handled by the {@link DecalBatch}. */ public class Decal { - //3(x,y,z) + 1(color) + 2(u,v) - /** - * Size of a decal vertex in floats - */ + // 3(x,y,z) + 1(color) + 2(u,v) + /** Size of a decal vertex in floats */ private static final int VERTEX_SIZE = 3 + 1 + 2; - /** - * Size of the decal in floats. - * It takes a float[SIZE] to hold the decal. - */ + /** Size of the decal in floats. It takes a float[SIZE] to hold the decal. */ public static final int SIZE = 4 * VERTEX_SIZE; - - /** - * Temporary vector for various calculations. - */ + + /** Temporary vector for various calculations. */ private static Vector3 tmp = new Vector3(); private static Vector3 tmp2 = new Vector3(); - - /** - * Set a multipurpose value which can be queried and used for things like group identification. - */ + + /** Set a multipurpose value which can be queried and used for things like group identification. */ public int value; protected float[] vertices = new float[SIZE]; @@ -42,29 +32,25 @@ public class Decal { protected Quaternion rotation = Quaternion.idt(); protected Vector2 scale = new Vector2(1, 1); - /** - * The transformation offset can be used to change the pivot point for rotation and scaling. - * By default the pivot is the middle of the decal. - */ + /** The transformation offset can be used to change the pivot point for rotation and scaling. By default the pivot is the middle + * of the decal. */ public Vector2 transformationOffset = null; protected Vector2 dimensions = new Vector2(); protected DecalMaterial material = new DecalMaterial(); protected boolean updated = false; - protected Decal() { + protected Decal () { } - /** - * Sets the color of all four vertices to the specified color - * + /** Sets the color of all four vertices to the specified color + * * @param r Red component * @param g Green component * @param b Blue component - * @param a Alpha component - */ - public void setColor(float r, float g, float b, float a) { - int intBits = ((int) (255 * a) << 24) | ((int) (255 * b) << 16) | ((int) (255 * g) << 8) | ((int) (255 * r)); + * @param a Alpha component */ + public void setColor (float r, float g, float b, float a) { + int intBits = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r)); float color = Float.intBitsToFloat(intBits & 0xfeffffff); vertices[C1] = color; vertices[C2] = color; @@ -72,332 +58,258 @@ public void setColor(float r, float g, float b, float a) { vertices[C4] = color; } - /** - * Rotates along local X axis by the specified angle - * - * @param angle Angle in degrees to rotate by - */ - public void rotateX(float angle) { + /** Rotates along local X axis by the specified angle + * + * @param angle Angle in degrees to rotate by */ + public void rotateX (float angle) { rotator.set(X_AXIS, angle); rotation.mul(rotator); updated = false; } - /** - * Rotates along local Y axis by the specified angle - * - * @param angle Angle in degrees to rotate by - */ - public void rotateY(float angle) { + /** Rotates along local Y axis by the specified angle + * + * @param angle Angle in degrees to rotate by */ + public void rotateY (float angle) { rotator.set(Y_AXIS, angle); rotation.mul(rotator); updated = false; } - /** - * Rotates along local Z axis by the specified angle - * - * @param angle Angle in degrees to rotate by - */ - public void rotateZ(float angle) { + /** Rotates along local Z axis by the specified angle + * + * @param angle Angle in degrees to rotate by */ + public void rotateZ (float angle) { rotator.set(Z_AXIS, angle); rotation.mul(rotator); updated = false; } - - /** - * Sets the rotation of this decal based on the (normalized) - * direction and up vector. + + /** Sets the rotation of this decal based on the (normalized) direction and up vector. * @param dir the direction vector - * @param up the up vector - */ - public void setRotation(Vector3 dir, Vector3 up) { + * @param up the up vector */ + public void setRotation (Vector3 dir, Vector3 up) { tmp.set(up).crs(dir).nor(); tmp2.set(dir).crs(tmp).nor(); - rotation.setFromAxes(tmp.x, tmp.y, tmp.z, tmp2.x, tmp2.y, tmp2.z, dir.x, dir.y, dir.z); + rotation.setFromAxes(tmp.x, tmp.y, tmp.z, tmp2.x, tmp2.y, tmp2.z, dir.x, dir.y, dir.z); updated = false; } - /** - * Returns the rotation. The returned quaternion should under no circumstances be modified. - * - * @return Quaternion representing the rotation - */ - public Quaternion getRotation() { + /** Returns the rotation. The returned quaternion should under no circumstances be modified. + * + * @return Quaternion representing the rotation */ + public Quaternion getRotation () { return rotation; } - /** - * Moves by the specified amount of units along the x axis - * - * @param units Units to move the decal - */ - public void translateX(float units) { + /** Moves by the specified amount of units along the x axis + * + * @param units Units to move the decal */ + public void translateX (float units) { this.position.x += units; updated = false; } - /** - * Sets the position on the x axis - * - * @param x Position to locate the decal at - */ - public void setX(float x) { + /** Sets the position on the x axis + * + * @param x Position to locate the decal at */ + public void setX (float x) { this.position.x = x; updated = false; } - /** - * @return position on the x axis - */ - public float getX() { + /** @return position on the x axis */ + public float getX () { return this.position.x; } - /** - * Moves by the specified amount of units along the y axis - * - * @param units Units to move the decal - */ - public void translateY(float units) { + /** Moves by the specified amount of units along the y axis + * + * @param units Units to move the decal */ + public void translateY (float units) { this.position.y += units; updated = false; } - /** - * Sets the position on the y axis - * - * @param y Position to locate the decal at - */ - public void setY(float y) { + /** Sets the position on the y axis + * + * @param y Position to locate the decal at */ + public void setY (float y) { this.position.y = y; updated = false; } - /** - * @return position on the y axis - */ - public float getY() { + /** @return position on the y axis */ + public float getY () { return this.position.y; } - /** - * Moves by the specified amount of units along the z axis - * - * @param units Units to move the decal - */ - public void translateZ(float units) { + /** Moves by the specified amount of units along the z axis + * + * @param units Units to move the decal */ + public void translateZ (float units) { this.position.z += units; updated = false; } - /** - * Sets the position on the z axis - * - * @param z Position to locate the decal at - */ - public void setZ(float z) { + /** Sets the position on the z axis + * + * @param z Position to locate the decal at */ + public void setZ (float z) { this.position.z = z; updated = false; } - /** - * @return position on the z axis - */ - public float getZ() { + /** @return position on the z axis */ + public float getZ () { return this.position.z; } - /** - * Translates by the specified amount of units - * + /** Translates by the specified amount of units + * * @param x Units to move along the x axis * @param y Units to move along the y axis - * @param z Units to move along the z axis - */ - public void translate(float x, float y, float z) { + * @param z Units to move along the z axis */ + public void translate (float x, float y, float z) { this.position.add(x, y, z); updated = false; } - /** - * Sets the position to the given world coordinates - * + /** Sets the position to the given world coordinates + * * @param x X position * @param y Y Position - * @param z Z Position - */ - public void setPosition(float x, float y, float z) { + * @param z Z Position */ + public void setPosition (float x, float y, float z) { this.position.set(x, y, z); updated = false; } - /** - * Returns the position of this decal. The returned vector should under no circumstances be modified. - * - * @return vector representing the position - */ - public Vector3 getPosition() { + /** Returns the position of this decal. The returned vector should under no circumstances be modified. + * + * @return vector representing the position */ + public Vector3 getPosition () { return position; } - /** - * Sets scale along the x axis - * - * @param scale New scale along x axis - */ - public void setScaleX(float scale) { + /** Sets scale along the x axis + * + * @param scale New scale along x axis */ + public void setScaleX (float scale) { this.scale.x = scale; updated = false; } - /** - * @return Scale on the x axis - */ - public float getScaleX() { + /** @return Scale on the x axis */ + public float getScaleX () { return this.scale.x; } - /** - * Sets scale along the y axis - * - * @param scale New scale along y axis - */ - public void setScaleY(float scale) { + /** Sets scale along the y axis + * + * @param scale New scale along y axis */ + public void setScaleY (float scale) { this.scale.y += scale; updated = false; } - /** - * @return Scale on the y axis - */ - public float getScaleY() { + /** @return Scale on the y axis */ + public float getScaleY () { return this.scale.y; } - /** - * Sets scale along both the x and y axis - * + /** Sets scale along both the x and y axis + * * @param scaleX Scale on the x axis - * @param scaleY Scale on the y axis - */ - public void setScale(float scaleX, float scaleY) { + * @param scaleY Scale on the y axis */ + public void setScale (float scaleX, float scaleY) { this.scale.set(scaleX, scaleY); updated = false; } - /** - * Sets scale along both the x and y axis - * - * @param scale New scale - */ - public void setScale(float scale) { + /** Sets scale along both the x and y axis + * + * @param scale New scale */ + public void setScale (float scale) { this.scale.set(scale, scale); updated = false; } - /** - * Sets the width in world units - * - * @param width Width in world units - */ - public void setWidth(float width) { + /** Sets the width in world units + * + * @param width Width in world units */ + public void setWidth (float width) { this.dimensions.x = width; updated = false; } - /** - * @return width in world units - */ - public float getWidth() { + /** @return width in world units */ + public float getWidth () { return this.dimensions.x; } - /** - * Sets the height in world units - * - * @param height Height in world units - */ - public void setHeight(float height) { + /** Sets the height in world units + * + * @param height Height in world units */ + public void setHeight (float height) { this.dimensions.y += height; updated = false; } - /** - * @return height in world units - */ - public float getHeight() { + /** @return height in world units */ + public float getHeight () { return dimensions.y; } - /** - * Sets the width and height in world units - * - * @param width Width in world units - * @param height Height in world units - */ - public void setDimensions(float width, float height) { + /** Sets the width and height in world units + * + * @param width Width in world units + * @param height Height in world units */ + public void setDimensions (float width, float height) { dimensions.set(width, height); updated = false; } - /** - * Returns the vertices backing this sprite.
        + /** Returns the vertices backing this sprite.
        * The returned value should under no circumstances be modified. - * - * @return vertex array backing the decal - */ - public float[] getVertices() { + * + * @return vertex array backing the decal */ + public float[] getVertices () { return vertices; } - /** - * Recalculates vertices array if it grew out of sync with the properties (position, ..) - */ - protected void update() { - if(!updated) { + /** Recalculates vertices array if it grew out of sync with the properties (position, ..) */ + protected void update () { + if (!updated) { resetVertices(); transformVertices(); } } - /** - * Transforms the position component of the vertices using properties such as position, scale, etc. - */ - protected void transformVertices() { - /** - * It would be possible to also load the x,y,z into a Vector3 and apply all the transformations using - * already existing methods. Especially the quaternion rotation already exists in the Quaternion class, - * it then would look like this: + /** Transforms the position component of the vertices using properties such as position, scale, etc. */ + protected void transformVertices () { + /** It would be possible to also load the x,y,z into a Vector3 and apply all the transformations using already existing + * methods. Especially the quaternion rotation already exists in the Quaternion class, it then would look like this: * ---------------------------------------------------------------------------------------------------- - * v3.set(vertices[xIndex] * scale.x, vertices[yIndex] * scale.y, vertices[zIndex]); - * rotation.transform(v3); - * v3.add(position); - * vertices[xIndex] = v3.x; - * vertices[yIndex] = v3.y; - * vertices[zIndex] = v3.z; - * ---------------------------------------------------------------------------------------------------- - * However, a half ass benchmark with dozens of thousands decals showed that doing it "by hand", - * as done here, is about 10% faster. So while duplicate code should be avoided for maintenance - * reasons etc. the performance gain is worth it. The math doesn't change. - */ + * v3.set(vertices[xIndex] * scale.x, vertices[yIndex] * scale.y, vertices[zIndex]); rotation.transform(v3); + * v3.add(position); vertices[xIndex] = v3.x; vertices[yIndex] = v3.y; vertices[zIndex] = v3.z; + * ---------------------------------------------------------------------------------------------------- However, a half ass + * benchmark with dozens of thousands decals showed that doing it "by hand", as done here, is about 10% faster. So while + * duplicate code should be avoided for maintenance reasons etc. the performance gain is worth it. The math doesn't change. */ float x, y, z, w; float tx, ty; - if(transformationOffset != null) { + if (transformationOffset != null) { tx = -transformationOffset.x; ty = -transformationOffset.y; - } - else { + } else { tx = ty = 0; } - /** - * Transform the first vertex - */ + /** Transform the first vertex */ // first apply the scale to the vector x = (vertices[X1] + tx) * scale.x; y = (vertices[Y1] + ty) * scale.y; z = vertices[Z1]; - //then transform the vector using the rotation quaternion + // then transform the vector using the rotation quaternion vertices[X1] = rotation.w * x + rotation.y * z - rotation.z * y; vertices[Y1] = rotation.w * y + rotation.z * x - rotation.x * z; vertices[Z1] = rotation.w * z + rotation.x * y - rotation.y * x; @@ -410,18 +322,16 @@ protected void transformVertices() { vertices[Y1] = w * rotation.y + y * rotation.w + z * rotation.x - x * rotation.z; vertices[Z1] = w * rotation.z + z * rotation.w + x * rotation.y - y * rotation.x; rotation.conjugate(); // <- don't forget to conjugate the rotation back to normal - //finally translate the vector according to position + // finally translate the vector according to position vertices[X1] += position.x - tx; vertices[Y1] += position.y - ty; vertices[Z1] += position.z; - /** - * Transform the second vertex - */ + /** Transform the second vertex */ // first apply the scale to the vector x = (vertices[X2] + tx) * scale.x; y = (vertices[Y2] + ty) * scale.y; z = vertices[Z2]; - //then transform the vector using the rotation quaternion + // then transform the vector using the rotation quaternion vertices[X2] = rotation.w * x + rotation.y * z - rotation.z * y; vertices[Y2] = rotation.w * y + rotation.z * x - rotation.x * z; vertices[Z2] = rotation.w * z + rotation.x * y - rotation.y * x; @@ -434,18 +344,16 @@ protected void transformVertices() { vertices[Y2] = w * rotation.y + y * rotation.w + z * rotation.x - x * rotation.z; vertices[Z2] = w * rotation.z + z * rotation.w + x * rotation.y - y * rotation.x; rotation.conjugate(); // <- don't forget to conjugate the rotation back to normal - //finally translate the vector according to position + // finally translate the vector according to position vertices[X2] += position.x - tx; vertices[Y2] += position.y - ty; vertices[Z2] += position.z; - /** - * Transform the third vertex - */ + /** Transform the third vertex */ // first apply the scale to the vector x = (vertices[X3] + tx) * scale.x; y = (vertices[Y3] + ty) * scale.y; z = vertices[Z3]; - //then transform the vector using the rotation quaternion + // then transform the vector using the rotation quaternion vertices[X3] = rotation.w * x + rotation.y * z - rotation.z * y; vertices[Y3] = rotation.w * y + rotation.z * x - rotation.x * z; vertices[Z3] = rotation.w * z + rotation.x * y - rotation.y * x; @@ -458,18 +366,16 @@ protected void transformVertices() { vertices[Y3] = w * rotation.y + y * rotation.w + z * rotation.x - x * rotation.z; vertices[Z3] = w * rotation.z + z * rotation.w + x * rotation.y - y * rotation.x; rotation.conjugate(); // <- don't forget to conjugate the rotation back to normal - //finally translate the vector according to position + // finally translate the vector according to position vertices[X3] += position.x - tx; vertices[Y3] += position.y - ty; vertices[Z3] += position.z; - /** - * Transform the fourth vertex - */ + /** Transform the fourth vertex */ // first apply the scale to the vector x = (vertices[X4] + tx) * scale.x; y = (vertices[Y4] + ty) * scale.y; z = vertices[Z4]; - //then transform the vector using the rotation quaternion + // then transform the vector using the rotation quaternion vertices[X4] = rotation.w * x + rotation.y * z - rotation.z * y; vertices[Y4] = rotation.w * y + rotation.z * x - rotation.x * z; vertices[Z4] = rotation.w * z + rotation.x * y - rotation.y * x; @@ -482,35 +388,33 @@ protected void transformVertices() { vertices[Y4] = w * rotation.y + y * rotation.w + z * rotation.x - x * rotation.z; vertices[Z4] = w * rotation.z + z * rotation.w + x * rotation.y - y * rotation.x; rotation.conjugate(); // <- don't forget to conjugate the rotation back to normal - //finally translate the vector according to position + // finally translate the vector according to position vertices[X4] += position.x - tx; vertices[Y4] += position.y - ty; vertices[Z4] += position.z; updated = true; } - /** - * Resets the position components of the vertices array based ont he dimensions (preparation for transformation) - */ - protected void resetVertices() { + /** Resets the position components of the vertices array based ont he dimensions (preparation for transformation) */ + protected void resetVertices () { float left = -dimensions.x / 2f; float right = left + dimensions.x; float top = dimensions.y / 2f; float bottom = top - dimensions.y; - //left top + // left top vertices[X1] = left; vertices[Y1] = top; vertices[Z1] = 0; - //right top + // right top vertices[X2] = right; vertices[Y2] = top; vertices[Z2] = 0; - //left bot + // left bot vertices[X3] = left; vertices[Y3] = bottom; vertices[Z3] = 0; - //right bot + // right bot vertices[X4] = right; vertices[Y4] = bottom; vertices[Z4] = 0; @@ -518,51 +422,45 @@ protected void resetVertices() { updated = false; } - /** - * Re-applies the uv coordinates from the material's texture region to the uv components of the vertices array - */ - protected void updateUVs() { + /** Re-applies the uv coordinates from the material's texture region to the uv components of the vertices array */ + protected void updateUVs () { TextureRegion tr = material.textureRegion; - //left top + // left top vertices[U1] = tr.getU(); vertices[V1] = tr.getV(); - //right top + // right top vertices[U2] = tr.getU2(); vertices[V2] = tr.getV(); - //left bot + // left bot vertices[U3] = tr.getU(); vertices[V3] = tr.getV2(); - //right bot + // right bot vertices[U4] = tr.getU2(); vertices[V4] = tr.getV2(); } - /** - * Sets the texture region - * - * @param textureRegion Texture region to apply - */ - public void setTextureRegion(TextureRegion textureRegion) { + /** Sets the texture region + * + * @param textureRegion Texture region to apply */ + public void setTextureRegion (TextureRegion textureRegion) { this.material.textureRegion = textureRegion; updateUVs(); } - /** - * Sets the blending parameters for this decal - * + /** Sets the blending parameters for this decal + * * @param srcBlendFactor Source blend factor used by glBlendFunc - * @param dstBlendFactor Destination blend factor used by glBlendFunc - */ - public void setBlending(int srcBlendFactor, int dstBlendFactor) { + * @param dstBlendFactor Destination blend factor used by glBlendFunc */ + public void setBlending (int srcBlendFactor, int dstBlendFactor) { material.srcBlendFactor = srcBlendFactor; material.dstBlendFactor = dstBlendFactor; } - protected DecalMaterial getMaterial() { + protected DecalMaterial getMaterial () { return material; } - //meaning of the floats in the vertices array + // meaning of the floats in the vertices array public static final int X1 = 0; public static final int Y1 = 1; public static final int Z1 = 2; @@ -593,68 +491,59 @@ protected DecalMaterial getMaterial() { protected static final Vector3 Y_AXIS = new Vector3(0, 1, 0); protected static final Vector3 Z_AXIS = new Vector3(0, 0, 1); - /** - * Creates a decal assuming the dimensions of the texture region - * + /** Creates a decal assuming the dimensions of the texture region + * * @param textureRegion Texture region to use - * @return Created decal - */ - public static Decal newDecal(TextureRegion textureRegion) { - return newDecal(textureRegion.getRegionWidth(), textureRegion.getRegionHeight(), textureRegion, DecalMaterial.NO_BLEND, DecalMaterial.NO_BLEND); + * @return Created decal */ + public static Decal newDecal (TextureRegion textureRegion) { + return newDecal(textureRegion.getRegionWidth(), textureRegion.getRegionHeight(), textureRegion, DecalMaterial.NO_BLEND, + DecalMaterial.NO_BLEND); } - /** - * Creates a decal assuming the dimensions of the texture region and adding transparency - * - * @param textureRegion Texture region to use + /** Creates a decal assuming the dimensions of the texture region and adding transparency + * + * @param textureRegion Texture region to use * @param hasTransparency Whether or not this sprite will be treated as having transparency (transparent png, etc.) - * @return Created decal - */ - public static Decal newDecal(TextureRegion textureRegion, boolean hasTransparency) { + * @return Created decal */ + public static Decal newDecal (TextureRegion textureRegion, boolean hasTransparency) { return newDecal(textureRegion.getRegionWidth(), textureRegion.getRegionHeight(), textureRegion, - hasTransparency ? GL10.GL_SRC_ALPHA : DecalMaterial.NO_BLEND, - hasTransparency ? GL10.GL_ONE_MINUS_SRC_ALPHA : DecalMaterial.NO_BLEND); + hasTransparency ? GL10.GL_SRC_ALPHA : DecalMaterial.NO_BLEND, hasTransparency ? GL10.GL_ONE_MINUS_SRC_ALPHA + : DecalMaterial.NO_BLEND); } - /** - * Creates a decal using the region for texturing - * - * @param width Width of the decal in world units - * @param height Height of the decal in world units + /** Creates a decal using the region for texturing + * + * @param width Width of the decal in world units + * @param height Height of the decal in world units * @param textureRegion TextureRegion to use - * @return Created decal - */ - //TODO : it would be convenient if {@link com.badlogic.gdx.graphics.Texture} had a getFormat() method to assume transparency from RGBA,.. - public static Decal newDecal(float width, float height, TextureRegion textureRegion) { + * @return Created decal */ + // TODO : it would be convenient if {@link com.badlogic.gdx.graphics.Texture} had a getFormat() method to assume transparency +// from RGBA,.. + public static Decal newDecal (float width, float height, TextureRegion textureRegion) { return newDecal(width, height, textureRegion, DecalMaterial.NO_BLEND, DecalMaterial.NO_BLEND); } - /** - * Creates a decal using the region for texturing - * - * @param width Width of the decal in world units - * @param height Height of the decal in world units - * @param textureRegion TextureRegion to use + /** Creates a decal using the region for texturing + * + * @param width Width of the decal in world units + * @param height Height of the decal in world units + * @param textureRegion TextureRegion to use * @param hasTransparency Whether or not this sprite will be treated as having transparency (transparent png, etc.) - * @return Created decal - */ - public static Decal newDecal(float width, float height, TextureRegion textureRegion, boolean hasTransparency) { - return newDecal(width, height, textureRegion, - hasTransparency ? GL10.GL_SRC_ALPHA : DecalMaterial.NO_BLEND, - hasTransparency ? GL10.GL_ONE_MINUS_SRC_ALPHA : DecalMaterial.NO_BLEND); - } - - /** - * Creates a decal using the region for texturing and the specified blending parameters for blending - * - * @param width Width of the decal in world units - * @param height Height of the decal in world units - * @param textureRegion TextureRegion to use + * @return Created decal */ + public static Decal newDecal (float width, float height, TextureRegion textureRegion, boolean hasTransparency) { + return newDecal(width, height, textureRegion, hasTransparency ? GL10.GL_SRC_ALPHA : DecalMaterial.NO_BLEND, + hasTransparency ? GL10.GL_ONE_MINUS_SRC_ALPHA : DecalMaterial.NO_BLEND); + } + + /** Creates a decal using the region for texturing and the specified blending parameters for blending + * + * @param width Width of the decal in world units + * @param height Height of the decal in world units + * @param textureRegion TextureRegion to use * @param srcBlendFactor Source blend used by glBlendFunc * @param dstBlendFactor Destination blend used by glBlendFunc - * @return Created decal - */ - public static Decal newDecal(float width, float height, TextureRegion textureRegion, int srcBlendFactor, int dstBlendFactor) { + * @return Created decal */ + public static Decal newDecal (float width, float height, TextureRegion textureRegion, int srcBlendFactor, int dstBlendFactor) { Decal decal = new Decal(); decal.setTextureRegion(textureRegion); decal.setBlending(srcBlendFactor, dstBlendFactor); diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalBatch.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalBatch.java index 5483585845e..8f7275d7ee3 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalBatch.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalBatch.java @@ -1,37 +1,36 @@ + package com.badlogic.gdx.graphics.g3d.decals; -import com.badlogic.gdx.graphics.*; +import com.badlogic.gdx.graphics.GL10; +import com.badlogic.gdx.graphics.Mesh; +import com.badlogic.gdx.graphics.VertexAttribute; +import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; -import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.SortedIntList; -import java.util.Iterator; - -/** - *

        +/**

        * Renderer for {@link Decal} objects. *

        *

        * New objects are added using {@link DecalBatch#add(Decal)}, there is no limit on how many decals can be added.
        - * Once all the decals have been submitted a call to {@link DecalBatch#flush()} will - * batch them together and send big chunks of geometry to the GL. + * Once all the decals have been submitted a call to {@link DecalBatch#flush()} will batch them together and send big chunks of + * geometry to the GL. *

        *

        - * The size of the batch specifies the maximum number of decals that can be batched together before they have to be - * submitted to the graphics pipeline. The default size is {@link DecalBatch#DEFAULT_SIZE}. If it is known before hand - * that not as many will be needed on average the batch can be downsized to save memory. If the game is basically 3d - * based and decals will only be needed for an orthogonal HUD it makes sense to tune the size down. + * The size of the batch specifies the maximum number of decals that can be batched together before they have to be submitted to + * the graphics pipeline. The default size is {@link DecalBatch#DEFAULT_SIZE}. If it is known before hand that not as many will be + * needed on average the batch can be downsized to save memory. If the game is basically 3d based and decals will only be needed + * for an orthogonal HUD it makes sense to tune the size down. *

        *

        - * The way the batch handles things depends on the {@link GroupStrategy}. Different strategies can be used to customize - * shaders, states, culling etc. for more details see the {@link GroupStrategy} java doc.
        - * While it shouldn't be necessary to change strategies, if you have to do so, do it before calling {@link #add(Decal)}, - * and if you already did, call {@link #flush()} first. - *

        - */ + * The way the batch handles things depends on the {@link GroupStrategy}. Different strategies can be used to customize shaders, + * states, culling etc. for more details see the {@link GroupStrategy} java doc.
        + * While it shouldn't be necessary to change strategies, if you have to do so, do it before calling {@link #add(Decal)}, and if + * you already did, call {@link #flush()} first. + *

        */ public class DecalBatch implements Disposable { private static final int DEFAULT_SIZE = 1000; private float[] vertices; @@ -43,77 +42,66 @@ public class DecalBatch implements Disposable { @Override protected Array newObject () { return new Array(false, 100); - } - }; + } + }; private final Array> usedGroups = new Array>(16); - /** - * Creates a new batch using the {@link DefaultGroupStrategy} - */ - public DecalBatch() { + /** Creates a new batch using the {@link DefaultGroupStrategy} */ + public DecalBatch () { this(DEFAULT_SIZE, new DefaultGroupStrategy()); } - public DecalBatch(GroupStrategy groupStrategy) { + public DecalBatch (GroupStrategy groupStrategy) { this(DEFAULT_SIZE, groupStrategy); } - public DecalBatch(int size, GroupStrategy groupStrategy) { + public DecalBatch (int size, GroupStrategy groupStrategy) { initialize(size); setGroupStrategy(groupStrategy); } - /** - * Sets the {@link GroupStrategy} used - * @param groupStrategy Group strategy to use - */ - public void setGroupStrategy(GroupStrategy groupStrategy) { + /** Sets the {@link GroupStrategy} used + * @param groupStrategy Group strategy to use */ + public void setGroupStrategy (GroupStrategy groupStrategy) { this.groupStrategy = groupStrategy; } - /** - * Initializes the batch with the given amount of decal objects the buffer is able to hold when full. - * - * @param size Maximum size of decal objects to hold in memory - */ - public void initialize(int size) { + /** Initializes the batch with the given amount of decal objects the buffer is able to hold when full. + * + * @param size Maximum size of decal objects to hold in memory */ + public void initialize (int size) { vertices = new float[size * Decal.SIZE]; - mesh = new Mesh( - Mesh.VertexDataType.VertexArray, false, size * 4, size * 6, - new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), - new VertexAttribute(VertexAttributes.Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); + mesh = new Mesh(Mesh.VertexDataType.VertexArray, false, size * 4, size * 6, new VertexAttribute( + VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute( + VertexAttributes.Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE), new VertexAttribute( + VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); short[] indices = new short[size * 6]; int v = 0; - for(int i = 0; i < indices.length; i += 6, v += 4) { - indices[i] = (short) (v); - indices[i + 1] = (short) (v + 2); - indices[i + 2] = (short) (v + 1); - indices[i + 3] = (short) (v + 1); - indices[i + 4] = (short) (v + 2); - indices[i + 5] = (short) (v + 3); + for (int i = 0; i < indices.length; i += 6, v += 4) { + indices[i] = (short)(v); + indices[i + 1] = (short)(v + 2); + indices[i + 2] = (short)(v + 1); + indices[i + 3] = (short)(v + 1); + indices[i + 4] = (short)(v + 2); + indices[i + 5] = (short)(v + 3); } mesh.setIndices(indices); } - /** - * @return maximum amount of decal objects this buffer can hold in memory - */ - public int getSize() { + /** @return maximum amount of decal objects this buffer can hold in memory */ + public int getSize () { return vertices.length / Decal.SIZE; } - /** - * Add a decal to the batch, marking it for later rendering - * - * @param decal Decal to add for rendering - */ - public void add(Decal decal) { + /** Add a decal to the batch, marking it for later rendering + * + * @param decal Decal to add for rendering */ + public void add (Decal decal) { DecalMaterial material = decal.getMaterial(); int groupIndex = groupStrategy.decideGroup(decal); Array targetGroup = groupList.get(groupIndex); - if(targetGroup == null) { + if (targetGroup == null) { targetGroup = groupPool.obtain(); targetGroup.clear(); usedGroups.add(targetGroup); @@ -122,20 +110,16 @@ public void add(Decal decal) { targetGroup.add(decal); } - /** - * Flush this batch sending all contained decals to GL. After flushing the batch is empty once again. - */ - public void flush() { + /** Flush this batch sending all contained decals to GL. After flushing the batch is empty once again. */ + public void flush () { render(); clear(); } - /** - * Renders all decals to the buffer and flushes the buffer to the GL when full/done - */ - protected void render() { + /** Renders all decals to the buffer and flushes the buffer to the GL when full/done */ + protected void render () { groupStrategy.beforeGroups(); - for(SortedIntList.Node> group : groupList) { + for (SortedIntList.Node> group : groupList) { groupStrategy.beforeGroup(group.index, group.value); ShaderProgram shader = groupStrategy.getGroupShader(group.index); render(shader, group.value); @@ -144,18 +128,16 @@ protected void render() { groupStrategy.afterGroups(); } - /** - * Renders a group of vertices to the buffer, flushing them to GL when done/full - * - * @param decals Decals to render - */ - private void render(ShaderProgram shader, Array decals) { - //batch vertices + /** Renders a group of vertices to the buffer, flushing them to GL when done/full + * + * @param decals Decals to render */ + private void render (ShaderProgram shader, Array decals) { + // batch vertices DecalMaterial lastMaterial = null; int idx = 0; - for(Decal decal : decals) { - if(lastMaterial == null || !lastMaterial.equals(decal.getMaterial())) { - if(idx > 0) { + for (Decal decal : decals) { + if (lastMaterial == null || !lastMaterial.equals(decal.getMaterial())) { + if (idx > 0) { flush(shader, idx); idx = 0; } @@ -165,47 +147,40 @@ private void render(ShaderProgram shader, Array decals) { decal.update(); System.arraycopy(decal.vertices, 0, vertices, idx, decal.vertices.length); idx += decal.vertices.length; - //if our batch is full we have to flush it - if(idx == vertices.length) { + // if our batch is full we have to flush it + if (idx == vertices.length) { flush(shader, idx); idx = 0; } } - //at the end if there is stuff left in the batch we render that - if(idx > 0) { + // at the end if there is stuff left in the batch we render that + if (idx > 0) { flush(shader, idx); } } - /** - * Flushes vertices[0,verticesPosition[ to GL - * verticesPosition % Decal.SIZE must equal 0 - * - * @param verticesPosition Amount of elements from the vertices array to flush - */ - protected void flush(ShaderProgram shader, int verticesPosition) { + /** Flushes vertices[0,verticesPosition[ to GL verticesPosition % Decal.SIZE must equal 0 + * + * @param verticesPosition Amount of elements from the vertices array to flush */ + protected void flush (ShaderProgram shader, int verticesPosition) { mesh.setVertices(vertices, 0, verticesPosition); - if(shader != null) { + if (shader != null) { mesh.render(shader, GL10.GL_TRIANGLES, 0, verticesPosition / 4); } else { mesh.render(GL10.GL_TRIANGLES, 0, verticesPosition / 4); } } - /** - * Remove all decals from batch - */ - protected void clear() { + /** Remove all decals from batch */ + protected void clear () { groupList.clear(); groupPool.free(usedGroups); usedGroups.clear(); } - /** - * Frees up memory by dropping the buffer and underlying resources. - * If the batch is needed again after disposing it can be {@link #initialize(int) initialized} again. - */ - public void dispose() { + /** Frees up memory by dropping the buffer and underlying resources. If the batch is needed again after disposing it can be + * {@link #initialize(int) initialized} again. */ + public void dispose () { clear(); vertices = null; mesh.dispose(); diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalMaterial.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalMaterial.java index 8c796778b98..687b5f64d95 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalMaterial.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DecalMaterial.java @@ -1,57 +1,50 @@ + package com.badlogic.gdx.graphics.g3d.decals; import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.g2d.TextureRegion; -/** - * Material used by the {@link Decal} class - */ +/** Material used by the {@link Decal} class */ public class DecalMaterial { public static final int NO_BLEND = -1; protected TextureRegion textureRegion; protected int srcBlendFactor; protected int dstBlendFactor; - /** - * Binds the material's texture to the OpenGL context and changes the glBlendFunc to the values used by it. - */ - public void set() { + /** Binds the material's texture to the OpenGL context and changes the glBlendFunc to the values used by it. */ + public void set () { textureRegion.getTexture().bind(); - if(!isOpaque()) { + if (!isOpaque()) { Gdx.gl.glBlendFunc(srcBlendFactor, dstBlendFactor); } } - /** - * @return true if the material is completely opaque, false if it is not and therefor requires blending - */ - public boolean isOpaque() { + /** @return true if the material is completely opaque, false if it is not and therefor requires blending */ + public boolean isOpaque () { return srcBlendFactor == NO_BLEND; } - public int getSrcBlendFactor() { + public int getSrcBlendFactor () { return srcBlendFactor; } - public int getDstBlendFactor() { + public int getDstBlendFactor () { return dstBlendFactor; } @Override - public boolean equals(Object o) { - if(o == null) return false; + public boolean equals (Object o) { + if (o == null) return false; - DecalMaterial material = (DecalMaterial) o; + DecalMaterial material = (DecalMaterial)o; - return dstBlendFactor == material.dstBlendFactor && - srcBlendFactor == material.srcBlendFactor && - textureRegion.getTexture() == material.textureRegion.getTexture(); + return dstBlendFactor == material.dstBlendFactor && srcBlendFactor == material.srcBlendFactor + && textureRegion.getTexture() == material.textureRegion.getTexture(); } @Override - public int hashCode() { + public int hashCode () { int result = textureRegion.getTexture() != null ? textureRegion.getTexture().hashCode() : 0; result = 31 * result + srcBlendFactor; result = 31 * result + dstBlendFactor; diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DefaultGroupStrategy.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DefaultGroupStrategy.java index d5b731b3f09..55b20ecda30 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DefaultGroupStrategy.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/DefaultGroupStrategy.java @@ -1,20 +1,15 @@ + package com.badlogic.gdx.graphics.g3d.decals; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Array; -import com.badlogic.gdx.utils.ObjectMap; -import com.badlogic.gdx.utils.Sort; - -import java.util.Comparator; -/** - *

        - * Minimalistic grouping strategy that splits decals into opaque and transparent ones enabling and disabling blending - * as needed. Opaque decals are rendered first (decal color is ignored in opacity check).
        - * Use this strategy only if the vast majority of your decals are opaque and the few transparent ones are unlikely - * to overlap. +/**

        + * Minimalistic grouping strategy that splits decals into opaque and transparent ones enabling and disabling blending as needed. + * Opaque decals are rendered first (decal color is ignored in opacity check).
        + * Use this strategy only if the vast majority of your decals are opaque and the few transparent ones are unlikely to overlap. *

        *

        * Can produce invisible artifacts when transparent decals overlap each other. @@ -23,59 +18,72 @@ * States (* = any, EV = entry value - same as value before flush):
        * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * *
        expectsexits onexpectsexits on
        glDepthMasktrueEVglDepthMasktrueEV
        GL_DEPTH_TESTenabledEVGL_DEPTH_TESTenabledEV
        glDepthFuncGL_LESS | GL_LEQUALEVglDepthFuncGL_LESS | GL_LEQUALEV
        GL_BLENDdisabledEV | disabledGL_BLENDdisabledEV | disabled
        glBlendFunc**glBlendFunc**
        GL_TEXTURE_2D*disabledGL_TEXTURE_2D*disabled
        - *

        - */ + *

        */ public class DefaultGroupStrategy implements GroupStrategy { private static final int GROUP_OPAQUE = 0; private static final int GROUP_BLEND = 1; @Override - public int decideGroup(Decal decal) { + public int decideGroup (Decal decal) { return decal.getMaterial().isOpaque() ? GROUP_OPAQUE : GROUP_BLEND; } @Override - public void beforeGroup(int group, Array contents) { - if(group == GROUP_BLEND) { + public void beforeGroup (int group, Array contents) { + if (group == GROUP_BLEND) { Gdx.gl10.glEnable(GL10.GL_BLEND); } } @Override - public void afterGroup(int group) { - if(group == GROUP_BLEND) { + public void afterGroup (int group) { + if (group == GROUP_BLEND) { Gdx.gl10.glDisable(GL10.GL_BLEND); } } @Override - public void beforeGroups() { + public void beforeGroups () { Gdx.gl10.glEnable(GL10.GL_TEXTURE_2D); } @Override - public void afterGroups() { + public void afterGroups () { Gdx.gl10.glDisable(GL10.GL_TEXTURE_2D); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupPlug.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupPlug.java index e2709aa3dc6..40761d6f532 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupPlug.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupPlug.java @@ -1,13 +1,12 @@ + package com.badlogic.gdx.graphics.g3d.decals; import com.badlogic.gdx.utils.Array; -import com.badlogic.gdx.utils.ObjectMap; -/** - * Handles a single group's pre and post render arrangements. Can be plugged into {@link PluggableGroupStrategy} to build - * modular {@link GroupStrategy GroupStrategies}. - */ +/** Handles a single group's pre and post render arrangements. Can be plugged into {@link PluggableGroupStrategy} to build modular + * {@link GroupStrategy GroupStrategies}. */ public interface GroupPlug { - public void beforeGroup(Array contents); - public void afterGroup(); + public void beforeGroup (Array contents); + + public void afterGroup (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupStrategy.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupStrategy.java index b4f38d8be8d..a73f2dae096 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupStrategy.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/GroupStrategy.java @@ -1,70 +1,55 @@ + package com.badlogic.gdx.graphics.g3d.decals; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Array; -import com.badlogic.gdx.utils.ObjectMap.Values; -/** - *

        - * This class provides hooks which are invoked by {@link DecalBatch} to evaluate the group a sprite falls into, as - * well as to adjust settings before and after rendering a group. +/**

        + * This class provides hooks which are invoked by {@link DecalBatch} to evaluate the group a sprite falls into, as well as to + * adjust settings before and after rendering a group. *

        *

        - * A group is identified by an integer. The {@link #beforeGroup(int, Array) beforeGroup()} - * method provides the strategy with a list of all the decals, which are contained in the group itself, and will be rendered - * before the associated call to {@link #afterGroup(int)}.
        + * A group is identified by an integer. The {@link #beforeGroup(int, Array) beforeGroup()} method provides the strategy with a + * list of all the decals, which are contained in the group itself, and will be rendered before the associated call to + * {@link #afterGroup(int)}.
        * A call to {@code beforeGroup()} is always fallowed by a call to {@code afterGroup()}.
        - * Groups are always invoked based on their ascending int values. Group -10 will be rendered before group -5, - * group -5 before group 0, group 0 before group 6 and so on.
        + * Groups are always invoked based on their ascending int values. Group -10 will be rendered before group -5, group -5 + * before group 0, group 0 before group 6 and so on.
        * The call order for a single flush is always {@code beforeGroups(), beforeGroup1(), afterGroup1(), ... beforeGroupN(), * afterGroupN(), afterGroups()}. *

        *

        - * The contents of the {@code beforeGroup()} call can be modified at will to realize view frustum culling, material & depth sorting, ... all based on - * the requirements of the current group. The batch itself does not change OpenGL settings except for whichever - * changes are entailed {@link DecalMaterial#set()}. If the group requires a special shader, - * blending, {@link #getGroupShader(int)} should return it so that DecalBatch can apply it while rendering the group. - *

        - */ + * The contents of the {@code beforeGroup()} call can be modified at will to realize view frustum culling, material & depth + * sorting, ... all based on the requirements of the current group. The batch itself does not change OpenGL settings except for + * whichever changes are entailed {@link DecalMaterial#set()}. If the group requires a special shader, blending, + * {@link #getGroupShader(int)} should return it so that DecalBatch can apply it while rendering the group. + *

        */ public interface GroupStrategy { - /** - * Returns the shader to be used for the group. Can be null - * in which case the GroupStrategy doesn't support GLES 2.0 + /** Returns the shader to be used for the group. Can be null in which case the GroupStrategy doesn't support GLES 2.0 * @param group the group - * @return the {@link ShaderProgram} - */ - public ShaderProgram getGroupShader(int group); - - /** - * Assigns a group to a decal - * + * @return the {@link ShaderProgram} */ + public ShaderProgram getGroupShader (int group); + + /** Assigns a group to a decal + * * @param decal Decal to assign group to - * @return group assigned - */ - public int decideGroup(Decal decal); + * @return group assigned */ + public int decideGroup (Decal decal); - /** - * Invoked directly before rendering the contents of a group - * - * @param group Group that will be rendered - * @param contents List of entries of arrays containing all the decals in the group - */ - public void beforeGroup(int group, Array contents); + /** Invoked directly before rendering the contents of a group + * + * @param group Group that will be rendered + * @param contents List of entries of arrays containing all the decals in the group */ + public void beforeGroup (int group, Array contents); - /** - * Invoked directly after rendering of a group has completed - * - * @param group Group which completed rendering - */ - public void afterGroup(int group); + /** Invoked directly after rendering of a group has completed + * + * @param group Group which completed rendering */ + public void afterGroup (int group); - /** - * Invoked before rendering any group - */ - public void beforeGroups(); + /** Invoked before rendering any group */ + public void beforeGroups (); - /** - * Invoked after having rendered all groups - */ - public void afterGroups(); + /** Invoked after having rendered all groups */ + public void afterGroups (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/PluggableGroupStrategy.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/PluggableGroupStrategy.java index eb55334a000..e19225e6fcf 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/PluggableGroupStrategy.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/PluggableGroupStrategy.java @@ -1,41 +1,35 @@ + package com.badlogic.gdx.graphics.g3d.decals; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.IntMap; -import com.badlogic.gdx.utils.ObjectMap; -/** - * This class in combination with the {@link GroupPlug GroupPlugs} allows you to build a modular {@link GroupStrategy} out - * of routines you already implemented. - */ +/** This class in combination with the {@link GroupPlug GroupPlugs} allows you to build a modular {@link GroupStrategy} out of + * routines you already implemented. */ public abstract class PluggableGroupStrategy implements GroupStrategy { private IntMap plugs = new IntMap(); @Override - public void beforeGroup(int group, Array contents) { + public void beforeGroup (int group, Array contents) { plugs.get(group).beforeGroup(contents); } @Override - public void afterGroup(int group) { + public void afterGroup (int group) { plugs.get(group).afterGroup(); } - /** - * Set the plug used for a specific group. The plug will automatically be invoked. + /** Set the plug used for a specific group. The plug will automatically be invoked. * @param plug Plug to use - * @param group Group the plug is for - */ - public void plugIn(GroupPlug plug, int group) { + * @param group Group the plug is for */ + public void plugIn (GroupPlug plug, int group) { plugs.put(group, plug); } - /** - * Remove a plug from the strategy + /** Remove a plug from the strategy * @param group Group to remove the plug from - * @return removed plug, null if there was none for that group - */ - public GroupPlug unPlug(int group) { + * @return removed plug, null if there was none for that group */ + public GroupPlug unPlug (int group) { return plugs.remove(group); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/SimpleOrthoGroupStrategy.java b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/SimpleOrthoGroupStrategy.java index 14677ec74cd..a950936fd24 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/decals/SimpleOrthoGroupStrategy.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/decals/SimpleOrthoGroupStrategy.java @@ -1,61 +1,73 @@ + package com.badlogic.gdx.graphics.g3d.decals; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Array; -import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.Sort; -/** - *

        - * Minimalistic grouping strategy useful for orthogonal scenes where the camera faces the negative z axis. - * Handles enabling and disabling of blending and uses world-z only front to back sorting for transparent decals. +/**

        + * Minimalistic grouping strategy useful for orthogonal scenes where the camera faces the negative z axis. Handles enabling and + * disabling of blending and uses world-z only front to back sorting for transparent decals. *

        *

        * States (* = any, EV = entry value - same as value before flush):
        * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * *
        expectsexits onexpectsexits on
        glDepthMasktrueEV | trueglDepthMasktrueEV | true
        GL_DEPTH_TESTenabledEVGL_DEPTH_TESTenabledEV
        glDepthFuncGL_LESS | GL_LEQUALEVglDepthFuncGL_LESS | GL_LEQUALEV
        GL_BLENDdisabledEV | disabledGL_BLENDdisabledEV | disabled
        glBlendFunc**glBlendFunc**
        GL_TEXTURE_2D*disabledGL_TEXTURE_2D*disabled
        - *

        - */ + *

        */ public class SimpleOrthoGroupStrategy implements GroupStrategy { private Comparator comparator = new Comparator(); private static final int GROUP_OPAQUE = 0; private static final int GROUP_BLEND = 1; @Override - public int decideGroup(Decal decal) { + public int decideGroup (Decal decal) { return decal.getMaterial().isOpaque() ? GROUP_OPAQUE : GROUP_BLEND; } @Override - public void beforeGroup(int group, Array contents) { - if(group == GROUP_BLEND) { + public void beforeGroup (int group, Array contents) { + if (group == GROUP_BLEND) { Sort.instance().sort(contents, comparator); Gdx.gl10.glEnable(GL10.GL_BLEND); - //no need for writing into the z buffer if transparent decals are the last thing to be rendered - //and they are rendered back to front + // no need for writing into the z buffer if transparent decals are the last thing to be rendered + // and they are rendered back to front Gdx.gl10.glDepthMask(false); } else { // FIXME sort by material @@ -63,26 +75,26 @@ public void beforeGroup(int group, Array contents) { } @Override - public void afterGroup(int group) { - if(group == GROUP_BLEND) { + public void afterGroup (int group) { + if (group == GROUP_BLEND) { Gdx.gl10.glDepthMask(true); Gdx.gl10.glDisable(GL10.GL_BLEND); } } @Override - public void beforeGroups() { + public void beforeGroups () { Gdx.gl10.glEnable(GL10.GL_TEXTURE_2D); } @Override - public void afterGroups() { + public void afterGroups () { Gdx.gl10.glDisable(GL10.GL_TEXTURE_2D); } class Comparator implements java.util.Comparator { @Override - public int compare(Decal a, Decal b) { + public int compare (Decal a, Decal b) { return a.getZ() - b.getZ() < 0 ? -1 : 1; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/Keyframe.java b/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/Keyframe.java index cf52c662417..8026434fe62 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/Keyframe.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/Keyframe.java @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d.keyframed; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; -/** - * Container for the geometry of a single animation keyframe. +/** Container for the geometry of a single animation keyframe. * - * @author Dave Clayton - * - */ + * @author Dave Clayton */ public class Keyframe { public float[][] vertices = null; public short[][] indices = null; public boolean indicesSet = false; public boolean indicesSent = false; - + public Vector3[] taggedJointPos = null; public Quaternion[] taggedJoint = null; } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimation.java b/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimation.java index de818b41c08..46385d66d5f 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimation.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimation.java @@ -13,24 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d.keyframed; import com.badlogic.gdx.graphics.g3d.Animation; -/** - * - * @author Dave Clayton - * - */ +/** @author Dave Clayton */ public class KeyframeAnimation extends Animation { public String name; public Keyframe[] keyframes; public float length; public float sampleRate; public int refs; - - public KeyframeAnimation(String name, int frames, float length, float sampleRate) - { + + public KeyframeAnimation (String name, int frames, float length, float sampleRate) { this.name = name; this.keyframes = new Keyframe[frames]; this.length = length; @@ -39,22 +35,20 @@ public KeyframeAnimation(String name, int frames, float length, float sampleRate } @Override - public float getLength() { + public float getLength () { return length; } @Override - public int getNumFrames() { + public int getNumFrames () { return keyframes.length; } - - public void addRef() - { + + public void addRef () { refs++; } - - public int removeRef() - { + + public int removeRef () { return --refs; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimator.java b/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimator.java index 0f351117068..f5b81e6267d 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimator.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/keyframed/KeyframeAnimator.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d.keyframed; import com.badlogic.gdx.graphics.g3d.Animator; @@ -20,12 +21,9 @@ import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; -/** - * An animation controller for keyframed animations. - * - * @author Dave Clayton - * - */ +/** An animation controller for keyframed animations. + * + * @author Dave Clayton */ public class KeyframeAnimator extends Animator { // constants @@ -36,141 +34,116 @@ public class KeyframeAnimator extends Animator { private Keyframe R = null; private int numMeshes = 0; private float invSampleRate = 0; - - /** - * Get the current {@link Keyframe}. - * @return the current keyframe. - */ - public Keyframe getInterpolatedKeyframe() { return R; } - - /** - * Constructs a new KeyframeAnimator. - * @param numMeshes - * The number of meshes in the {@link KeyframedModel}. - * @param sampleRate - * The sample rate used to make the {@link KeyframeAnimation}s. - */ - public KeyframeAnimator(int numMeshes, float sampleRate) - { + + /** Get the current {@link Keyframe}. + * @return the current keyframe. */ + public Keyframe getInterpolatedKeyframe () { + return R; + } + + /** Constructs a new KeyframeAnimator. + * @param numMeshes The number of meshes in the {@link KeyframedModel}. + * @param sampleRate The sample rate used to make the {@link KeyframeAnimation}s. */ + public KeyframeAnimator (int numMeshes, float sampleRate) { this.numMeshes = numMeshes; // allocate vertex and index buffers for our temp result keyframe this.R = new Keyframe(); this.R.vertices = new float[numMeshes][]; this.R.indices = new short[numMeshes][]; - this.invSampleRate = 1.f/sampleRate; + this.invSampleRate = 1.f / sampleRate; } - - /** - * Set the result (interpolated) keyframe internal array dimensions. - * @param idx - * The index of the mesh the keyframe represents. - * @param numVertices - * The number of vertices the mesh has. - * @param numIndices - * The number of indices the mesh has. - */ - public void setKeyframeDimensions(int idx, int numVertices, int numIndices) - { + + /** Set the result (interpolated) keyframe internal array dimensions. + * @param idx The index of the mesh the keyframe represents. + * @param numVertices The number of vertices the mesh has. + * @param numIndices The number of indices the mesh has. */ + public void setKeyframeDimensions (int idx, int numVertices, int numIndices) { R.vertices[idx] = new float[numVertices]; R.indices[idx] = new short[numIndices]; } - - /** - * Set the number of tagged joints for allocation - * @param num - */ - public void setNumTaggedJoints(int num) - { + + /** Set the number of tagged joints for allocation + * @param num */ + public void setNumTaggedJoints (int num) { // allocate space for joint data in the result keyframe R.taggedJointPos = new Vector3[num]; - for(int i=0; i - * - */ + * + * @author Dave Clayton */ public class KeyframedModel { - + private Material[] materials; private static ObjectMap animations = null; private ArrayList animationRefs = new ArrayList(); @@ -51,95 +49,74 @@ public class KeyframedModel { private boolean[] visible = null; private int numMeshes = 0; private ArrayList taggedJointNames = new ArrayList(); - - /** - * Gets the {@link KeyframeAnimator} for this model. - * @return the animator. - */ - public Animator getAnimator() { return animator; } - - /** - * Sets the {@link Material} list for this model, one for each mesh, in mesh order. - * @param mats - * An array of materials. - */ - public void setMaterials(Material[] mats) - { + + /** Gets the {@link KeyframeAnimator} for this model. + * @return the animator. */ + public Animator getAnimator () { + return animator; + } + + /** Sets the {@link Material} list for this model, one for each mesh, in mesh order. + * @param mats An array of materials. */ + public void setMaterials (Material[] mats) { materials = new Material[mats.length]; - for(int i=0; i joints) - { + + /** Sets the tagged joints for this model's animations. Tagged joints have their data preserved post-sampling. + * @param joints An array of joint names. */ + public void setTaggedJoints (ArrayList joints) { taggedJointNames = joints; } - //TODO: Split this out to an MD5toKeyframe loader in com.badlogic.gdx.graphics.loaders - /** - * Loads a single {@link KeyframeAnimation} from an {@link MD5Animation}, then stores it in the animation dictionary for runtime playback. - * The dictionary manages ref counted animations so you do not have multiple copies of 100k animations in memory when you only need one per - * unique MD5 model. You must call dispose() when finished with this class. - * @param md5model - * The source {@link MD5Model}. - * @param md5renderer - * An {@link MD5Renderer} instance, used to calculate the skinned geometry. - * @param md5animator - * An {@link MD5Animator} instance to control the MD5 animation cycle the keyframing samples from. - * @param md5animation - * The {@link MD5Animation} to sample. - * @param sampleRate - * The sample rate (use smaller values for smoother animation but greater memory usage). Recommended value: 0.3 - * @param modelAsset - * The name of the model asset. Must be unique to the model. Using its path is recommended - * @param animKey - * The name used to store the animation in the mode's animation map. - */ - public KeyframeAnimation sampleAnimationFromMD5(MD5Model md5model, MD5Renderer md5renderer, MD5Animator md5animator, MD5Animation md5animation, float sampleRate, String modelAsset, String animKey) - { + // TODO: Split this out to an MD5toKeyframe loader in com.badlogic.gdx.graphics.loaders + /** Loads a single {@link KeyframeAnimation} from an {@link MD5Animation}, then stores it in the animation dictionary for + * runtime playback. The dictionary manages ref counted animations so you do not have multiple copies of 100k animations in + * memory when you only need one per unique MD5 model. You must call dispose() when finished with this class. + * @param md5model The source {@link MD5Model}. + * @param md5renderer An {@link MD5Renderer} instance, used to calculate the skinned geometry. + * @param md5animator An {@link MD5Animator} instance to control the MD5 animation cycle the keyframing samples from. + * @param md5animation The {@link MD5Animation} to sample. + * @param sampleRate The sample rate (use smaller values for smoother animation but greater memory usage). Recommended value: + * 0.3 + * @param modelAsset The name of the model asset. Must be unique to the model. Using its path is recommended + * @param animKey The name used to store the animation in the mode's animation map. */ + public KeyframeAnimation sampleAnimationFromMD5 (MD5Model md5model, MD5Renderer md5renderer, MD5Animator md5animator, + MD5Animation md5animation, float sampleRate, String modelAsset, String animKey) { this.assetName = modelAsset; numMeshes = md5model.meshes.length; boolean cached = false; - - if(animator == null) - { + + if (animator == null) { animator = new KeyframeAnimator(numMeshes, sampleRate); target = new Mesh[numMeshes]; visible = new boolean[numMeshes]; - for(int i = 0; i < visible.length; i++) { + for (int i = 0; i < visible.length; i++) { visible[i] = true; } } - if(animations == null) - { + if (animations == null) { animations = new ObjectMap(); } - String key = modelAsset+"_"+animKey; - + String key = modelAsset + "_" + animKey; + KeyframeAnimation a = null; - if(animations.containsKey(key)) - { + if (animations.containsKey(key)) { a = animations.get(key); a.addRef(); cached = true; } animationRefs.add(key); - + md5animator.setAnimation(md5animation, WrapMode.Clamp); - float len = md5animation.frames.length*md5animation.secondsPerFrame; - int numSamples = (int)(len/sampleRate)+1; - - if(!cached) - { + float len = md5animation.frames.length * md5animation.secondsPerFrame; + int numSamples = (int)(len / sampleRate) + 1; + + if (!cached) { a = new KeyframeAnimation(md5animation.name, numSamples, len, sampleRate); animations.put(key, a); } @@ -147,97 +124,85 @@ public KeyframeAnimation sampleAnimationFromMD5(MD5Model md5model, MD5Renderer m md5animator.update(0.1f); md5renderer.setSkeleton(md5animator.getSkeleton()); - int i=0; - int numVertices=0,numIndices=0; - for(float t = 0; t < len; t += sampleRate) - { - //store meshes. + int i = 0; + int numVertices = 0, numIndices = 0; + for (float t = 0; t < len; t += sampleRate) { + // store meshes. Keyframe k = null; - if(!cached) - { + if (!cached) { k = new Keyframe(); k.vertices = new float[numMeshes][]; k.indices = new short[numMeshes][]; - if(taggedJointNames.size() > 0) - { + if (taggedJointNames.size() > 0) { k.taggedJointPos = new Vector3[taggedJointNames.size()]; k.taggedJoint = new Quaternion[taggedJointNames.size()]; } - } - for(int m=0; m, Nathan Sweet , Dave Clayton - * - */ +/** Represents an MD5 (Doom 3) skeletal animation. + * @author Mario Zechner , Nathan Sweet , Dave Clayton + * */ public class MD5Animation extends Animation { public int frameRate; public float secondsPerFrame; @@ -35,19 +34,16 @@ public class MD5Animation extends Animation { public BoundingBox[] bounds; public String name; - public void write(DataOutputStream out) throws IOException - { + public void write (DataOutputStream out) throws IOException { out.writeUTF(name); out.writeInt(frameRate); out.writeFloat(secondsPerFrame); out.writeInt(frames.length); - for(int i=0; i - * - */ + * @author Dave Clayton */ public class MD5Animator extends Animator { protected MD5Joints mCurrentFrame = null; protected MD5Joints mNextFrame = null; protected MD5Joints mSkeleton = null; - - /** - * Set the current skeleton. - * @param skeleton - */ - public void setSkeleton(MD5Joints skeleton) - { + + /** Set the current skeleton. + * @param skeleton */ + public void setSkeleton (MD5Joints skeleton) { mSkeleton = skeleton; } - - /** - * Get the current skeleton. - * @return the skeleton. - */ - public MD5Joints getSkeleton() { return mSkeleton; } + + /** Get the current skeleton. + * @return the skeleton. */ + public MD5Joints getSkeleton () { + return mSkeleton; + } @Override /** @@ -53,25 +48,22 @@ public void setSkeleton(MD5Joints skeleton) * @param WrapMode * The animation {@link WrapMode}. */ - public void setAnimation(Animation anim, WrapMode wrapMode) - { + public void setAnimation (Animation anim, WrapMode wrapMode) { super.setAnimation(anim, wrapMode); - - if(anim != null) - { + + if (anim != null) { mCurrentFrame = mSkeleton = mNextFrame = ((MD5Animation)anim).frames[0]; } } @Override - protected void setInterpolationFrames() { + protected void setInterpolationFrames () { mCurrentFrame = ((MD5Animation)mCurrentAnim).frames[mCurrentFrameIdx]; mNextFrame = ((MD5Animation)mCurrentAnim).frames[mNextFrameIdx]; } @Override - protected void interpolate() { + protected void interpolate () { MD5Animation.interpolate(mCurrentFrame, mNextFrame, mSkeleton, mFrameDelta); } } - diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Jni.java b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Jni.java index 660e3a7e744..e81d67d050b 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Jni.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Jni.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d.loaders.md5; public class MD5Jni { diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Joints.java b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Joints.java index a0b32b42f4c..9438f0824d4 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Joints.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Joints.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d.loaders.md5; import java.io.DataInputStream; @@ -25,31 +26,27 @@ public class MD5Joints { /** (0) parent, (1) pos.x, (2) pos.y, (3) pos.z, (4) orient.x, (5) orient.y, (6) orient.z, (7) orient.w **/ private static final int stride = 8; public float[] joints; - - public void read(DataInputStream in) throws IOException { + + public void read (DataInputStream in) throws IOException { int numNames = in.readInt(); names = new String[numNames]; - for(int i=0; i, Nathan Sweet , Dave Clayton - * - */ +/** Loads an {@link MD5Model} MD5 (Doom 3) model. + * @author Mario Zechner , Nathan Sweet , Dave Clayton + * */ public class MD5Loader { public static MD5Model loadModel (InputStream in, boolean allocateNormals) { - BufferedReader reader = new BufferedReader( new InputStreamReader( in ), 1024 ); - MD5Model model = new MD5Model( ); - Listtokens = new ArrayList( 10 ); - MD5Quaternion quat = new MD5Quaternion( ); + BufferedReader reader = new BufferedReader(new InputStreamReader(in), 1024); + MD5Model model = new MD5Model(); + List tokens = new ArrayList(10); + MD5Quaternion quat = new MD5Quaternion(); int floatsPerVert = 4; - if(allocateNormals) floatsPerVert += 3; - + if (allocateNormals) floatsPerVert += 3; + int floatsPerWeight = 5; - if(allocateNormals) floatsPerWeight += 3; - - try - { + if (allocateNormals) floatsPerWeight += 3; + + 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(); mesh.floatsPerVertex = floatsPerVert; mesh.floatsPerWeight = floatsPerWeight; - + 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.numVertices = parseInt( tokens.get(1) ); - mesh.vertices = new float[mesh.numVertices*floatsPerVert]; + if (tokens.get(0).equals("numverts")) { + mesh.numVertices = parseInt(tokens.get(1)); + mesh.vertices = new float[mesh.numVertices * floatsPerVert]; } - 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.numWeights = parseInt( tokens.get(1) ); - mesh.weights = new float[mesh.numWeights*floatsPerWeight]; + if (tokens.get(0).equals("numweights")) { + mesh.numWeights = parseInt(tokens.get(1)); + mesh.weights = new float[mesh.numWeights * floatsPerWeight]; } - if( tokens.get(0).equals( "vert" ) ) - { - vertIndex = parseInt( tokens.get(1) ); - - int idx = vertIndex*floatsPerVert; - 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(allocateNormals) - { + if (tokens.get(0).equals("vert")) { + vertIndex = parseInt(tokens.get(1)); + + int idx = vertIndex * floatsPerVert; + 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 (allocateNormals) { mesh.vertices[idx++] = 0.f; mesh.vertices[idx++] = 0.f; mesh.vertices[idx++] = 0.f; } } - 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*floatsPerWeight; - 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 * floatsPerWeight; + 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 } } - //Gdx.app.log("MD5Loader", "mesh.vertices.length["+(currMesh-1)+"] = "+mesh.vertices.length); + // Gdx.app.log("MD5Loader", "mesh.vertices.length["+(currMesh-1)+"] = "+mesh.vertices.length); } } - + 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(); diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Mesh.java b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Mesh.java index 35f13b495fc..b499406230a 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Mesh.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/md5/MD5Mesh.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d.loaders.md5; import java.io.DataInputStream; @@ -22,11 +23,9 @@ import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; -/** - * Represents an MD5 (Doom 3) mesh, with or without normal data. - * @author Mario Zechner , Nathan Sweet , Dave Clayton - * - */ +/** Represents an MD5 (Doom 3) mesh, with or without normal data. + * @author Mario Zechner , Nathan Sweet , Dave Clayton + * */ public class MD5Mesh { public String shader; @@ -39,26 +38,25 @@ public class MD5Mesh { public float[] weights; /** idx 1, idx 2, idx 3 **/ public short[] indices; - + public int floatsPerVertex; public int floatsPerWeight; public float[] createVertexArray () { return createVertexArray(5); } - + public float[] createVertexArray (int stride) { float[] verts = new float[numVertices * stride]; int vertex_stride = floatsPerVertex; - for( int i = 0, j = 0; i < vertices.length; i+=vertex_stride ) - { - j+=3; // skip vertex + for (int i = 0, j = 0; i < vertices.length; i += vertex_stride) { + j += 3; // skip vertex verts[j++] = vertices[i]; // tex coord 1 - verts[j++] = vertices[i+1]; // tex coord 2 - if(stride == 8) // skip normals - j+=3; + verts[j++] = vertices[i + 1]; // tex coord 2 + if (stride == 8) // skip normals + j += 3; } - + return verts; } @@ -66,91 +64,88 @@ public short[] getIndices () { return indices; } - public void calculateVerticesN( MD5Joints skeleton, float[] verts, BoundingBox bbox ) - { - calculateVerticesN( skeleton, weights, vertices, verts, floatsPerVertex, floatsPerWeight, bbox ); + public void calculateVerticesN (MD5Joints skeleton, float[] verts, BoundingBox bbox) { + calculateVerticesN(skeleton, weights, vertices, verts, floatsPerVertex, floatsPerWeight, bbox); } - - public void calculateVertices( MD5Joints skeleton, float[] verts, BoundingBox bbox ) { - calculateVertices( skeleton, weights, vertices, verts, floatsPerVertex, floatsPerWeight, bbox ); + + public void calculateVertices (MD5Joints skeleton, float[] verts, BoundingBox bbox) { + calculateVertices(skeleton, weights, vertices, verts, floatsPerVertex, floatsPerWeight, bbox); } static Vector3 bn = new Vector3(); - public static void calculateVerticesN( MD5Joints skeleton, float[] weights, float vertices[], float[] verts, - int vstride, int wstride, BoundingBox bbox ) - { - for( int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += vstride ) - { + + public static void calculateVerticesN (MD5Joints skeleton, float[] weights, float vertices[], float[] verts, int vstride, + int wstride, BoundingBox bbox) { + for (int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += vstride) { float finalX = 0; float finalY = 0; float finalZ = 0; - + int weightOffset = (int)vertices[vertexOffset]; - int weightCount = (int)vertices[vertexOffset+1]; - weightOffset = weightOffset*wstride; - - // get the bind pose normal - bn.set(vertices[vertexOffset+2], vertices[vertexOffset+3], vertices[vertexOffset+4]); - /*float bnx = vertices[vertexOffset+2]; - float bny = vertices[vertexOffset+3]; - float bnz = vertices[vertexOffset+4];*/ + int weightCount = (int)vertices[vertexOffset + 1]; + weightOffset = weightOffset * wstride; + // get the bind pose normal + bn.set(vertices[vertexOffset + 2], vertices[vertexOffset + 3], vertices[vertexOffset + 4]); + /* + * float bnx = vertices[vertexOffset+2]; float bny = vertices[vertexOffset+3]; float bnz = vertices[vertexOffset+4]; + */ - 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++]; - //weightOffset += 3; + // weightOffset += 3; // get the weight normal - vn.set(weights[weightOffset++], - weights[weightOffset++], - 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]; + vn.set(weights[weightOffset++], weights[weightOffset++], 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]; // add to the bind pose normal: - quat.x = qx; quat.y = qy; quat.z = qz; quat.w = qw; + quat.x = qx; + quat.y = qy; + quat.z = qz; + quat.w = qw; quat.rotate(vn); vn.mul(bias); bn.add(vn); - //bnx += vn.x; bny += vn.y; bnz += vn.z; - - float ix = -qx, iy = -qy, iz = -qz, iw = qw; - + // bnx += vn.x; bny += vn.y; bnz += vn.z; + + 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; } - + bbox.ext(finalX, finalY, finalZ); - + verts[k++] = finalX; verts[k++] = finalY; verts[k++] = finalZ; - k+=2; - + k += 2; + // normals bn.nor(); - verts[k++] = bn.x;//bnx; - verts[k++] = bn.y;//bny; - verts[k++] = bn.z;//bnz; - + verts[k++] = bn.x;// bnx; + verts[k++] = bn.y;// bny; + verts[k++] = bn.z;// bnz; + // For each weight of a vertex, transform the vertex normal by the inverse joint's orientation // quaternion of the weight. You now have the normal in joint's local space. @@ -160,69 +155,67 @@ public static void calculateVerticesN( MD5Joints skeleton, float[] weights, floa } } - public static void calculateVertices( MD5Joints skeleton, float[] weights, float vertices[], float[] verts, - int vstride, int wstride, BoundingBox bbox ) { - for( int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += vstride ) - { + public static void calculateVertices (MD5Joints skeleton, float[] weights, float vertices[], float[] verts, int vstride, + int wstride, BoundingBox bbox) { + for (int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += vstride) { 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; } - + bbox.ext(finalX, finalY, finalZ); 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 calculateNormalsBind(MD5Joints bindPoseSkeleton, float[] verts) { - calculateNormalsBind( bindPoseSkeleton, weights, vertices, indices, verts, floatsPerVertex, floatsPerWeight ); + public void calculateNormalsBind (MD5Joints bindPoseSkeleton, float[] verts) { + calculateNormalsBind(bindPoseSkeleton, weights, vertices, indices, verts, floatsPerVertex, floatsPerWeight); } - + static Vector3 _A = new Vector3(); static Vector3 _B = new Vector3(); static Vector3 _n = new Vector3(); - private static Vector3 calcNor(Vector3 v1, Vector3 v2, Vector3 v3) - { + + private static Vector3 calcNor (Vector3 v1, Vector3 v2, Vector3 v3) { _A = v2.cpy(); _A.sub(v1); _B = v3.cpy(); @@ -230,132 +223,145 @@ private static Vector3 calcNor(Vector3 v1, Vector3 v2, Vector3 v3) _n = _A.crs(_B).nor(); return _n; } - + static MD5Quaternion quat = new MD5Quaternion(); static Vector3 vn = new Vector3(); - public static void calculateNormalsBind( MD5Joints skeleton, float[] weights, float vertices[], short indices[], - float verts[], int vstride, int wstride ) - { - for( int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += vstride ) - { + + public static void calculateNormalsBind (MD5Joints skeleton, float[] weights, float vertices[], short indices[], + float verts[], int vstride, int wstride) { + for (int vertexOffset = 2, k = 0; vertexOffset < vertices.length; vertexOffset += vstride) { float finalX = 0; float finalY = 0; float finalZ = 0; - + int weightOffset = (int)vertices[vertexOffset]; - int weightCount = (int)vertices[vertexOffset+1]; - weightOffset = weightOffset*wstride; - - for( int j = 0; j < weightCount; j++ ) - { - int jointOffset = (int)weights[weightOffset++] << 3; - float bias = weights[weightOffset++]; + int weightCount = (int)vertices[vertexOffset + 1]; + weightOffset = weightOffset * wstride; + + 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++]; weightOffset += 3; // skip normal - - 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+=3; + k += 2; + + k += 3; } // compute normals in bind pose - for(int i = 0; i < indices.length; i+=3) - { + for (int i = 0; i < indices.length; i += 3) { // only doing this once so let's use data structures short i1 = indices[i]; - short i2 = indices[i+1]; - short i3 = indices[i+2]; - int vo1 = i1*8; - int vo2 = i2*8; - int vo3 = i3*8; - - Vector3 v1 = new Vector3(verts[vo1], verts[vo1+1], verts[vo1+2]); - Vector3 v2 = new Vector3(verts[vo2], verts[vo2+1], verts[vo2+2]); - Vector3 v3 = new Vector3(verts[vo3], verts[vo3+1], verts[vo3+2]); + short i2 = indices[i + 1]; + short i3 = indices[i + 2]; + int vo1 = i1 * 8; + int vo2 = i2 * 8; + int vo3 = i3 * 8; + + Vector3 v1 = new Vector3(verts[vo1], verts[vo1 + 1], verts[vo1 + 2]); + Vector3 v2 = new Vector3(verts[vo2], verts[vo2 + 1], verts[vo2 + 2]); + Vector3 v3 = new Vector3(verts[vo3], verts[vo3 + 1], verts[vo3 + 2]); // calculate face normal. Clockwise winding. Vector3 fn = calcNor(v1, v2, v3); - + // store them back in the mesh's vertex array. - int ovo1 = i1*7; int ovo2 = i2*7; int ovo3 = i3*7; - - vertices[ovo1+4] += fn.x; vertices[ovo1+5] += fn.y; vertices[ovo1+6] += fn.z; - vertices[ovo2+4] += fn.x; vertices[ovo2+5] += fn.y; vertices[ovo2+6] += fn.z; - vertices[ovo3+4] += fn.x; vertices[ovo3+5] += fn.y; vertices[ovo3+6] += fn.z; + int ovo1 = i1 * 7; + int ovo2 = i2 * 7; + int ovo3 = i3 * 7; + + vertices[ovo1 + 4] += fn.x; + vertices[ovo1 + 5] += fn.y; + vertices[ovo1 + 6] += fn.z; + vertices[ovo2 + 4] += fn.x; + vertices[ovo2 + 5] += fn.y; + vertices[ovo2 + 6] += fn.z; + vertices[ovo3 + 4] += fn.x; + vertices[ovo3 + 5] += fn.y; + vertices[ovo3 + 6] += fn.z; } - - for(int i=0; i, Nathan Sweet , Dave Clayton - * - */ +/** Represents an MD5 (Doom 3) skinned model. Note: The normal interpolation implementation is experimental. Using it will incur a + * greater CPU overhead, and correct normals for dynamically lit models are not guaranteed at this time. Expert contribution for + * this code is encouraged, please email Dave if you're interested in helping. + * @author Mario Zechner , Nathan Sweet , Dave Clayton + * */ public class MD5Model { public int numJoints; public MD5Joints baseSkeleton; @@ -49,28 +47,24 @@ public int getNumTriangles () { return numTriangles; } - - public void read(DataInputStream in) throws IOException - { + + public void read (DataInputStream in) throws IOException { numJoints = in.readInt(); baseSkeleton = new MD5Joints(); baseSkeleton.read(in); int numMeshes = in.readInt(); meshes = new MD5Mesh[numMeshes]; - for(int i=0; i, Nathan Sweet , Dave Clayton - * - */ -public class MD5Renderer implements Disposable{ +/** The MD5Renderer draws the current frame of an animated MD5 model. It also calculates the bounding box using the resulting + * interpolated vertex data. + * @author Mario Zechner , Nathan Sweet , Dave Clayton + * */ +public class MD5Renderer implements Disposable { private final MD5Model model; private final Mesh mesh; private final short[][] indices; @@ -38,26 +38,31 @@ public class MD5Renderer implements Disposable{ private boolean useJni; private boolean useNormals; private BoundingBox mBBox = new BoundingBox(); - - public BoundingBox getBBox() { return mBBox; } - public float[] getVertices(int idx) { return vertices[idx]; } - public short[] getIndices(int idx) { return indices[idx]; } - public Mesh getMesh() { return mesh; } - - /** - * Constructs an MD5Renderer. Normals are required for dynamic lighting. Note that there is currently no JNI implementation - * supporting normal animation, so if you require normals you must use the Java implementation. On >=2.2 phones JNI is not - * much faster anyway. - * @param model - * The MD5 model this renderer will draw. - * @param useNormals - * Whether to interpolate the model's normals as well as its vertices. - * @param useJni - * Whether to use the JNI implementation or not. - */ + + public BoundingBox getBBox () { + return mBBox; + } + + public float[] getVertices (int idx) { + return vertices[idx]; + } + + public short[] getIndices (int idx) { + return indices[idx]; + } + + public Mesh getMesh () { + return mesh; + } + + /** Constructs an MD5Renderer. Normals are required for dynamic lighting. Note that there is currently no JNI implementation + * supporting normal animation, so if you require normals you must use the Java implementation. On >=2.2 phones JNI is not much + * faster anyway. + * @param model The MD5 model this renderer will draw. + * @param useNormals Whether to interpolate the model's normals as well as its vertices. + * @param useJni Whether to use the JNI implementation or not. */ public MD5Renderer (MD5Model model, boolean useNormals, boolean useJni) { - if(useJni && useNormals) - throw new GdxRuntimeException("JNI with normals is currently unsupported."); + if (useJni && useNormals) throw new GdxRuntimeException("JNI with normals is currently unsupported."); int maxVertices = 0; int maxIndices = 0; int stride = useNormals ? 8 : 5; @@ -76,53 +81,42 @@ public MD5Renderer (MD5Model model, boolean useNormals, boolean useJni) { this.vertices[i] = model.meshes[i].createVertexArray(stride); } - if(useNormals) - { - this.mesh = new Mesh( false, maxVertices, maxIndices, - new VertexAttribute( VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE ), - new VertexAttribute( VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0" ), - new VertexAttribute( VertexAttributes.Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE ) ); - } - else - { - this.mesh = new Mesh(false, maxVertices, maxIndices, - new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); + if (useNormals) { + this.mesh = new Mesh(false, maxVertices, maxIndices, new VertexAttribute(VertexAttributes.Usage.Position, 3, + ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, + ShaderProgram.TEXCOORD_ATTRIBUTE + "0"), new VertexAttribute(VertexAttributes.Usage.Normal, 3, + ShaderProgram.NORMAL_ATTRIBUTE)); + } else { + this.mesh = new Mesh(false, maxVertices, maxIndices, new VertexAttribute(VertexAttributes.Usage.Position, 3, + ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, + ShaderProgram.TEXCOORD_ATTRIBUTE + "0")); } } public void setSkeleton (MD5Joints skeleton) { mBBox.clr(); - for( int i = 0; i < model.meshes.length; i++ ) { + for (int i = 0; i < model.meshes.length; i++) { MD5Mesh mesh = model.meshes[i]; - - if( useJni ) - { + + if (useJni) { mesh.calculateVerticesJni(skeleton, vertices[i]); - } - else - { - if(useNormals) - { - mesh.calculateVerticesN(skeleton, vertices[i], mBBox ); - } - else - { + } else { + if (useNormals) { + mesh.calculateVerticesN(skeleton, vertices[i], mBBox); + } else { mesh.calculateVertices(skeleton, vertices[i], mBBox); } } - + } } public void setUseJni (boolean useJni) { this.useJni = useJni; } - - public void calculateNormals( MD5Joints bindPoseSkeleton ) - { - for(int i = 0; i < model.meshes.length; i++ ) - { + + public void calculateNormals (MD5Joints bindPoseSkeleton) { + for (int i = 0; i < model.meshes.length; i++) { MD5Mesh mesh = model.meshes[i]; mesh.calculateNormalsBind(bindPoseSkeleton, vertices[i]); } @@ -135,23 +129,19 @@ public void render () { this.mesh.render(GL10.GL_TRIANGLES, 0, indices[i].length); } } - - public void render( Material[] materials ) - { - for( int i = 0; i < model.meshes.length; i++ ) - { - if(materials[i] != null) - { - if(materials[i].Texture != null) - { + + public void render (Material[] materials) { + for (int i = 0; i < model.meshes.length; i++) { + if (materials[i] != null) { + if (materials[i].Texture != null) { materials[i].Texture.bind(); } materials[i].set(GL10.GL_FRONT); } - - this.mesh.setIndices( indices[i] ); - this.mesh.setVertices( vertices[i] ); - this.mesh.render( GL10.GL_TRIANGLES, 0, indices[i].length ); + + this.mesh.setIndices(indices[i]); + this.mesh.setVertices(vertices[i]); + this.mesh.render(GL10.GL_TRIANGLES, 0, indices[i].length); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/obj/ObjLoader.java b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/obj/ObjLoader.java index a1284f40fc8..789996c9d02 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/obj/ObjLoader.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/loaders/obj/ObjLoader.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.g3d.loaders.obj; import java.io.BufferedReader; @@ -25,29 +26,20 @@ import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.glutils.ShaderProgram; -/** - * Loads Wavefront OBJ files, ignores material files. - * @author mzechner - * - */ +/** Loads Wavefront OBJ files, ignores material files. + * @author mzechner */ public class ObjLoader { - /** - * Loads a Wavefront OBJ file from the given input stream. - * - * @param in the InputStream + /** Loads a Wavefront OBJ file from the given input stream. * - */ - public static Mesh loadObj(InputStream in) { + * @param in the InputStream */ + public static Mesh loadObj (InputStream in) { return loadObj(in, false); } - - /** - * Loads a Wavefront OBJ file from the given input stream. + + /** Loads a Wavefront OBJ file from the given input stream. * * @param in the InputStream - * @param flipV whether to flip the v texture coordinate or not - * - */ + * @param flipV whether to flip the v texture coordinate or not */ public static Mesh loadObj (InputStream in, boolean flipV) { String line = ""; @@ -69,23 +61,19 @@ public static Mesh loadObj (InputStream in, boolean flipV) { return loadObjFromString(line, flipV); } - /** - * Loads a mesh from the given string in Wavefront OBJ format + /** Loads a mesh from the given string in Wavefront OBJ format * * @param obj The string - * @return The Mesh - */ + * @return The Mesh */ public static Mesh loadObjFromString (String obj) { return loadObjFromString(obj, false); } - - /** - * Loads a mesh from the given string in Wavefront OBJ format + + /** Loads a mesh from the given string in Wavefront OBJ format * * @param obj The string * @param flipV whether to flip the v texture coordinate or not - * @return The Mesh - */ + * @return The Mesh */ public static Mesh loadObjFromString (String obj, boolean flipV) { String[] lines = obj.split("\n"); float[] vertices = new float[lines.length * 3]; @@ -130,7 +118,7 @@ public static Mesh loadObjFromString (String obj, boolean flipV) { if (line.startsWith("vt")) { String[] tokens = line.split("[ ]+"); uv[uvIndex] = Float.parseFloat(tokens[1]); - uv[uvIndex + 1] = flipV? 1 - Float.parseFloat(tokens[2]):Float.parseFloat(tokens[2]); + uv[uvIndex + 1] = flipV ? 1 - Float.parseFloat(tokens[2]) : Float.parseFloat(tokens[2]); uvIndex += 2; numUV++; continue; diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java index 8a935da961b..fb1dcc90746 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.io.BufferedInputStream; @@ -29,22 +30,15 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Class for encoding and decoding ETC1 compressed images. Also provides - * methods to add a PKM header. - * @author mzechner - * - */ +/** Class for encoding and decoding ETC1 compressed images. Also provides methods to add a PKM header. + * @author mzechner */ public class ETC1 { /** The PKM header size in bytes **/ public static int PKM_HEADER_SIZE = 16; public static int ETC1_RGB8_OES = 0x00008d64; - - /** - * Class for storing ETC1 compressed image data. - * @author mzechner - * - */ + + /** Class for storing ETC1 compressed image data. + * @author mzechner */ public final static class ETC1Data implements Disposable { /** the width in pixels **/ public final int width; @@ -54,136 +48,129 @@ public final static class ETC1Data implements Disposable { public final ByteBuffer compressedData; /** the offset in bytes to the actual compressed data. Might be 16 if this contains a PKM header, 0 otherwise **/ public final int dataOffset; - - ETC1Data(int width, int height, ByteBuffer compressedData, int dataOffset) { + + ETC1Data (int width, int height, ByteBuffer compressedData, int dataOffset) { this.width = width; this.height = height; this.compressedData = compressedData; this.dataOffset = dataOffset; } - - public ETC1Data(FileHandle pkmFile) { - byte[] buffer = new byte[1024*10]; + + public ETC1Data (FileHandle pkmFile) { + byte[] buffer = new byte[1024 * 10]; DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))); int fileSize = in.readInt(); compressedData = BufferUtils.newDisposableByteBuffer(fileSize); int readBytes = 0; - while((readBytes = in.read(buffer)) != -1) { + while ((readBytes = in.read(buffer)) != -1) { compressedData.put(buffer, 0, readBytes); } compressedData.position(0); compressedData.limit(compressedData.capacity()); - } catch(Exception e) { + } catch (Exception e) { throw new GdxRuntimeException("Couldn't load pkm file '" + pkmFile + "'", e); } finally { - if(in != null) try { in.close(); } catch(Exception e) { } + if (in != null) try { + in.close(); + } catch (Exception e) { + } } - + width = getWidthPKM(compressedData, 0); height = getHeightPKM(compressedData, 0); dataOffset = PKM_HEADER_SIZE; compressedData.position(dataOffset); } - - /** - * @return whether this ETC1Data has a PKM header - */ - public boolean hasPKMHeader() { + + /** @return whether this ETC1Data has a PKM header */ + public boolean hasPKMHeader () { return dataOffset == 16; } - - /** - * Writes the ETC1Data with a PKM header to the given file. - * @param file the file. - */ - public void write(FileHandle file) { + + /** Writes the ETC1Data with a PKM header to the given file. + * @param file the file. */ + public void write (FileHandle file) { DataOutputStream write = null; - byte[] buffer = new byte[10*1024]; + byte[] buffer = new byte[10 * 1024]; int writtenBytes = 0; compressedData.position(0); compressedData.limit(compressedData.capacity()); try { write = new DataOutputStream(new GZIPOutputStream(file.write(false))); write.writeInt(compressedData.capacity()); - while(writtenBytes != compressedData.capacity()) { - int bytesToWrite = Math.min(compressedData.remaining(), buffer.length); + while (writtenBytes != compressedData.capacity()) { + int bytesToWrite = Math.min(compressedData.remaining(), buffer.length); System.out.println("writting " + bytesToWrite); compressedData.get(buffer, 0, bytesToWrite); write.write(buffer, 0, bytesToWrite); writtenBytes += bytesToWrite; } - } catch(Exception e) { + } catch (Exception e) { throw new GdxRuntimeException("Couldn't write PKM file to '" + file + "'", e); } finally { - if(write != null) try { write.close(); } catch(Exception e) { } + if (write != null) try { + write.close(); + } catch (Exception e) { + } } compressedData.position(dataOffset); compressedData.limit(compressedData.capacity()); } - - /** - * Releases the native resources of the ETC1Data instance. - */ - public void dispose() { + + /** Releases the native resources of the ETC1Data instance. */ + public void dispose () { BufferUtils.freeMemory(compressedData); } - - public String toString() { - if(hasPKMHeader()) { - return (ETC1.isValidPKM(compressedData, 0)?"valid":"invalid") + " pkm [" + ETC1.getWidthPKM(compressedData, 0) + "x" + - ETC1.getHeightPKM(compressedData, 0) + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); + + public String toString () { + if (hasPKMHeader()) { + return (ETC1.isValidPKM(compressedData, 0) ? "valid" : "invalid") + " pkm [" + ETC1.getWidthPKM(compressedData, 0) + + "x" + ETC1.getHeightPKM(compressedData, 0) + "], compressed: " + + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } else { return "raw [" + width + "x" + height + "], compressed: " + (compressedData.capacity() - ETC1.PKM_HEADER_SIZE); } } } - - private static int getPixelSize(Format format) { - if(format == Format.RGB565) return 2; - if(format == Format.RGB888) return 3; + + private static int getPixelSize (Format format) { + if (format == Format.RGB565) return 2; + if (format == Format.RGB888) return 3; throw new GdxRuntimeException("Can only handle RGB565 or RGB888 images"); } - - /** - * Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and - * {@link Format#RGB888} are supported. + + /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. * @param pixmap the {@link Pixmap} - * @return the {@link ETC1Data} - */ - public static ETC1Data encodeImage(Pixmap pixmap) { + * @return the {@link ETC1Data} */ + public static ETC1Data encodeImage (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImage(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 0); } - - /** - * Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and - * {@link Format#RGB888} are supported. Adds a PKM header in front of the compressed - * image data. + + /** Encodes the image via the ETC1 compression scheme. Only {@link Format#RGB565} and {@link Format#RGB888} are supported. Adds + * a PKM header in front of the compressed image data. * @param pixmap the {@link Pixmap} - * @return the {@link ETC1Data} - */ - public static ETC1Data encodeImagePKM(Pixmap pixmap) { + * @return the {@link ETC1Data} */ + public static ETC1Data encodeImagePKM (Pixmap pixmap) { int pixelSize = getPixelSize(pixmap.getFormat()); ByteBuffer compressedData = encodeImagePKM(pixmap.getPixels(), 0, pixmap.getWidth(), pixmap.getHeight(), pixelSize); return new ETC1Data(pixmap.getWidth(), pixmap.getHeight(), compressedData, 16); } - - /** - * Takes ETC1 compressed image data and converts it to a {@link Format#RGB565} or {@link Format#RGB888} - * {@link Pixmap}. Does not modify the ByteBuffer's position or limit. + + /** Takes ETC1 compressed image data and converts it to a {@link Format#RGB565} or {@link Format#RGB888} {@link Pixmap}. Does + * not modify the ByteBuffer's position or limit. * @param etc1Data the {@link ETC1Data} instance * @param format either {@link Format#RGB565} or {@link Format#RGB888} - * @return the Pixmap - */ - public static Pixmap decodeImage(ETC1Data etc1Data, Format format) { + * @return the Pixmap */ + public static Pixmap decodeImage (ETC1Data etc1Data, Format format) { int dataOffset = 0; int width = 0; int height = 0; - - if(etc1Data.hasPKMHeader()) { + + if (etc1Data.hasPKMHeader()) { dataOffset = 16; width = ETC1.getWidthPKM(etc1Data.compressedData, 0); height = ETC1.getHeightPKM(etc1Data.compressedData, 0); @@ -192,85 +179,67 @@ public static Pixmap decodeImage(ETC1Data etc1Data, Format format) { width = etc1Data.width; height = etc1Data.height; } - + int pixelSize = getPixelSize(format); Pixmap pixmap = new Pixmap(width, height, format); decodeImage(etc1Data.compressedData, dataOffset, pixmap.getPixels(), 0, width, height, pixelSize); return pixmap; } - - /** - * @param width the width in pixels + + /** @param width the width in pixels * @param height the height in pixels - * @return the number of bytes needed to store the compressed data - */ - public static native int getCompressedDataSize(int width, int height); - - /** - * Writes a PKM header to the {@link ByteBuffer}. Does not - * modify the position or limit of the ByteBuffer. + * @return the number of bytes needed to store the compressed data */ + public static native int getCompressedDataSize (int width, int height); + + /** Writes a PKM header to the {@link ByteBuffer}. Does not modify the position or limit of the ByteBuffer. * @param header the direct native order {@link ByteBuffer} * @param offset the offset to the header in bytes * @param width the width in pixels - * @param height the height in pixels - */ - public static native void formatHeader(ByteBuffer header, int offset, int width, int height); - - /** - * @param header direct native order {@link ByteBuffer} holding the PKM header + * @param height the height in pixels */ + public static native void formatHeader (ByteBuffer header, int offset, int width, int height); + + /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start - * @return the width stored in the PKM header - */ - static native int getWidthPKM(ByteBuffer header, int offset); - - /** - * @param header direct native order {@link ByteBuffer} holding the PKM header + * @return the width stored in the PKM header */ + static native int getWidthPKM (ByteBuffer header, int offset); + + /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start - * @return the height stored in the PKM header - */ - static native int getHeightPKM(ByteBuffer header, int offset); - - /** - * @param header direct native order {@link ByteBuffer} holding the PKM header + * @return the height stored in the PKM header */ + static native int getHeightPKM (ByteBuffer header, int offset); + + /** @param header direct native order {@link ByteBuffer} holding the PKM header * @param offset the offset in bytes to the PKM header from the ByteBuffer's start - * @return the width stored in the PKM header - */ - static native boolean isValidPKM(ByteBuffer header, int offset); - - /** - * Decodes the compressed image data to RGB565 or RGB888 pixel data. Does not - * modify the position or limit of the {@link ByteBuffer} instances. + * @return the width stored in the PKM header */ + static native boolean isValidPKM (ByteBuffer header, int offset); + + /** Decodes the compressed image data to RGB565 or RGB888 pixel data. Does not modify the position or limit of the + * {@link ByteBuffer} instances. * @param compressedData the compressed image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param decodedData the decoded data in a direct native order ByteBuffer, must hold width * height * pixelSize bytes. * @param offsetDec the offset in bytes to the decoded image data. * @param width the width in pixels * @param height the height in pixels - * @param pixelSize the pixel size, either 2 (RBG565) or 3 (RGB888) - */ - private static native void decodeImage(ByteBuffer compressedData, int offset, ByteBuffer decodedData, int offsetDec, int width, int height, int pixelSize); - - /** - * Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit - * of the {@link ByteBuffer}. + * @param pixelSize the pixel size, either 2 (RBG565) or 3 (RGB888) */ + private static native void decodeImage (ByteBuffer compressedData, int offset, ByteBuffer decodedData, int offsetDec, + int width, int height, int pixelSize); + + /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) - * @return a new direct native order ByteBuffer containing the compressed image data - */ - private static native ByteBuffer encodeImage(ByteBuffer imageData, int offset, int width, int height, int pixelSize); - - /** - * Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit - * of the {@link ByteBuffer}. + * @return a new direct native order ByteBuffer containing the compressed image data */ + private static native ByteBuffer encodeImage (ByteBuffer imageData, int offset, int width, int height, int pixelSize); + + /** Encodes the image data given as RGB565 or RGB888. Does not modify the position or limit of the {@link ByteBuffer}. * @param imageData the image data in a direct native order {@link ByteBuffer} * @param offset the offset in bytes to the image data from the start of the buffer * @param width the width in pixels * @param height the height in pixels * @param pixelSize the pixel size, either 2 (RGB565) or 3 (RGB888) - * @return a new direct native order ByteBuffer containing the compressed image data - */ - private static native ByteBuffer encodeImagePKM(ByteBuffer imageData, int offset, int width, int height, int pixelSize); + * @return a new direct native order ByteBuffer containing the compressed image data */ + private static native ByteBuffer encodeImagePKM (ByteBuffer imageData, int offset, int width, int height, int pixelSize); } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java index 813a05ec9ef..8754283099c 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.glutils; import com.badlogic.gdx.Application.ApplicationType; @@ -16,12 +17,12 @@ public class ETC1TextureData implements TextureData { boolean useMipMaps; int width = 0; int height = 0; - - public ETC1TextureData(FileHandle file) { + + public ETC1TextureData (FileHandle file) { this(file, false); } - - public ETC1TextureData(FileHandle file, boolean useMipMaps) { + + public ETC1TextureData (FileHandle file, boolean useMipMaps) { this.file = file; this.useMipMaps = useMipMaps; } @@ -46,16 +47,18 @@ public void uploadCompressedData () { ETC1Data data = new ETC1Data(file); width = data.width; height = data.height; - - if(Gdx.app.getType() == ApplicationType.Desktop || Gdx.graphics.isGL20Available() == false) { + + if (Gdx.app.getType() == ApplicationType.Desktop || Gdx.graphics.isGL20Available() == false) { Pixmap pixmap = ETC1.decodeImage(data, Format.RGB565); - Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); - if(useMipMaps) MipMapGenerator.generateMipMap(pixmap, pixmap.getWidth(), pixmap.getHeight(), false); + Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + if (useMipMaps) MipMapGenerator.generateMipMap(pixmap, pixmap.getWidth(), pixmap.getHeight(), false); pixmap.dispose(); useMipMaps = false; } else { - Gdx.gl.glCompressedTexImage2D(GL10.GL_TEXTURE_2D, 0, ETC1.ETC1_RGB8_OES, width, height, 0, data.compressedData.capacity() - data.dataOffset, data.compressedData); - if(useMipMaps()) Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D); + Gdx.gl.glCompressedTexImage2D(GL10.GL_TEXTURE_2D, 0, ETC1.ETC1_RGB8_OES, width, height, 0, + data.compressedData.capacity() - data.dataOffset, data.compressedData); + if (useMipMaps()) Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D); } data.dispose(); } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureData.java index eef56e19ee3..30560dec718 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureData.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.glutils; import com.badlogic.gdx.files.FileHandle; @@ -13,30 +14,30 @@ public class FileTextureData implements TextureData { Format format; Pixmap pixmap; boolean useMipMaps; - - public FileTextureData(FileHandle file, Pixmap preloadedPixmap, Format format, boolean useMipMaps) { + + public FileTextureData (FileHandle file, Pixmap preloadedPixmap, Format format, boolean useMipMaps) { this.file = file; this.pixmap = preloadedPixmap; this.format = format; this.useMipMaps = useMipMaps; - if(pixmap != null) { + if (pixmap != null) { width = pixmap.getWidth(); height = pixmap.getHeight(); - if(format == null) this.format = pixmap.getFormat(); + if (format == null) this.format = pixmap.getFormat(); } } - + @Override public Pixmap getPixmap () { - if(pixmap != null) { + if (pixmap != null) { Pixmap tmp = pixmap; this.pixmap = null; return tmp; - } else { + } else { Pixmap pixmap = new Pixmap(file); width = pixmap.getWidth(); height = pixmap.getHeight(); - if(format == null) format = pixmap.getFormat(); + if (format == null) format = pixmap.getFormat(); return pixmap; } } @@ -70,11 +71,11 @@ public boolean useMipMaps () { public boolean isManaged () { return true; } - - public FileHandle getFileHandle() { + + public FileHandle getFileHandle () { return file; } - + @Override public TextureDataType getType () { return TextureDataType.Pixmap; diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/FrameBuffer.java b/gdx/src/com/badlogic/gdx/graphics/glutils/FrameBuffer.java index e638256659a..e24aed5a2d8 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/FrameBuffer.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/FrameBuffer.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -26,7 +27,6 @@ import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; -import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; @@ -34,8 +34,7 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * 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. @@ -50,9 +49,7 @@ * A FrameBuffer must be disposed if it is no longer needed *

        * - * @author mzechner - * - */ + * @author mzechner */ public class FrameBuffer implements Disposable { /** the frame buffers **/ private final static Map> buffers = new HashMap>(); @@ -74,19 +71,17 @@ public class FrameBuffer implements Disposable { /** depth **/ private final boolean hasDepth; - + /** 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 hasDepth whether to attach a depth buffer - * @throws GdxRuntimeException in case the FraeBuffer could not be created - */ + * @throws GdxRuntimeException in case the FraeBuffer could not be created */ public FrameBuffer (Pixmap.Format format, int width, int height, boolean hasDepth) { this.width = width; this.height = height; @@ -110,22 +105,23 @@ private void build () { gl.glGenFramebuffers(1, handle); framebufferHandle = handle.get(0); - if(hasDepth) { + if (hasDepth) { gl.glGenRenderbuffers(1, handle); depthbufferHandle = handle.get(0); } gl.glBindTexture(GL20.GL_TEXTURE_2D, colorTexture.getTextureObjectHandle()); - - if(hasDepth) { + + if (hasDepth) { gl.glBindRenderbuffer(GL20.GL_RENDERBUFFER, depthbufferHandle); - gl.glRenderbufferStorage(GL20.GL_RENDERBUFFER, GL20.GL_DEPTH_COMPONENT16, colorTexture.getWidth(), colorTexture.getHeight()); + 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); - if(hasDepth) { + if (hasDepth) { gl.glFramebufferRenderbuffer(GL20.GL_FRAMEBUFFER, GL20.GL_DEPTH_ATTACHMENT, GL20.GL_RENDERBUFFER, depthbufferHandle); } int result = gl.glCheckFramebufferStatus(GL20.GL_FRAMEBUFFER); @@ -136,7 +132,7 @@ private void build () { if (result != GL20.GL_FRAMEBUFFER_COMPLETE) { colorTexture.dispose(); - if(hasDepth) { + if (hasDepth) { handle.put(depthbufferHandle); handle.flip(); gl.glDeleteRenderbuffers(1, handle); @@ -156,9 +152,7 @@ private void build () { } } - /** - * Releases all resources associated with the FrameBuffer. - */ + /** Releases all resources associated with the FrameBuffer. */ public void dispose () { GL20 gl = Gdx.graphics.getGL20(); @@ -167,7 +161,7 @@ public void dispose () { IntBuffer handle = tmp.asIntBuffer(); colorTexture.dispose(); - if(hasDepth) { + if (hasDepth) { handle.put(depthbufferHandle); handle.flip(); gl.glDeleteRenderbuffers(1, handle); @@ -177,20 +171,16 @@ public void dispose () { handle.flip(); gl.glDeleteFramebuffers(1, handle); - if(buffers.get(Gdx.app) != null) buffers.get(Gdx.app).remove(this); + if (buffers.get(Gdx.app) != null) buffers.get(Gdx.app).remove(this); } - /** - * Makes the frame buffer current so everything gets drawn to it. - */ + /** 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); } - /** - * Unbinds the framebuffer, all drawing will be performed to the normal framebuffer from here on. - */ + /** 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); @@ -198,20 +188,18 @@ public void end () { private void addManagedFrameBuffer (Application app, FrameBuffer frameBuffer) { List managedResources = buffers.get(app); - if(managedResources == null) managedResources = new ArrayList(); + if (managedResources == null) managedResources = new ArrayList(); managedResources.add(frameBuffer); buffers.put(app, managedResources); } - - /** - * 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 (Application app) { if (Gdx.graphics.getGL20() == null) return; List bufferList = buffers.get(app); - if(bufferList == null) return; + if (bufferList == null) return; for (int i = 0; i < bufferList.size(); i++) { bufferList.get(i).build(); } @@ -220,12 +208,12 @@ public static void invalidateAllFrameBuffers (Application app) { public static void clearAllFrameBuffers (Application app) { buffers.remove(app); } - - public static String getManagedStatus() { + + public static String getManagedStatus () { StringBuilder builder = new StringBuilder(); int i = 0; builder.append("Managed buffers/app: { "); - for(Application app: buffers.keySet()) { + for (Application app : buffers.keySet()) { builder.append(buffers.get(app).size()); builder.append(" "); } @@ -233,23 +221,17 @@ public static String getManagedStatus() { return builder.toString(); } - /** - * @return the color buffer texture - */ + /** @return the color buffer texture */ public Texture getColorBufferTexture () { return colorTexture; } - /** - * @return the height of the framebuffer in pixels - */ + /** @return the height of the framebuffer in pixels */ public int getHeight () { return colorTexture.getHeight(); } - /** - * @return the width of the framebuffer in pixels - */ + /** @return the width of the framebuffer in pixels */ public int getWidth () { return colorTexture.getWidth(); } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer10.java b/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer10.java index ca21d8fef30..f1a2cec94a1 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer10.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer10.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -26,20 +27,17 @@ import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.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 ImmediateModeRenderer10#begin(int)} 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 +/** 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 ImmediateModeRenderer10#begin(int)} 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 ImmediateModeRenderer10#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. + * geometry you have to call {@link ImmediateModeRenderer10#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 - * - */ + * @author mzechner */ public class ImmediateModeRenderer10 implements ImmediateModeRenderer { /** the primitive type **/ private int primitiveType; @@ -70,16 +68,12 @@ public class ImmediateModeRenderer10 implements ImmediateModeRenderer { private boolean hasNors; private boolean hasTexCoords; - /** - * Constructs a new ImmediateModeRenderer - */ + /** Constructs a new ImmediateModeRenderer */ public ImmediateModeRenderer10 () { this(2000); } - /** - * Constructs a new ImmediateModeRenderer - */ + /** Constructs a new ImmediateModeRenderer */ public ImmediateModeRenderer10 (int maxVertices) { if (Gdx.graphics.isGL20Available()) throw new GdxRuntimeException("ImmediateModeRenderer can only be used with OpenGL ES 1.0/1.1"); @@ -109,12 +103,10 @@ public void begin (Matrix4 projModelView, int primitiveType) { begin(primitiveType); } - /** - * Starts a new list of primitives. The primitiveType specifies which primitives to draw. Can be any of GL10.GL_TRIANGLES, + /** 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. - */ + * @param primitiveType the primitive type. */ public void begin (int primitiveType) { this.primitiveType = primitiveType; idxPos = 0; @@ -126,13 +118,11 @@ public void begin (int primitiveType) { hasTexCoords = false; } - /** - * Specifies the color of the current vertex + /** Specifies the color of the current vertex * @param r the red component * @param g the green component * @param b the blue component - * @param a the alpha component - */ + * @param a the alpha component */ public void color (float r, float g, float b, float a) { colors[idxCols] = r; colors[idxCols + 1] = g; @@ -141,12 +131,10 @@ public void color (float r, float g, float b, float a) { hasCols = true; } - /** - * Specifies the normal of the current vertex + /** Specifies the normal of the current vertex * @param x the x component * @param y the y component - * @param z the z component - */ + * @param z the z component */ public void normal (float x, float y, float z) { normals[idxNors] = x; normals[idxNors + 1] = y; @@ -154,25 +142,21 @@ public void normal (float x, float y, float z) { hasNors = true; } - /** - * Specifies the texture coordinates of the current vertex + /** Specifies the texture coordinates of the current vertex * @param u the u coordinate - * @param v the v coordinate - */ + * @param v the v coordinate */ public void texCoord (float u, float v) { texCoords[idxTexCoords] = u; texCoords[idxTexCoords + 1] = v; hasTexCoords = true; } - /** - * Specifies the position of the current vertex and finalizes it. After a call to this method you will effectively define a new + /** 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 - */ + * @param z the z component */ public void vertex (float x, float y, float z) { positions[idxPos++] = x; positions[idxPos++] = y; @@ -187,9 +171,7 @@ public int getNumVertices () { return idxPos / 3; } - /** - * Renders the primitives just defined. - */ + /** Renders the primitives just defined. */ public void end () { if (idxPos == 0) return; diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer20.java b/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer20.java index f545c0a789d..6a80e287dbb 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer20.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/ImmediateModeRenderer20.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.glutils; import com.badlogic.gdx.graphics.Color; @@ -8,182 +9,178 @@ import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * Immediate mode rendering class for GLES 2.0. The renderer will allow you to - * specify vertices on the fly and provides a default shader for (unlit) rendering.

        * +/** Immediate mode rendering class for GLES 2.0. The renderer will allow you to specify vertices on the fly and provides a default + * shader for (unlit) rendering.

        * * - * @author mzechner - * - */ -public class ImmediateModeRenderer20 implements ImmediateModeRenderer { - int primitiveType; + * @author mzechner */ +public class ImmediateModeRenderer20 implements ImmediateModeRenderer { + int primitiveType; int vertexIdx; int numSetTexCoords; - + final Mesh mesh; final int numTexCoords; final int vertexSize; final int normalOffset; - final int colorOffset; + final int colorOffset; final int texCoordOffset; - final Matrix4 projModelView = new Matrix4(); + final Matrix4 projModelView = new Matrix4(); final float[] vertices; ShaderProgram customShader; final ShaderProgram defaultShader; - - public ImmediateModeRenderer20(boolean hasNormals, boolean hasColors, int numTexCoords) { + + public ImmediateModeRenderer20 (boolean hasNormals, boolean hasColors, int numTexCoords) { this(5000, hasNormals, hasColors, numTexCoords); } - - public ImmediateModeRenderer20(int maxVertices, boolean hasNormals, boolean hasColors, int numTexCoords) { + + public ImmediateModeRenderer20 (int maxVertices, boolean hasNormals, boolean hasColors, int numTexCoords) { VertexAttribute[] attribs = buildVertexAttributes(hasNormals, hasColors, numTexCoords); mesh = new Mesh(false, maxVertices, 0, attribs); String vertexShader = createVertexShader(hasNormals, hasColors, numTexCoords); - String fragmentShader = createFragmentShader(hasNormals, hasColors, numTexCoords); - + String fragmentShader = createFragmentShader(hasNormals, hasColors, numTexCoords); + defaultShader = new ShaderProgram(vertexShader, fragmentShader); - if(!defaultShader.isCompiled()) throw new GdxRuntimeException("Couldn't compile immediate mode default shader!\n" + defaultShader.getLog()); - + if (!defaultShader.isCompiled()) + throw new GdxRuntimeException("Couldn't compile immediate mode default shader!\n" + defaultShader.getLog()); + this.numTexCoords = numTexCoords; vertices = new float[maxVertices * (mesh.getVertexAttributes().vertexSize / 4)]; vertexSize = mesh.getVertexAttributes().vertexSize / 4; - normalOffset = mesh.getVertexAttribute(Usage.Normal)!= null? mesh.getVertexAttribute(Usage.Normal).offset / 4: 0; - colorOffset = mesh.getVertexAttribute(Usage.ColorPacked)!= null? mesh.getVertexAttribute(Usage.ColorPacked).offset / 4: 0; - texCoordOffset = mesh.getVertexAttribute(Usage.TextureCoordinates)!= null? mesh.getVertexAttribute(Usage.TextureCoordinates).offset / 4: 0; + normalOffset = mesh.getVertexAttribute(Usage.Normal) != null ? mesh.getVertexAttribute(Usage.Normal).offset / 4 : 0; + colorOffset = mesh.getVertexAttribute(Usage.ColorPacked) != null ? mesh.getVertexAttribute(Usage.ColorPacked).offset / 4 + : 0; + texCoordOffset = mesh.getVertexAttribute(Usage.TextureCoordinates) != null ? mesh + .getVertexAttribute(Usage.TextureCoordinates).offset / 4 : 0; } private VertexAttribute[] buildVertexAttributes (boolean hasNormals, boolean hasColor, int numTexCoords) { Array attribs = new Array(); attribs.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); - if(hasNormals) attribs.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); - if(hasColor) attribs.add(new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE)); - for(int i = 0; i < numTexCoords; i++) { + if (hasNormals) attribs.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); + if (hasColor) attribs.add(new VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE)); + for (int i = 0; i < numTexCoords; i++) { attribs.add(new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + i)); } VertexAttribute[] array = new VertexAttribute[attribs.size]; - for(int i = 0; i < attribs.size; i++) array[i] = attribs.get(i); + for (int i = 0; i < attribs.size; i++) + array[i] = attribs.get(i); return array; } - - public String createVertexShader(boolean hasNormals, boolean hasColors, int numTexCoords) { - String shader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" - + (hasNormals?"attribute vec3 " + ShaderProgram.NORMAL_ATTRIBUTE + ";\n": "") - + (hasColors?"attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n": ""); - - for(int i = 0; i < numTexCoords; i++) { + + public String createVertexShader (boolean hasNormals, boolean hasColors, int numTexCoords) { + String shader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + + (hasNormals ? "attribute vec3 " + ShaderProgram.NORMAL_ATTRIBUTE + ";\n" : "") + + (hasColors ? "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" : ""); + + for (int i = 0; i < numTexCoords; i++) { shader += "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + i + ";\n"; } - - shader += "uniform mat4 u_projModelView;\n"; - shader += (hasColors?"varying vec4 v_col;\n":""); - for(int i = 0; i < numTexCoords; i++) { + shader += "uniform mat4 u_projModelView;\n"; + shader += (hasColors ? "varying vec4 v_col;\n" : ""); + + for (int i = 0; i < numTexCoords; i++) { shader += "varying vec2 v_tex" + i + ";\n"; } - - shader += "void main() {\n" - + " gl_Position = u_projModelView * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" - + (hasColors?" v_col = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n":""); - - for(int i = 0; i < numTexCoords; i++) { + + shader += "void main() {\n" + " gl_Position = u_projModelView * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + + (hasColors ? " v_col = " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" : ""); + + for (int i = 0; i < numTexCoords; i++) { shader += " v_tex" + i + " = " + ShaderProgram.TEXCOORD_ATTRIBUTE + i + ";\n"; } - + shader += "}\n"; - + return shader; } - + private String createFragmentShader (boolean hasNormals, boolean hasColors, int numTexCoords) { - String shader = "#ifdef GL_ES\n" - + "precision highp float;\n" - + "#endif\n"; - - if(hasColors) shader += "varying vec4 v_col;\n"; - for(int i = 0; i < numTexCoords; i++) { + String shader = "#ifdef GL_ES\n" + "precision highp float;\n" + "#endif\n"; + + if (hasColors) shader += "varying vec4 v_col;\n"; + for (int i = 0; i < numTexCoords; i++) { shader += "varying vec2 v_tex" + i + ";\n"; shader += "uniform sampler2D u_sampler" + i + ";\n"; } - - shader += "void main() {\n" - + " gl_FragColor = " - + (hasColors?"v_col": "vec4(1, 1, 1, 1)"); - - if(numTexCoords > 0) shader +=" * "; - - for(int i = 0; i < numTexCoords; i++) { - if(i == numTexCoords - 1) { + + shader += "void main() {\n" + " gl_FragColor = " + (hasColors ? "v_col" : "vec4(1, 1, 1, 1)"); + + if (numTexCoords > 0) shader += " * "; + + for (int i = 0; i < numTexCoords; i++) { + if (i == numTexCoords - 1) { shader += " texture2D(u_sampler" + i + ", v_tex" + i + ")"; } else { shader += " texture2D(u_sampler" + i + ", v_tex" + i + ") *"; } } - - shader += ";\n}"; - + + shader += ";\n}"; + return shader; } - - public void begin(Matrix4 projModelView, int primitiveType) { + + public void begin (Matrix4 projModelView, int primitiveType) { this.customShader = null; this.projModelView.set(projModelView); this.primitiveType = primitiveType; } - - public void begin(ShaderProgram shader, int primitiveType) { - this.customShader = shader; + + public void begin (ShaderProgram shader, int primitiveType) { + this.customShader = shader; this.primitiveType = primitiveType; } - - public void color(float r, float g, float b, float a) { - vertices[vertexIdx + colorOffset] = Color.toFloatBits(r, g, b, a); + + public void color (float r, float g, float b, float a) { + vertices[vertexIdx + colorOffset] = Color.toFloatBits(r, g, b, a); } - - public void texCoord(float u, float v) { + + public void texCoord (float u, float v) { final int idx = vertexIdx + texCoordOffset; vertices[idx] = u; vertices[idx + 1] = v; numSetTexCoords += 2; } - - public void normal(float x, float y, float z) { - final int idx = vertexIdx + normalOffset; + + public void normal (float x, float y, float z) { + final int idx = vertexIdx + normalOffset; vertices[idx] = x; vertices[idx + 1] = y; vertices[idx + 2] = z; } - - public void vertex(float x, float y, float z) { + + public void vertex (float x, float y, float z) { final int idx = vertexIdx; vertices[idx] = x; vertices[idx + 1] = y; vertices[idx + 2] = z; - + numSetTexCoords = 0; - vertexIdx += vertexSize; + vertexIdx += vertexSize; } - - public void end() { - if(customShader != null) { - customShader.begin(); + + public void end () { + if (customShader != null) { + customShader.begin(); mesh.setVertices(vertices, 0, vertexIdx); - mesh.render(customShader, primitiveType); + mesh.render(customShader, primitiveType); customShader.end(); } else { defaultShader.begin(); defaultShader.setUniformMatrix("u_projModelView", projModelView); - for(int i = 0; i < numTexCoords; i++) { + for (int i = 0; i < numTexCoords; i++) { defaultShader.setUniformi("u_sampler" + i, i); - } + } mesh.setVertices(vertices, 0, vertexIdx); - mesh.render(defaultShader, primitiveType); + mesh.render(defaultShader, primitiveType); defaultShader.end(); } - + numSetTexCoords = 0; vertexIdx = 0; } - + public int getNumVertices () { return vertexIdx / 3; } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObject.java b/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObject.java index b758ac074c7..ad69c6cc449 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObject.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObject.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -26,8 +27,7 @@ import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * In IndexBufferObject wraps OpenGL's index buffer functionality to be used in conjunction with VBOs. This class can be * seamlessly used with OpenGL ES 1.x and 2.0. *

        @@ -46,9 +46,7 @@ * VertexBufferObjects must be disposed via the {@link #dispose()} method when no longer needed *

        * - * @author mzechner - * - */ + * @author mzechner */ public class IndexBufferObject implements IndexData { final static IntBuffer tmpHandle = BufferUtils.newIntBuffer(1); @@ -60,12 +58,10 @@ public class IndexBufferObject implements IndexData { boolean isBound = false; final int usage; - /** - * Creates a new IndexBufferObject. + /** Creates a new IndexBufferObject. * * @param isStatic whether the index buffer is static - * @param maxIndices the maximum number of indices this buffer can hold - */ + * @param maxIndices the maximum number of indices this buffer can hold */ public IndexBufferObject (boolean isStatic, int maxIndices) { // if (Gdx.app.getType() == ApplicationType.Android // && Gdx.app.getVersion() < 5) { @@ -84,11 +80,9 @@ public IndexBufferObject (boolean isStatic, int maxIndices) { usage = isStatic ? GL11.GL_STATIC_DRAW : GL11.GL_DYNAMIC_DRAW; } - /** - * Creates a new IndexBufferObject to be used with vertex arrays. + /** Creates a new IndexBufferObject to be used with vertex arrays. * - * @param maxIndices the maximum number of indices this buffer can hold - */ + * @param maxIndices the maximum number of indices this buffer can hold */ public IndexBufferObject (int maxIndices) { byteBuffer = ByteBuffer.allocateDirect(maxIndices * 2); byteBuffer.order(ByteOrder.nativeOrder()); @@ -113,22 +107,17 @@ private int createBufferObject () { return 0; } - /** - * @return the number of indices currently stored in this buffer - */ + /** @return the number of indices currently stored in this buffer */ public int getNumIndices () { return buffer.limit(); } - /** - * @return the maximum number of indices this IndexBufferObject can store. - */ + /** @return the maximum number of indices this IndexBufferObject can store. */ public int getNumMaxIndices () { return buffer.capacity(); } - /** - *

        + /**

        * Sets the indices of this IndexBufferObject, discarding the old indices. The count must equal the number of indices to be * copied to this IndexBufferObject. *

        @@ -139,8 +128,7 @@ public int getNumMaxIndices () { * * @param indices the vertex data * @param offset the offset to start copying the data from - * @param count the number of shorts to copy - */ + * @param count the number of shorts to copy */ public void setIndices (short[] indices, int offset, int count) { isDirty = true; buffer.clear(); @@ -161,22 +149,18 @@ public void setIndices (short[] indices, int offset, int count) { } } - /** - *

        + /**

        * Returns the underlying ShortBuffer. If you modify the buffer contents they wil be uploaded on the call to {@link #bind()}. * If you need immediate uploading use {@link #setIndices(short[], int, int)}. *

        * - * @return the underlying short buffer. - */ + * @return the underlying short buffer. */ public ShortBuffer getBuffer () { isDirty = true; return buffer; } - /** - * Binds this IndexBufferObject for rendering with glDrawElements. - */ + /** Binds this IndexBufferObject for rendering with glDrawElements. */ public void bind () { if (bufferHandle == 0) throw new GdxRuntimeException("buuh"); @@ -200,9 +184,7 @@ public void bind () { isBound = true; } - /** - * Unbinds this IndexBufferObject. - */ + /** Unbinds this IndexBufferObject. */ public void unbind () { if (Gdx.gl11 != null) { Gdx.gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); @@ -212,17 +194,13 @@ public void unbind () { isBound = false; } - /** - * Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. - */ + /** Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. */ public void invalidate () { bufferHandle = createBufferObject(); isDirty = true; } - /** - * Disposes this IndexBufferObject and all its associated OpenGL resources. - */ + /** Disposes this IndexBufferObject and all its associated OpenGL resources. */ public void dispose () { if (Gdx.gl20 != null) { tmpHandle.clear(); diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObjectSubData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObjectSubData.java index e9ec82bcd26..e88ddaa8c6d 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObjectSubData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/IndexBufferObjectSubData.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -26,8 +27,7 @@ import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * In IndexBufferObject wraps OpenGL's index buffer functionality to be used in conjunction with VBOs. This class can be * seamlessly used with OpenGL ES 1.x and 2.0. *

        @@ -46,9 +46,7 @@ * VertexBufferObjects must be disposed via the {@link #dispose()} method when no longer needed *

        * - * @author mzechner - * - */ + * @author mzechner */ public class IndexBufferObjectSubData implements IndexData { final static IntBuffer tmpHandle = BufferUtils.newIntBuffer(1); @@ -60,12 +58,10 @@ public class IndexBufferObjectSubData implements IndexData { boolean isBound = false; final int usage; - /** - * Creates a new IndexBufferObject. + /** Creates a new IndexBufferObject. * * @param isStatic whether the index buffer is static - * @param maxIndices the maximum number of indices this buffer can hold - */ + * @param maxIndices the maximum number of indices this buffer can hold */ public IndexBufferObjectSubData (boolean isStatic, int maxIndices) { // if (Gdx.app.getType() == ApplicationType.Android // && Gdx.app.getVersion() < 5) { @@ -84,11 +80,9 @@ public IndexBufferObjectSubData (boolean isStatic, int maxIndices) { bufferHandle = createBufferObject(); } - /** - * Creates a new IndexBufferObject to be used with vertex arrays. + /** Creates a new IndexBufferObject to be used with vertex arrays. * - * @param maxIndices the maximum number of indices this buffer can hold - */ + * @param maxIndices the maximum number of indices this buffer can hold */ public IndexBufferObjectSubData (int maxIndices) { byteBuffer = ByteBuffer.allocateDirect(maxIndices * 2); byteBuffer.order(ByteOrder.nativeOrder()); @@ -119,22 +113,17 @@ private int createBufferObject () { return 0; } - /** - * @return the number of indices currently stored in this buffer - */ + /** @return the number of indices currently stored in this buffer */ public int getNumIndices () { return buffer.limit(); } - /** - * @return the maximum number of indices this IndexBufferObject can store. - */ + /** @return the maximum number of indices this IndexBufferObject can store. */ public int getNumMaxIndices () { return buffer.capacity(); } - /** - *

        + /**

        * Sets the indices of this IndexBufferObject, discarding the old indices. The count must equal the number of indices to be * copied to this IndexBufferObject. *

        @@ -145,8 +134,7 @@ public int getNumMaxIndices () { * * @param indices the vertex data * @param offset the offset to start copying the data from - * @param count the number of floats to copy - */ + * @param count the number of floats to copy */ public void setIndices (short[] indices, int offset, int count) { isDirty = true; buffer.clear(); @@ -172,22 +160,18 @@ public void setIndices (short[] indices, int offset, int count) { } } - /** - *

        + /**

        * Returns the underlying ShortBuffer. If you modify the buffer contents they wil be uploaded on the call to {@link #bind()}. * If you need immediate uploading use {@link #setIndices(short[], int, int)}. *

        * - * @return the underlying short buffer. - */ + * @return the underlying short buffer. */ public ShortBuffer getBuffer () { isDirty = true; return buffer; } - /** - * Binds this IndexBufferObject for rendering with glDrawElements. - */ + /** Binds this IndexBufferObject for rendering with glDrawElements. */ public void bind () { if (bufferHandle == 0) throw new GdxRuntimeException("buuh"); @@ -215,9 +199,7 @@ public void bind () { isBound = true; } - /** - * Unbinds this IndexBufferObject. - */ + /** Unbinds this IndexBufferObject. */ public void unbind () { if (Gdx.gl11 != null) { Gdx.gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); @@ -227,17 +209,13 @@ public void unbind () { isBound = false; } - /** - * Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. - */ + /** Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. */ public void invalidate () { bufferHandle = createBufferObject(); isDirty = true; } - /** - * Disposes this IndexBufferObject and all its associated OpenGL resources. - */ + /** Disposes this IndexBufferObject and all its associated OpenGL resources. */ public void dispose () { if (Gdx.gl20 != null) { tmpHandle.clear(); diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/IndexData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/IndexData.java index 9e3a9e4da82..d1bf840f485 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/IndexData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/IndexData.java @@ -13,30 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ShortBuffer; import com.badlogic.gdx.utils.Disposable; -/** - * An IndexData instance holds index data. Can be either a plain short buffer or an OpenGL buffer object. - * @author mzechner - * - */ +/** An IndexData instance holds index data. Can be either a plain short buffer or an OpenGL buffer object. + * @author mzechner */ public interface IndexData extends Disposable { - /** - * @return the number of indices currently stored in this buffer - */ + /** @return the number of indices currently stored in this buffer */ public int getNumIndices (); - /** - * @return the maximum number of indices this IndexBufferObject can store. - */ + /** @return the maximum number of indices this IndexBufferObject can store. */ public int getNumMaxIndices (); - /** - *

        + /**

        * Sets the indices of this IndexBufferObject, discarding the old indices. The count must equal the number of indices to be * copied to this IndexBufferObject. *

        @@ -47,37 +40,26 @@ public interface IndexData extends Disposable { * * @param indices the vertex data * @param offset the offset to start copying the data from - * @param count the number of floats to copy - */ + * @param count the number of floats to copy */ public void setIndices (short[] indices, int offset, int count); - /** - *

        + /**

        * Returns the underlying ShortBuffer. If you modify the buffer contents they wil be uploaded on the call to {@link #bind()}. * If you need immediate uploading use {@link #setIndices(short[], int, int)}. *

        * - * @return the underlying short buffer. - */ + * @return the underlying short buffer. */ public ShortBuffer getBuffer (); - /** - * Binds this IndexBufferObject for rendering with glDrawElements. - */ + /** Binds this IndexBufferObject for rendering with glDrawElements. */ public void bind (); - /** - * Unbinds this IndexBufferObject. - */ + /** Unbinds this IndexBufferObject. */ public void unbind (); - /** - * Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. - */ + /** Invalidates the IndexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. */ public void invalidate (); - /** - * Disposes this IndexDatat and all its associated OpenGL resources. - */ + /** Disposes this IndexDatat and all its associated OpenGL resources. */ public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java b/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java index f0b2a208e5b..3c56b88599b 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/MipMapGenerator.java @@ -1,7 +1,8 @@ + package com.badlogic.gdx.graphics.glutils; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Application.ApplicationType; +import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GLCommon; @@ -12,26 +13,22 @@ public class MipMapGenerator { private static boolean useHWMipMap = true; - static public void setUseHardwareMipMap(boolean useHWMipMap) { + static public void setUseHardwareMipMap (boolean useHWMipMap) { MipMapGenerator.useHWMipMap = useHWMipMap; } - - /** - * Sets the image data of the {@link Texture} based on the {@link Pixmap}. The texture - * must be bound for this to work. If disposePixmap is true, the pixmap - * will be disposed at the end of the method. + + /** Sets the image data of the {@link Texture} based on the {@link Pixmap}. The texture must be bound for this to work. If + * disposePixmap is true, the pixmap will be disposed at the end of the method. * @param pixmap the Pixmap - * @param texture the Texture - * @param disposePixmap whether to dispose the Pixmap after upload - */ - public static void generateMipMap(Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { - if(!useHWMipMap) { + * @param disposePixmap whether to dispose the Pixmap after upload */ + public static void generateMipMap (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { + if (!useHWMipMap) { generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); return; } - - if(Gdx.app.getType() == ApplicationType.Android) { - if(Gdx.graphics.isGL20Available()) + + if (Gdx.app.getType() == ApplicationType.Android) { + if (Gdx.graphics.isGL20Available()) generateMipMapGLES20(pixmap, disposePixmap); else generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); @@ -39,47 +36,51 @@ public static void generateMipMap(Pixmap pixmap, int textureWidth, int textureHe generateMipMapDesktop(pixmap, textureWidth, textureHeight, disposePixmap); } } - - private static void generateMipMapGLES20(Pixmap pixmap, boolean disposePixmap) { - Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + + private static void generateMipMapGLES20 (Pixmap pixmap, boolean disposePixmap) { + Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D); - if(disposePixmap) pixmap.dispose(); + if (disposePixmap) pixmap.dispose(); } - - private static void generateMipMapDesktop(Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { - if(Gdx.graphics.isGL20Available() && - (Gdx.graphics.supportsExtension("GL_ARB_framebuffer_object") || - Gdx.graphics.supportsExtension("GL_EXT_framebuffer_object"))) { - Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + + private static void generateMipMapDesktop (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { + if (Gdx.graphics.isGL20Available() + && (Gdx.graphics.supportsExtension("GL_ARB_framebuffer_object") || Gdx.graphics + .supportsExtension("GL_EXT_framebuffer_object"))) { + Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D); - if(disposePixmap) pixmap.dispose(); - } else if(Gdx.graphics.supportsExtension("GL_SGIS_generate_mipmap")) { - if((Gdx.gl20==null) && textureWidth != textureHeight) + if (disposePixmap) pixmap.dispose(); + } else if (Gdx.graphics.supportsExtension("GL_SGIS_generate_mipmap")) { + if ((Gdx.gl20 == null) && textureWidth != textureHeight) throw new GdxRuntimeException("texture width and height must be square when using mipmapping in OpenGL ES 1.x"); Gdx.gl.glTexParameterf(GL20.GL_TEXTURE_2D, GLCommon.GL_GENERATE_MIPMAP, GL10.GL_TRUE); - Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); - if(disposePixmap) pixmap.dispose(); + Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + if (disposePixmap) pixmap.dispose(); } else { generateMipMapCPU(pixmap, textureWidth, textureHeight, disposePixmap); - } + } } - - private static void generateMipMapCPU(Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { - Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); - if((Gdx.gl20==null) && textureWidth != textureHeight) + + private static void generateMipMapCPU (Pixmap pixmap, int textureWidth, int textureHeight, boolean disposePixmap) { + Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + if ((Gdx.gl20 == null) && textureWidth != textureHeight) throw new GdxRuntimeException("texture width and height must be square when using mipmapping."); int width = pixmap.getWidth() / 2; int height = pixmap.getHeight() / 2; int level = 1; - while(width > 0 && height > 0) { - Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); + while (width > 0 && height > 0) { + Pixmap tmp = new Pixmap(width, height, pixmap.getFormat()); tmp.drawPixmap(pixmap, 0, 0, pixmap.getWidth(), pixmap.getHeight(), 0, 0, width, height); - if(level > 1 || disposePixmap) - pixmap.dispose(); + if (level > 1 || disposePixmap) pixmap.dispose(); pixmap = tmp; - - Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); - + + Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, level, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + width = pixmap.getWidth() / 2; height = pixmap.getHeight() / 2; level++; diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/PixmapTextureData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/PixmapTextureData.java index 670147e0449..a5b7de64f05 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/PixmapTextureData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/PixmapTextureData.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.graphics.glutils; import com.badlogic.gdx.graphics.Pixmap; @@ -10,19 +11,19 @@ public class PixmapTextureData implements TextureData { final Format format; final boolean useMipMaps; final boolean disposePixmap; - - public PixmapTextureData(Pixmap pixmap, Format format, boolean useMipMaps, boolean disposePixmap) { + + public PixmapTextureData (Pixmap pixmap, Format format, boolean useMipMaps, boolean disposePixmap) { this.pixmap = pixmap; - this.format = format == null? pixmap.getFormat(): format; + this.format = format == null ? pixmap.getFormat() : format; this.useMipMaps = useMipMaps; this.disposePixmap = disposePixmap; } - + @Override public boolean disposePixmap () { return disposePixmap; } - + @Override public Pixmap getPixmap () { return pixmap; @@ -60,6 +61,6 @@ public TextureDataType getType () { @Override public void uploadCompressedData () { - throw new GdxRuntimeException("This TextureData implementation does not upload data itself"); + throw new GdxRuntimeException("This TextureData implementation does not upload data itself"); } } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/ShaderProgram.java b/gdx/src/com/badlogic/gdx/graphics/glutils/ShaderProgram.java index 49390dc8e9e..f3e1259cc0d 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/ShaderProgram.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/ShaderProgram.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -34,8 +35,7 @@ import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.ObjectMap; -/** - *

        +/**

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

        * @@ -62,9 +62,7 @@ * automatically reloaded when the OpenGL context is recreated so you don't have to do this manually. *

        * - * @author mzechner - * - */ + * @author mzechner */ public class ShaderProgram implements Disposable { /** default name for position attributes **/ public static final String POSITION_ATTRIBUTE = "a_position"; @@ -78,10 +76,10 @@ public class ShaderProgram implements Disposable { public static final String TANGENT_ATTRIBUTE = "a_tangent"; /** default name for binormal attribute **/ public static final String BINORMAL_ATTRIBUTE = "a_binormal"; - + /** flag indicating whether attributes & uniforms must be present at all times **/ - public static boolean pedantic = true; - + public static boolean pedantic = true; + /** the list of currently available shaders **/ private final static Map> shaders = new HashMap>(); @@ -90,22 +88,22 @@ public class ShaderProgram implements Disposable { /** whether this program compiled succesfully **/ private boolean isCompiled; - + /** uniform lookup **/ private final ObjectMap uniforms = new ObjectMap(); /** uniform types **/ private final ObjectMap uniformTypes = new ObjectMap(); - + /** uniform names **/ private String[] uniformNames; - + /** attribute lookup **/ private final ObjectMap attributes = new ObjectMap(); - + /** attribute types **/ private final ObjectMap attributeTypes = new ObjectMap(); - + /** attribute names **/ private String[] attributeNames; @@ -134,16 +132,14 @@ public class ShaderProgram implements Disposable { private ByteBuffer buffer = null; private FloatBuffer floatBuffer = null; private IntBuffer intBuffer = null; - + /** reference count **/ private int refCount = 0; - - /** - * Construcs a new JOglShaderProgram and immediatly compiles it. + + /** Construcs a new JOglShaderProgram and immediatly compiles it. * * @param vertexShader the vertex shader - * @param fragmentShader the fragment shader - */ + * @param fragmentShader the fragment shader */ public ShaderProgram (String vertexShader, String fragmentShader) { if (vertexShader == null) throw new IllegalArgumentException("vertex shader must not be null"); @@ -153,20 +149,18 @@ public ShaderProgram (String vertexShader, String fragmentShader) { this.fragmentShaderSource = fragmentShader; this.matrix = BufferUtils.newFloatBuffer(16); - compileShaders(vertexShader, fragmentShader); - if(isCompiled()) { + compileShaders(vertexShader, fragmentShader); + if (isCompiled()) { fetchAttributes(); - fetchUniforms(); - addManagedShader(Gdx.app, this); + fetchUniforms(); + addManagedShader(Gdx.app, this); } } - /** - * Loads and compiles the shaders, creates a new program and links the shaders. + /** Loads and compiles the shaders, creates a new program and links the shaders. * * @param vertexShader - * @param fragmentShader - */ + * @param fragmentShader */ private void compileShaders (String vertexShader, String fragmentShader) { vertexShaderHandle = loadShader(GL20.GL_VERTEX_SHADER, vertexShader); fragmentShaderHandle = loadShader(GL20.GL_FRAGMENT_SHADER, fragmentShader); @@ -235,25 +229,21 @@ private int linkProgram () { } final static IntBuffer intbuf = BufferUtils.newIntBuffer(1); - - /** - * @return the log info for the shader compilation and program linking stage. The shader needs to be bound for this - * method to have an effect. - */ + + /** @return the log info for the shader compilation and program linking stage. The shader needs to be bound for this method to + * have an effect. */ public String getLog () { - if(isCompiled) { + if (isCompiled) { Gdx.gl20.glGetProgramiv(program, GL20.GL_INFO_LOG_LENGTH, intbuf); int infoLogLength = intbuf.get(0); if (infoLogLength > 1) log = Gdx.gl20.glGetProgramInfoLog(program); return log; } else { return log; - } + } } - /** - * @return whether this ShaderProgram compiled successfully. - */ + /** @return whether this ShaderProgram compiled successfully. */ public boolean isCompiled () { return isCompiled; } @@ -279,13 +269,11 @@ private int fetchUniformLocation (String name) { return location; } - /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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 - */ + * @param value the value */ public void setUniformi (String name, int value) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -293,14 +281,12 @@ public void setUniformi (String name, int value) { gl.glUniform1i(location, value); } - /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -308,15 +294,13 @@ public void setUniformi (String name, int value1, int 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 + /** 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) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -324,16 +308,14 @@ public void setUniformi (String name, int value1, int value2, int 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 + /** 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 value4 the fourth value - */ + * @param value4 the fourth value */ public void setUniformi (String name, int value1, int value2, int value3, int value4) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -341,13 +323,11 @@ public void setUniformi (String name, int value1, int value2, int value3, int va 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 + /** 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 - */ + * @param value the value */ public void setUniformf (String name, float value) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -355,14 +335,12 @@ public void setUniformf (String name, float value) { gl.glUniform1f(location, value); } - /** - * Sets the uniform with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -370,15 +348,13 @@ public void setUniformf (String name, float value1, float 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 + /** 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) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -386,24 +362,22 @@ public void setUniformf (String name, float value1, float value2, float 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 + /** 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 value4 the fourth value - */ + * @param value4 the fourth value */ public void setUniformf (String name, float value1, float value2, float value3, float value4) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); int location = fetchUniformLocation(name); gl.glUniform4f(location, value1, value2, value3, value4); } - - public void setUniform1fv(String name, float[] values, int offset, int length) { + + public void setUniform1fv (String name, float[] values, int offset, int length) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); int location = fetchUniformLocation(name); @@ -412,8 +386,8 @@ public void setUniform1fv(String name, float[] values, int offset, int length) { BufferUtils.copy(values, floatBuffer, length, offset); gl.glUniform1fv(location, length, floatBuffer); } - - public void setUniform2fv(String name, float[] values, int offset, int length) { + + public void setUniform2fv (String name, float[] values, int offset, int length) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); int location = fetchUniformLocation(name); @@ -421,9 +395,9 @@ public void setUniform2fv(String name, float[] values, int offset, int length) { floatBuffer.clear(); BufferUtils.copy(values, floatBuffer, length, offset); gl.glUniform2fv(location, length / 2, floatBuffer); - } - - public void setUniform3fv(String name, float[] values, int offset, int length) { + } + + public void setUniform3fv (String name, float[] values, int offset, int length) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); int location = fetchUniformLocation(name); @@ -431,9 +405,9 @@ public void setUniform3fv(String name, float[] values, int offset, int length) { floatBuffer.clear(); BufferUtils.copy(values, floatBuffer, length, offset); gl.glUniform3fv(location, length / 3, floatBuffer); - } - - public void setUniform4fv(String name, float[] values, int offset, int length) { + } + + public void setUniform4fv (String name, float[] values, int offset, int length) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); int location = fetchUniformLocation(name); @@ -441,27 +415,23 @@ public void setUniform4fv(String name, float[] values, int offset, int length) { floatBuffer.clear(); BufferUtils.copy(values, floatBuffer, length, offset); gl.glUniform4fv(location, length / 4, floatBuffer); - } + } - /** - * Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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 - */ + * @param matrix the matrix */ public void setUniformMatrix (String name, Matrix4 matrix) { setUniformMatrix(name, matrix, false); } - /** - * Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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 - * @param transpose whether the matrix shouls be transposed - */ + * @param transpose whether the matrix shouls be transposed */ public void setUniformMatrix (String name, Matrix4 matrix, boolean transpose) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -471,25 +441,21 @@ public void setUniformMatrix (String name, Matrix4 matrix, boolean transpose) { gl.glUniformMatrix4fv(location, 1, transpose, this.matrix); } - /** - * Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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 - */ + * @param matrix the matrix */ public void setUniformMatrix (String name, Matrix3 matrix) { setUniformMatrix(name, matrix, false); } - /** - * Sets the uniform matrix with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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 - * @param transpose whether the uniform matrix should be transposed - */ + * @param transpose whether the uniform matrix should be transposed */ public void setUniformMatrix (String name, Matrix3 matrix, boolean transpose) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -500,8 +466,7 @@ public void setUniformMatrix (String name, Matrix3 matrix, boolean transpose) { gl.glUniformMatrix3fv(location, 1, transpose, this.matrix); } - /** - * Sets the vertex attribute with the given name. Throws an IllegalArgumentException in case it is not called in between a + /** 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 @@ -510,8 +475,7 @@ public void setUniformMatrix (String name, Matrix3 matrix, boolean transpose) { * 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. - */ + * @param buffer the buffer containing the vertex attributes. */ public void setVertexAttribute (String name, int size, int type, boolean normalize, int stride, FloatBuffer buffer) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -519,8 +483,7 @@ public void setVertexAttribute (String name, int size, int type, boolean normali 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 + /** 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 @@ -529,8 +492,7 @@ public void setVertexAttribute (String name, int size, int type, boolean normali * 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. - */ + * @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) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -539,42 +501,34 @@ public void setVertexAttribute (String name, int size, int type, boolean normali 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 () { GL20 gl = Gdx.graphics.getGL20(); 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 () { GL20 gl = Gdx.graphics.getGL20(); gl.glUseProgram(0); } - /** - * Disposes all resources associated with this shader. Must be called when the shader is no longer used. - */ - public void dispose () { + /** Disposes all resources associated with this shader. Must be called when the shader is no longer used. */ + public void dispose () { GL20 gl = Gdx.graphics.getGL20(); gl.glUseProgram(0); gl.glDeleteShader(vertexShaderHandle); gl.glDeleteShader(fragmentShaderHandle); gl.glDeleteProgram(program); - if(shaders.get(Gdx.app) != null) shaders.get(Gdx.app).remove(this); + if (shaders.get(Gdx.app) != null) shaders.get(Gdx.app).remove(this); } - /** - * Disables the vertex attribute with the given name + /** Disables the vertex attribute with the given name * - * @param name the vertex attribute name - */ + * @param name the vertex attribute name */ public void disableVertexAttribute (String name) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -583,11 +537,9 @@ public void disableVertexAttribute (String name) { gl.glDisableVertexAttribArray(location); } - /** - * Enables the vertex attribute with the given name + /** Enables the vertex attribute with the given name * - * @param name the vertex attribute name - */ + * @param name the vertex attribute name */ public void enableVertexAttribute (String name) { GL20 gl = Gdx.graphics.getGL20(); checkManaged(); @@ -605,21 +557,19 @@ private void checkManaged () { private void addManagedShader (Application app, ShaderProgram shaderProgram) { List managedResources = shaders.get(app); - if(managedResources == null) managedResources = new ArrayList(); + if (managedResources == null) managedResources = new ArrayList(); managedResources.add(shaderProgram); shaders.put(app, managedResources); } - - /** - * Invalidates all shaders so the next time they are used new handles are generated - * @param app - */ + + /** Invalidates all shaders so the next time they are used new handles are generated + * @param app */ public static void invalidateAllShaderPrograms (Application app) { if (Gdx.graphics.getGL20() == null) return; List shaderList = shaders.get(app); - if(shaderList == null) return; - + if (shaderList == null) return; + for (int i = 0; i < shaderList.size(); i++) { shaderList.get(i).invalidated = true; shaderList.get(i).checkManaged(); @@ -629,12 +579,12 @@ public static void invalidateAllShaderPrograms (Application app) { public static void clearAllShaderPrograms (Application app) { shaders.remove(app); } - - public static String getManagedStatus() { + + public static String getManagedStatus () { StringBuilder builder = new StringBuilder(); int i = 0; builder.append("Managed shaders/app: { "); - for(Application app: shaders.keySet()) { + for (Application app : shaders.keySet()) { builder.append(shaders.get(app).size()); builder.append(" "); } @@ -642,39 +592,38 @@ public static String getManagedStatus() { return builder.toString(); } - /** - * Sets the given attribute + /** Sets the given attribute * * @param name the name of the attribute * @param value1 the first value * @param value2 the second value * @param value3 the third value - * @param value4 the fourth value - */ + * @param value4 the fourth value */ 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); } - - private void ensureBufferCapacity(int numBytes) { - if(buffer == null || buffer.capacity() != numBytes) { + + private void ensureBufferCapacity (int numBytes) { + if (buffer == null || buffer.capacity() != numBytes) { buffer = BufferUtils.newByteBuffer(numBytes); floatBuffer = buffer.asFloatBuffer(); intBuffer = buffer.asIntBuffer(); } } - + IntBuffer params = BufferUtils.newIntBuffer(1); IntBuffer type = BufferUtils.newIntBuffer(1); - private void fetchUniforms() { + + private void fetchUniforms () { params.clear(); Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_UNIFORMS, params); int numUniforms = params.get(0); - + uniformNames = new String[numUniforms]; - - for(int i = 0; i < numUniforms; i++) { + + for (int i = 0; i < numUniforms; i++) { params.clear(); params.put(0, 256); type.clear(); @@ -685,15 +634,15 @@ private void fetchUniforms() { uniformNames[i] = name; } } - - private void fetchAttributes() { + + private void fetchAttributes () { params.clear(); Gdx.gl20.glGetProgramiv(program, GL20.GL_ACTIVE_ATTRIBUTES, params); int numAttributes = params.get(0); - + attributeNames = new String[numAttributes]; - - for(int i = 0; i < numAttributes; i++) { + + for (int i = 0; i < numAttributes; i++) { params.clear(); params.put(0, 256); type.clear(); @@ -701,77 +650,69 @@ private void fetchAttributes() { int location = Gdx.gl20.glGetAttribLocation(program, name); attributes.put(name, location); attributeTypes.put(name, type.get(0)); - attributeNames[i] = name; + attributeNames[i] = name; } - } - - /** - * @param name the name of the attribute - * @return whether the attribute is available in the shader - */ - public boolean hasAttribute(String name) { + } + + /** @param name the name of the attribute + * @return whether the attribute is available in the shader */ + public boolean hasAttribute (String name) { return attributes.containsKey(name); } - - /** - * @param name the name of the attribute - * @return the type of the attribute, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc. - */ - public int getAttributeType(String name) { + + /** @param name the name of the attribute + * @return the type of the attribute, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc. */ + public int getAttributeType (String name) { Integer type = attributes.get(name); - if(type == null) return 0; - else return type; + if (type == null) + return 0; + else + return type; } - - /** - * @param name the name of the attribute - * @return the location of the attribute or -1. - */ - public int getAttributeLocation(String name) { + + /** @param name the name of the attribute + * @return the location of the attribute or -1. */ + public int getAttributeLocation (String name) { Integer location = attributes.get(name); - if(location == null) return -1; - else return location; + if (location == null) + return -1; + else + return location; } - - /** - * @param name the name of the uniform - * @return whether the uniform is available in the shader - */ - public boolean hasUniform(String name) { + + /** @param name the name of the uniform + * @return whether the uniform is available in the shader */ + public boolean hasUniform (String name) { return uniforms.containsKey(name); } - - /** - * @param name the name of the uniform - * @return the type of the uniform, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc. - */ - public int getUniformType(String name) { + + /** @param name the name of the uniform + * @return the type of the uniform, one of {@link GL20#GL_FLOAT}, {@link GL20#GL_FLOAT_VEC2} etc. */ + public int getUniformType (String name) { Integer type = attributes.get(name); - if(type == null) return 0; - else return type; + if (type == null) + return 0; + else + return type; } - - /** - * @param name the name of the uniform - * @return the location of the uniform or -1. - */ - public int getUniformLocation(String name) { + + /** @param name the name of the uniform + * @return the location of the uniform or -1. */ + public int getUniformLocation (String name) { Integer location = uniforms.get(name); - if(location == null) return -1; - else return location; - } - - /** - * @return the attributes - */ - public String[] getAttributes() { + if (location == null) + return -1; + else + return location; + } + + /** @return the attributes */ + public String[] getAttributes () { return attributeNames; } - - /** - * @return the uniforms - */ - public String[] getUniforms() { + + /** @return the uniforms */ + public String[] getUniforms () { return uniformNames; - } -} \ No newline at end of file + } +} diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexArray.java b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexArray.java index 4390513ad82..c6a907ab0b3 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexArray.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexArray.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -26,10 +27,8 @@ import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.utils.BufferUtils; -import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * Convenience class for working with OpenGL vertex arrays. It interleaves all data in the order you specified in the constructor * via {@link VertexAttribute}. *

        @@ -38,36 +37,26 @@ * This class does not support shaders and for that matter OpenGL ES 2.0. For this {@link VertexBufferObject}s are needed. *

        * - * @author mzechner, Dave Clayton - * - */ + * @author mzechner, Dave Clayton */ public class VertexArray implements VertexData { final VertexAttributes attributes; final FloatBuffer buffer; final ByteBuffer byteBuffer; boolean isBound = false; - /** - * Constructs a new interleaved VertexArray + /** Constructs a new interleaved VertexArray * - * @param numVertices - * the maximum number of vertices - * @param attributes - * the {@link VertexAttribute}s - */ - public VertexArray(int numVertices, VertexAttribute... attributes) { + * @param numVertices the maximum number of vertices + * @param attributes the {@link VertexAttribute}s */ + public VertexArray (int numVertices, VertexAttribute... attributes) { this(numVertices, new VertexAttributes(attributes)); } - - /** - * Constructs a new interleaved VertexArray + + /** Constructs a new interleaved VertexArray * - * @param numVertices - * the maximum number of vertices - * @param attributes - * the {@link VertexAttributes} - */ - public VertexArray(int numVertices, VertexAttributes attributes) { + * @param numVertices the maximum number of vertices + * @param attributes the {@link VertexAttributes} */ + public VertexArray (int numVertices, VertexAttributes attributes) { this.attributes = attributes; byteBuffer = ByteBuffer.allocateDirect(this.attributes.vertexSize * numVertices); byteBuffer.order(ByteOrder.nativeOrder()); @@ -76,44 +65,39 @@ public VertexArray(int numVertices, VertexAttributes attributes) { byteBuffer.flip(); } - /** - * {@inheritDoc} - */ - @Override public void dispose () { + /** {@inheritDoc} */ + @Override + public void dispose () { } - /** - * {@inheritDoc} - */ - @Override public FloatBuffer getBuffer () { + /** {@inheritDoc} */ + @Override + public FloatBuffer getBuffer () { return buffer; } - /** - * {@inheritDoc} - */ - @Override public int getNumVertices () { + /** {@inheritDoc} */ + @Override + public int getNumVertices () { return buffer.limit() * 4 / attributes.vertexSize; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public int getNumMaxVertices () { return byteBuffer.capacity() / attributes.vertexSize; } - /** - * {@inheritDoc} - */ - @Override public void setVertices (float[] vertices, int offset, int count) { + /** {@inheritDoc} */ + @Override + public void setVertices (float[] vertices, int offset, int count) { BufferUtils.copy(vertices, byteBuffer, count, offset); buffer.position(0); buffer.limit(count); } - @Override public void bind () { + @Override + public void bind () { GL10 gl = Gdx.gl10; int textureUnit = 0; int numAttributes = attributes.size(); @@ -154,14 +138,15 @@ public int getNumMaxVertices () { break; default: - //throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); + // throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); } } isBound = true; } - @Override public void unbind () { + @Override + public void unbind () { GL10 gl = Gdx.gl10; int textureUnit = 0; int numAttributes = attributes.size(); @@ -185,14 +170,15 @@ public int getNumMaxVertices () { textureUnit++; break; default: - //throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); + // throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); } } byteBuffer.position(0); isBound = false; } - @Override public VertexAttributes getAttributes () { + @Override + public VertexAttributes getAttributes () { return attributes; } } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObject.java b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObject.java index b1ef93b4816..895df91b3d0 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObject.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObject.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -28,10 +29,8 @@ import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.utils.BufferUtils; -import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * A {@link VertexData} implementation based on OpenGL vertex buffer objects. *

        * @@ -53,9 +52,7 @@ * VertexBufferObjects must be disposed via the {@link #dispose()} method when no longer needed *

        * - * @author mzechner, Dave Clayton - * - */ + * @author mzechner, Dave Clayton */ public class VertexBufferObject implements VertexData { final static IntBuffer tmpHandle = BufferUtils.newIntBuffer(1); @@ -69,29 +66,21 @@ public class VertexBufferObject implements VertexData { boolean isDirty = false; boolean isBound = false; - /** - * Constructs a new interleaved VertexBufferObject. + /** Constructs a new interleaved VertexBufferObject. * * @param isStatic whether the vertex data is static. * @param numVertices the maximum number of vertices - * @param attributes the {@link VertexAttribute}s. - */ + * @param attributes the {@link VertexAttribute}s. */ public VertexBufferObject (boolean isStatic, int numVertices, VertexAttribute... attributes) { this(isStatic, numVertices, new VertexAttributes(attributes)); } - - /** - * Constructs a new interleaved VertexBufferObject. + + /** Constructs a new interleaved VertexBufferObject. * - * @param isStatic - * whether the vertex data is static. - * @param numVertices - * the maximum number of vertices - * @param attributes - * the {@link VertexAttributes}. - */ - public VertexBufferObject(boolean isStatic, int numVertices, VertexAttributes attributes) - { + * @param isStatic whether the vertex data is static. + * @param numVertices the maximum number of vertices + * @param attributes the {@link VertexAttributes}. */ + public VertexBufferObject (boolean isStatic, int numVertices, VertexAttributes attributes) { this.isStatic = isStatic; this.attributes = attributes; @@ -113,39 +102,33 @@ private int createBufferObject () { return tmpHandle.get(0); } - /** - * {@inheritDoc} - */ - @Override public VertexAttributes getAttributes () { + /** {@inheritDoc} */ + @Override + public VertexAttributes getAttributes () { return attributes; } - /** - * {@inheritDoc} - */ - @Override public int getNumVertices () { + /** {@inheritDoc} */ + @Override + public int getNumVertices () { return buffer.limit() * 4 / attributes.vertexSize; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public int getNumMaxVertices () { return byteBuffer.capacity() / attributes.vertexSize; } - /** - * {@inheritDoc} - */ - @Override public FloatBuffer getBuffer () { + /** {@inheritDoc} */ + @Override + public FloatBuffer getBuffer () { isDirty = true; return buffer; } - /** - * {@inheritDoc} - */ - @Override public void setVertices (float[] vertices, int offset, int count) { + /** {@inheritDoc} */ + @Override + public void setVertices (float[] vertices, int offset, int count) { isDirty = true; if (isDirect) { BufferUtils.copy(vertices, byteBuffer, count, offset); @@ -171,10 +154,9 @@ public int getNumMaxVertices () { } } - /** - * {@inheritDoc} - */ - @Override public void bind () { + /** {@inheritDoc} */ + @Override + public void bind () { GL11 gl = Gdx.gl11; gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, bufferHandle); @@ -218,18 +200,16 @@ public int getNumMaxVertices () { break; default: - //throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); + // throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); } } isBound = true; } - /** - * Binds this VertexBufferObject for rendering via glDrawArrays or glDrawElements + /** Binds this VertexBufferObject for rendering via glDrawArrays or glDrawElements * - * @param shader the shader - */ + * @param shader the shader */ public void bind (ShaderProgram shader) { GL20 gl = Gdx.gl20; @@ -256,10 +236,9 @@ public void bind (ShaderProgram shader) { isBound = true; } - /** - * {@inheritDoc} - */ - @Override public void unbind () { + /** {@inheritDoc} */ + @Override + public void unbind () { GL11 gl = Gdx.gl11; int textureUnit = 0; int numAttributes = attributes.size(); @@ -283,7 +262,7 @@ public void bind (ShaderProgram shader) { textureUnit++; break; default: - //throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); + // throw new GdxRuntimeException("unkown vertex attribute type: " + attribute.usage); } } @@ -291,11 +270,9 @@ public void bind (ShaderProgram shader) { isBound = false; } - /** - * Unbinds this VertexBufferObject. + /** Unbinds this VertexBufferObject. * - * @param shader the shader - */ + * @param shader the shader */ public void unbind (ShaderProgram shader) { GL20 gl = Gdx.gl20; int numAttributes = attributes.size(); @@ -307,18 +284,15 @@ public void unbind (ShaderProgram shader) { isBound = false; } - /** - * Invalidates the VertexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. - */ + /** Invalidates the VertexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. */ public void invalidate () { bufferHandle = createBufferObject(); isDirty = true; } - /** - * Disposes of all resources this VertexBufferObject uses. - */ - @Override public void dispose () { + /** Disposes of all resources this VertexBufferObject uses. */ + @Override + public void dispose () { if (Gdx.gl20 != null) { tmpHandle.clear(); tmpHandle.put(bufferHandle); diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObjectSubData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObjectSubData.java index 6b69c8b5bbf..a9edc5f176f 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObjectSubData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexBufferObjectSubData.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.ByteBuffer; @@ -30,8 +31,7 @@ import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        +/**

        * A {@link VertexData} implementation based on OpenGL vertex buffer objects. *

        * @@ -53,9 +53,7 @@ * VertexBufferObjects must be disposed via the {@link #dispose()} method when no longer needed *

        * - * @author mzechner - * - */ + * @author mzechner */ public class VertexBufferObjectSubData implements VertexData { final static IntBuffer tmpHandle = BufferUtils.newIntBuffer(1); @@ -69,13 +67,11 @@ public class VertexBufferObjectSubData implements VertexData { boolean isDirty = false; boolean isBound = false; - /** - * Constructs a new interleaved VertexBufferObject. + /** Constructs a new interleaved VertexBufferObject. * * @param isStatic whether the vertex data is static. * @param numVertices the maximum number of vertices - * @param attributes the {@link VertexAttribute}s. - */ + * @param attributes the {@link VertexAttribute}s. */ public VertexBufferObjectSubData (boolean isStatic, int numVertices, VertexAttribute... attributes) { this.isStatic = isStatic; this.attributes = new VertexAttributes(attributes); @@ -112,39 +108,33 @@ private int createBufferObject () { return tmpHandle.get(0); } - /** - * {@inheritDoc} - */ - @Override public VertexAttributes getAttributes () { + /** {@inheritDoc} */ + @Override + public VertexAttributes getAttributes () { return attributes; } - /** - * {@inheritDoc} - */ - @Override public int getNumVertices () { + /** {@inheritDoc} */ + @Override + public int getNumVertices () { return buffer.limit() * 4 / attributes.vertexSize; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public int getNumMaxVertices () { return byteBuffer.capacity() / attributes.vertexSize; } - /** - * {@inheritDoc} - */ - @Override public FloatBuffer getBuffer () { + /** {@inheritDoc} */ + @Override + public FloatBuffer getBuffer () { isDirty = true; return buffer; } - /** - * {@inheritDoc} - */ - @Override public void setVertices (float[] vertices, int offset, int count) { + /** {@inheritDoc} */ + @Override + public void setVertices (float[] vertices, int offset, int count) { isDirty = true; if (isDirect) { BufferUtils.copy(vertices, byteBuffer, count, offset); @@ -170,10 +160,9 @@ public int getNumMaxVertices () { } } - /** - * {@inheritDoc} - */ - @Override public void bind () { + /** {@inheritDoc} */ + @Override + public void bind () { GL11 gl = Gdx.gl11; gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, bufferHandle); @@ -226,11 +215,9 @@ public int getNumMaxVertices () { isBound = true; } - /** - * Binds this VertexBufferObject for rendering via glDrawArrays or glDrawElements + /** Binds this VertexBufferObject for rendering via glDrawArrays or glDrawElements * - * @param shader the shader - */ + * @param shader the shader */ public void bind (ShaderProgram shader) { GL20 gl = Gdx.gl20; @@ -259,10 +246,9 @@ public void bind (ShaderProgram shader) { isBound = true; } - /** - * {@inheritDoc} - */ - @Override public void unbind () { + /** {@inheritDoc} */ + @Override + public void unbind () { GL11 gl = Gdx.gl11; int textureUnit = 0; int numAttributes = attributes.size(); @@ -294,11 +280,9 @@ public void bind (ShaderProgram shader) { isBound = false; } - /** - * Unbinds this VertexBufferObject. + /** Unbinds this VertexBufferObject. * - * @param shader the shader - */ + * @param shader the shader */ public void unbind (ShaderProgram shader) { GL20 gl = Gdx.gl20; int numAttributes = attributes.size(); @@ -310,18 +294,15 @@ public void unbind (ShaderProgram shader) { isBound = false; } - /** - * Invalidates the VertexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. - */ + /** Invalidates the VertexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss. */ public void invalidate () { bufferHandle = createBufferObject(); isDirty = true; } - /** - * Disposes of all resources this VertexBufferObject uses. - */ - @Override public void dispose () { + /** Disposes of all resources this VertexBufferObject uses. */ + @Override + public void dispose () { if (Gdx.gl20 != null) { tmpHandle.clear(); tmpHandle.put(bufferHandle); @@ -341,10 +322,8 @@ public void invalidate () { } } - /** - * Returns the VBO handle - * @return the VBO handle - */ + /** Returns the VBO handle + * @return the VBO handle */ public int getBufferHandle () { return bufferHandle; } diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexData.java index 0e7d8ca86b6..9c1ea5bb708 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/VertexData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/VertexData.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.graphics.glutils; import java.nio.FloatBuffer; @@ -20,31 +21,21 @@ import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.utils.Disposable; -/** - * A VertexData instance holds vertices for rendering with OpenGL. It is implemented as either a {@link VertexArray} or a +/** A VertexData instance holds vertices for rendering with OpenGL. It is implemented as either a {@link VertexArray} or a * {@link VertexBufferObject}. Only the later supports OpenGL ES 2.0. * - * @author mzechner - * - */ + * @author mzechner */ public interface VertexData extends Disposable { - /** - * @return the number of vertices this VertexData stores - */ + /** @return the number of vertices this VertexData stores */ public int getNumVertices (); - /** - * @return the number of vertices this VertedData can store - */ + /** @return the number of vertices this VertedData can store */ public int getNumMaxVertices (); - /** - * @return the {@link VertexAttributes} as specified during construction. - */ + /** @return the {@link VertexAttributes} as specified during construction. */ public VertexAttributes getAttributes (); - /** - *

        + /**

        * Sets the vertices of this VertexData, discarding the old vertex data. The count must equal the number of floats per vertex * times the number of vertices to be copied to this VertexData. The order of the vertex attributes must be the same as * specified at construction time via {@link VertexAttributes}. @@ -56,32 +47,23 @@ public interface VertexData extends Disposable { * * @param vertices the vertex data * @param offset the offset to start copying the data from - * @param count the number of floats to copy - */ + * @param count the number of floats to copy */ public void setVertices (float[] vertices, int offset, int count); - /** - *

        + /**

        * Returns the underlying FloatBuffer. If you modify the buffer contents they will be uploaded on the next call to * {@link #bind()}. If you need immediate uploading use {@link #setVertices(float[], int, int)}; *

        * - * @return the underlying FloatBuffer holding the vertex data. - */ + * @return the underlying FloatBuffer holding the vertex data. */ public FloatBuffer getBuffer (); - /** - * Binds this VertexData for rendering via glDrawArrays or glDrawElements. - */ + /** Binds this VertexData for rendering via glDrawArrays or glDrawElements. */ public void bind (); - /** - * Unbinds this VertexData. - */ + /** Unbinds this VertexData. */ public void unbind (); - /** - * Disposes this VertexData and all its associated OpenGL resources. - */ + /** Disposes this VertexData and all its associated OpenGL resources. */ public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/input/RemoteInput.java b/gdx/src/com/badlogic/gdx/input/RemoteInput.java index 51b9fde0cc4..325fd33a6d6 100644 --- a/gdx/src/com/badlogic/gdx/input/RemoteInput.java +++ b/gdx/src/com/badlogic/gdx/input/RemoteInput.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.input; import java.io.DataInputStream; @@ -26,26 +27,25 @@ import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; -import com.badlogic.gdx.Input.Orientation; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - *

        An {@link Input} implementation that receives touch, key, accelerometer - * and compass events from a remote Android device. Just instantiate it - * and specify the port it should listen on for incoming connections (default - * 8190). Then store the new RemoteInput instance in Gdx.input. That's it.

        +/**

        + * An {@link Input} implementation that receives touch, key, accelerometer and compass events from a remote Android device. Just + * instantiate it and specify the port it should listen on for incoming connections (default 8190). Then store the new RemoteInput + * instance in Gdx.input. That's it. + *

        * - *

        On your Android device you can use the gdx-remote application available - * on the Google Code page as an APK or in SVN (extensions/gdx-remote). Open it, - * specify the IP address and the port of the PC your libgdx app is running on - * and then tap away.

        + *

        + * On your Android device you can use the gdx-remote application available on the Google Code page as an APK or in SVN + * (extensions/gdx-remote). Open it, specify the IP address and the port of the PC your libgdx app is running on and then tap + * away. + *

        * - *

        The touch coordinates will be translated to the desktop window's coordinate - * system, no matter the orientation of the device

        + *

        + * The touch coordinates will be translated to the desktop window's coordinate system, no matter the orientation of the device + *

        * - * @author mzechner - * - */ + * @author mzechner */ public class RemoteInput implements Runnable, Input { class KeyEvent { static final int KEY_DOWN = 0; @@ -69,23 +69,24 @@ class TouchEvent { int y; int pointer; } - + class EventTrigger implements Runnable { TouchEvent touchEvent; KeyEvent keyEvent; - - public EventTrigger(TouchEvent touchEvent, KeyEvent keyEvent) { + + public EventTrigger (TouchEvent touchEvent, KeyEvent keyEvent) { this.touchEvent = touchEvent; - this.keyEvent = keyEvent; + this.keyEvent = keyEvent; } - - @Override public void run () { + + @Override + public void run () { justTouched = false; - if(processor != null) { - if(touchEvent != null) { + if (processor != null) { + if (touchEvent != null) { touchX[touchEvent.pointer] = touchEvent.x; - touchY[touchEvent.pointer] = touchEvent.y; - switch(touchEvent.type) { + touchY[touchEvent.pointer] = touchEvent.y; + switch (touchEvent.type) { case TouchEvent.TOUCH_DOWN: processor.touchDown(touchEvent.x, touchEvent.y, touchEvent.pointer, Input.Buttons.LEFT); isTouched[touchEvent.pointer] = true; @@ -100,8 +101,8 @@ public EventTrigger(TouchEvent touchEvent, KeyEvent keyEvent) { break; } } - if(keyEvent != null) { - switch(keyEvent.type) { + if (keyEvent != null) { + switch (keyEvent.type) { case KeyEvent.KEY_DOWN: processor.keyDown(keyEvent.keyCode); keys.add(keyEvent.keyCode); @@ -116,25 +117,25 @@ public EventTrigger(TouchEvent touchEvent, KeyEvent keyEvent) { } } } else { - if(touchEvent != null) { + if (touchEvent != null) { touchX[touchEvent.pointer] = touchEvent.x; touchY[touchEvent.pointer] = touchEvent.y; - if(touchEvent.type == TouchEvent.TOUCH_DOWN) { + if (touchEvent.type == TouchEvent.TOUCH_DOWN) { isTouched[touchEvent.pointer] = true; justTouched = true; } - if(touchEvent.type == TouchEvent.TOUCH_UP) { + if (touchEvent.type == TouchEvent.TOUCH_UP) { isTouched[touchEvent.pointer] = false; } } - if(keyEvent != null) { - if(keyEvent.type == KeyEvent.KEY_DOWN) keys.add(keyEvent.keyCode); - if(keyEvent.type == KeyEvent.KEY_UP) keys.remove(keyEvent.keyCode); + if (keyEvent != null) { + if (keyEvent.type == KeyEvent.KEY_DOWN) keys.add(keyEvent.keyCode); + if (keyEvent.type == KeyEvent.KEY_UP) keys.remove(keyEvent.keyCode); } } - } + } } - + public static int DEFAULT_PORT = 8190; private ServerSocket serverSocket; private float[] accel = new float[3]; @@ -142,7 +143,7 @@ public EventTrigger(TouchEvent touchEvent, KeyEvent keyEvent) { private boolean multiTouch = false; private float remoteWidth = 0; private float remoteHeight = 0; - Set keys = new HashSet(); + Set keys = new HashSet(); int[] touchX = new int[20]; int[] touchY = new int[20]; boolean isTouched[] = new boolean[20]; @@ -150,47 +151,48 @@ public EventTrigger(TouchEvent touchEvent, KeyEvent keyEvent) { InputProcessor processor = null; private final int port; public final String[] ips; - - public RemoteInput() { + + public RemoteInput () { this(DEFAULT_PORT); } - - public RemoteInput(int port) { + + public RemoteInput (int port) { try { this.port = port; serverSocket = new ServerSocket(port); Thread thread = new Thread(this); thread.setDaemon(true); - thread.start(); + thread.start(); InetAddress[] allByName = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); ips = new String[allByName.length]; - for(int i = 0; i < allByName.length; i++) { + for (int i = 0; i < allByName.length; i++) { ips[i] = allByName[i].getHostAddress(); - } - } catch(Exception e) { - throw new GdxRuntimeException("Couldn't open listening socket at port '" + port+ "'", e); + } + } catch (Exception e) { + throw new GdxRuntimeException("Couldn't open listening socket at port '" + port + "'", e); } } - @Override public void run () { - while(true) { - try { + @Override + public void run () { + while (true) { + try { System.out.println("listening, port " + port); Socket socket = null; - while(true) { - socket = serverSocket.accept(); - break; - } - socket.setTcpNoDelay(true); - socket.setSoTimeout(3000); - + while (true) { + socket = serverSocket.accept(); + break; + } + socket.setTcpNoDelay(true); + socket.setSoTimeout(3000); + DataInputStream in = new DataInputStream(socket.getInputStream()); multiTouch = in.readBoolean(); - while(true) { + while (true) { int event = in.readInt(); KeyEvent keyEvent = null; TouchEvent touchEvent = null; - switch(event) { + switch (event) { case RemoteSender.ACCEL: accel[0] = in.readFloat(); accel[1] = in.readFloat(); @@ -242,162 +244,194 @@ public RemoteInput(int port) { touchEvent.type = TouchEvent.TOUCH_DRAGGED; break; } - + Gdx.app.postRunnable(new EventTrigger(touchEvent, keyEvent)); - } + } } catch (IOException e) { e.printStackTrace(); } } } - @Override public float getAccelerometerX () { + @Override + public float getAccelerometerX () { return accel[0]; } - @Override public float getAccelerometerY () { + @Override + public float getAccelerometerY () { return accel[1]; } - @Override public float getAccelerometerZ () { + @Override + public float getAccelerometerZ () { return accel[2]; } - @Override public int getX () { + @Override + public int getX () { return touchX[0]; } - @Override public int getX (int pointer) { + @Override + public int getX (int pointer) { return touchX[pointer]; } - @Override public int getY () { + @Override + public int getY () { return touchY[0]; } - @Override public int getY (int pointer) { + @Override + public int getY (int pointer) { return touchY[pointer]; } - @Override public boolean isTouched () { + @Override + public boolean isTouched () { return isTouched[0]; } - @Override public boolean justTouched () { + @Override + public boolean justTouched () { return justTouched; } - @Override public boolean isTouched (int pointer) { + @Override + public boolean isTouched (int pointer) { return isTouched[pointer]; } - @Override public boolean isButtonPressed (int button) { - if(button != Buttons.LEFT) return false; - for(int i = 0; i < isTouched.length; i++) - if(isTouched[i]) return true; + @Override + public boolean isButtonPressed (int button) { + if (button != Buttons.LEFT) return false; + for (int i = 0; i < isTouched.length; i++) + if (isTouched[i]) return true; return false; } - @Override public boolean isKeyPressed (int key) { + @Override + public boolean isKeyPressed (int key) { return keys.contains(key); } - @Override public void getTextInput (TextInputListener listener, String title, String text) { + @Override + public void getTextInput (TextInputListener listener, String title, String text) { Gdx.app.getInput().getTextInput(listener, title, text); } - @Override public void setOnscreenKeyboardVisible (boolean visible) { - } + @Override + public void setOnscreenKeyboardVisible (boolean visible) { + } + + @Override + public void vibrate (int milliseconds) { - @Override public void vibrate (int milliseconds) { - } - @Override public void vibrate (long[] pattern, int repeat) { - + @Override + public void vibrate (long[] pattern, int repeat) { + } - @Override public void cancelVibrate () { - + @Override + public void cancelVibrate () { + } - @Override public float getAzimuth () { + @Override + public float getAzimuth () { return compass[0]; } - @Override public float getPitch () { + @Override + public float getPitch () { return compass[1]; } - @Override public float getRoll () { + @Override + public float getRoll () { return compass[2]; } - @Override public void setCatchBackKey (boolean catchBack) { - + @Override + public void setCatchBackKey (boolean catchBack) { + } - @Override public void setInputProcessor (InputProcessor processor) { + @Override + public void setInputProcessor (InputProcessor processor) { this.processor = processor; } - - @Override public InputProcessor getInputProcessor() { + + @Override + public InputProcessor getInputProcessor () { return this.processor; } - - /** - * @return the IP addresses {@link RemoteSender} or gdx-remote should connect to. Most likely the LAN addresses if behind a NAT. - */ - public String[] getIPs() { + + /** @return the IP addresses {@link RemoteSender} or gdx-remote should connect to. Most likely the LAN addresses if behind a + * NAT. */ + public String[] getIPs () { return ips; } - @Override public boolean isPeripheralAvailable (Peripheral peripheral) { - if(peripheral == Peripheral.Accelerometer) return true; - if(peripheral == Peripheral.Compass) return true; - if(peripheral == Peripheral.MultitouchScreen) return multiTouch; + @Override + public boolean isPeripheralAvailable (Peripheral peripheral) { + if (peripheral == Peripheral.Accelerometer) return true; + if (peripheral == Peripheral.Compass) return true; + if (peripheral == Peripheral.MultitouchScreen) return multiTouch; return false; } - @Override public int getRotation () { + @Override + public int getRotation () { return 0; } - @Override public Orientation getNativeOrientation () { + @Override + public Orientation getNativeOrientation () { return Orientation.Landscape; } - @Override public void setCursorCatched (boolean catched) { - + @Override + public void setCursorCatched (boolean catched) { + } - @Override public boolean isCursorCatched () { + @Override + public boolean isCursorCatched () { return false; } - @Override public int getDeltaX () { + @Override + public int getDeltaX () { // TODO Auto-generated method stub return 0; } - @Override public int getDeltaX (int pointer) { + @Override + public int getDeltaX (int pointer) { return 0; } - @Override public int getDeltaY () { + @Override + public int getDeltaY () { return 0; } - @Override public int getDeltaY (int pointer) { + @Override + public int getDeltaY (int pointer) { return 0; } - @Override public void setCursorPosition (int x, int y) { + @Override + public void setCursorPosition (int x, int y) { } @Override - public void setCatchMenuKey(boolean catchMenu) { + public void setCatchMenuKey (boolean catchMenu) { // TODO Auto-generated method stub - + } } diff --git a/gdx/src/com/badlogic/gdx/input/RemoteSender.java b/gdx/src/com/badlogic/gdx/input/RemoteSender.java index 16699fc14f0..35ee1274e30 100644 --- a/gdx/src/com/badlogic/gdx/input/RemoteSender.java +++ b/gdx/src/com/badlogic/gdx/input/RemoteSender.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.input; import java.io.DataOutputStream; @@ -22,30 +23,27 @@ import com.badlogic.gdx.Input.Peripheral; import com.badlogic.gdx.InputProcessor; -/** - * Sends all inputs from touch, key, accelerometer and compass to a {@link RemoteInput} - * at the given ip/port. Instantiate this and call sendUpdate() periodically. +/** Sends all inputs from touch, key, accelerometer and compass to a {@link RemoteInput} at the given ip/port. Instantiate this and + * call sendUpdate() periodically. * - * @author mzechner - * - */ + * @author mzechner */ public class RemoteSender implements InputProcessor { private DataOutputStream out; private boolean connected = false; - + public static final int KEY_DOWN = 0; public static final int KEY_UP = 1; public static final int KEY_TYPED = 2; - + public static final int TOUCH_DOWN = 3; public static final int TOUCH_UP = 4; public static final int TOUCH_DRAGGED = 5; - + public static final int ACCEL = 6; public static final int COMPASS = 7; public static final int SIZE = 8; - - public RemoteSender(String ip, int port) { + + public RemoteSender (String ip, int port) { try { Socket socket = new Socket(ip, port); socket.setTcpNoDelay(true); @@ -54,14 +52,14 @@ public RemoteSender(String ip, int port) { out.writeBoolean(Gdx.input.isPeripheralAvailable(Peripheral.MultitouchScreen)); connected = true; Gdx.input.setInputProcessor(this); - } catch(Exception e) { + } catch (Exception e) { Gdx.app.log("RemoteSender", "couldn't connect to " + ip + ":" + port); } - } - - public void sendUpdate() { - synchronized(this) { - if(!connected) return; + } + + public void sendUpdate () { + synchronized (this) { + if (!connected) return; } try { out.writeInt(ACCEL); @@ -75,124 +73,132 @@ public void sendUpdate() { out.writeInt(SIZE); out.writeFloat(Gdx.graphics.getWidth()); out.writeFloat(Gdx.graphics.getHeight()); - } catch(Throwable t) { + } catch (Throwable t) { out = null; connected = false; } } - @Override public boolean keyDown (int keycode) { - synchronized(this) { - if(!connected) return false; + @Override + public boolean keyDown (int keycode) { + synchronized (this) { + if (!connected) return false; } - + try { out.writeInt(KEY_DOWN); out.writeInt(keycode); - } catch(Throwable t) { - synchronized(this) { + } catch (Throwable t) { + synchronized (this) { connected = false; } } return false; } - @Override public boolean keyUp (int keycode) { - synchronized(this) { - if(!connected) return false; + @Override + public boolean keyUp (int keycode) { + synchronized (this) { + if (!connected) return false; } - + try { out.writeInt(KEY_UP); out.writeInt(keycode); - } catch(Throwable t) { - synchronized(this) { + } catch (Throwable t) { + synchronized (this) { connected = false; } } return false; } - @Override public boolean keyTyped (char character) { - synchronized(this) { - if(!connected) return false; + @Override + public boolean keyTyped (char character) { + synchronized (this) { + if (!connected) return false; } - + try { out.writeInt(KEY_TYPED); out.writeChar(character); - } catch(Throwable t) { - synchronized(this) { + } catch (Throwable t) { + synchronized (this) { connected = false; } } return false; } - @Override public boolean touchDown (int x, int y, int pointer, int button) { - synchronized(this) { - if(!connected) return false; + @Override + public boolean touchDown (int x, int y, int pointer, int button) { + synchronized (this) { + if (!connected) return false; } - + try { out.writeInt(TOUCH_DOWN); out.writeInt(x); out.writeInt(y); - out.writeInt(pointer); - } catch(Throwable t) { - synchronized(this) { + out.writeInt(pointer); + } catch (Throwable t) { + synchronized (this) { connected = false; } } return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { - synchronized(this) { - if(!connected) return false; + @Override + public boolean touchUp (int x, int y, int pointer, int button) { + synchronized (this) { + if (!connected) return false; } - + try { out.writeInt(TOUCH_UP); out.writeInt(x); out.writeInt(y); - out.writeInt(pointer); - } catch(Throwable t) { - synchronized(this) { + out.writeInt(pointer); + } catch (Throwable t) { + synchronized (this) { connected = false; } } return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { - synchronized(this) { - if(!connected) return false; + @Override + public boolean touchDragged (int x, int y, int pointer) { + synchronized (this) { + if (!connected) return false; } - + try { out.writeInt(TOUCH_DRAGGED); out.writeInt(x); out.writeInt(y); - out.writeInt(pointer); - } catch(Throwable t) { - synchronized(this) { + out.writeInt(pointer); + } catch (Throwable t) { + synchronized (this) { connected = false; } } return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } - - public boolean isConnected() { - synchronized(this) { + + public boolean isConnected () { + synchronized (this) { return connected; } } diff --git a/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java b/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java index 31657deb498..0f660c8be5d 100644 --- a/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java +++ b/gdx/src/com/badlogic/gdx/math/CatmullRomSpline.java @@ -13,48 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.io.Serializable; 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 +/** 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 - * - */ + * @author badlogicgames@gmail.com */ public class CatmullRomSpline implements Serializable { private static final long serialVersionUID = -3290464799289771451L; private List controlPoints = new ArrayList(); Vector3 T1 = new Vector3(); Vector3 T2 = new Vector3(); - /** - * Adds a new control point + /** Adds a new control point * - * @param point the point - */ + * @param point the point */ public void add (Vector3 point) { controlPoints.add(point); } - /** - * @return all control points - */ + /** @return all control points */ public List getControlPoints () { return controlPoints; } - /** - * Returns a path, between every two control points numPoints are generated and the control points themselves are added too. + /** 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 - * @return the path - */ + * @return the path */ public List getPath (int numPoints) { ArrayList points = new ArrayList(); @@ -93,17 +85,15 @@ public List getPath (int numPoints) { return points; } - - /** - * Returns a path, between every two control points numPoints are generated and the control points themselves are added too. + + /** 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 points the array of Vector3 instances to store the path in - * @param numPoints number of points returned for a segment - */ - public void getPath (Vector3[] points, int numPoints) { + * @param numPoints number of points returned for a segment */ + public void getPath (Vector3[] points, int numPoints) { int idx = 0; - if (controlPoints.size() < 4) return; + if (controlPoints.size() < 4) return; for (int i = 1; i <= controlPoints.size() - 3; i++) { points[idx++].set(controlPoints.get(i)); @@ -125,20 +115,18 @@ public void getPath (Vector3[] points, int numPoints) { Vector3 point = points[idx++].set(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.add(T2.tmp().mul(h4)); t += increment; } } - points[idx].set(controlPoints.get(controlPoints.size() - 2)); + points[idx].set(controlPoints.get(controlPoints.size() - 2)); } - /** - * 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 - * @return the tangents of the points in the path - */ + * @return the tangents of the points in the path */ public List getTangents (int numPoints) { ArrayList tangents = new ArrayList(); @@ -178,13 +166,11 @@ public List getTangents (int numPoints) { 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 + /** 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 - * @return the tangents of the points in the path - */ + * @return the tangents of the points in the path */ public List getTangentNormals2D (int numPoints) { ArrayList tangents = new ArrayList(); @@ -228,13 +214,11 @@ public List getTangentNormals2D (int numPoints) { 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 a list of tangent normals - */ + * @return a list of tangent normals */ public List getTangentNormals (int numPoints, Vector3 up) { List tangents = getTangents(numPoints); ArrayList normals = new ArrayList(); diff --git a/gdx/src/com/badlogic/gdx/math/Circle.java b/gdx/src/com/badlogic/gdx/math/Circle.java index f4bb02cb20c..c3a78c336e1 100644 --- a/gdx/src/com/badlogic/gdx/math/Circle.java +++ b/gdx/src/com/badlogic/gdx/math/Circle.java @@ -10,38 +10,38 @@ * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; -/** - * A convenient 2D circle class. - * @author mzechner - * - */ +/** A convenient 2D circle class. + * @author mzechner */ public class Circle implements Serializable { public float x, y; public float radius; - - public Circle(float x, float y, float radius) { - this.x = x; this.y = y; + + public Circle (float x, float y, float radius) { + this.x = x; + this.y = y; this.radius = radius; } - - public Circle(Vector2 position, float radius) { - this.x = position.x; this.y = position.y; + + public Circle (Vector2 position, float radius) { + this.x = position.x; + this.y = position.y; this.radius = radius; } - - public boolean contains(float x, float y) { + + public boolean contains (float x, float y) { x = this.x - x; y = this.y - y; - return x*x + y*y <= radius * radius; + return x * x + y * y <= radius * radius; } - - public boolean contains(Vector2 point) { + + public boolean contains (Vector2 point) { float x = this.x - point.x; float y = this.y - point.y; - return x*x + y*y <= radius * radius; + return x * x + y * y <= radius * radius; } } diff --git a/gdx/src/com/badlogic/gdx/math/EarClippingTriangulator.java b/gdx/src/com/badlogic/gdx/math/EarClippingTriangulator.java index 04a744e2605..7402e663cf9 100644 --- a/gdx/src/com/badlogic/gdx/math/EarClippingTriangulator.java +++ b/gdx/src/com/badlogic/gdx/math/EarClippingTriangulator.java @@ -13,23 +13,20 @@ * 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.Collections; import java.util.List; -/** - * A simple implementation of the ear cutting algorithm to triangulate simple - * polygons without holes. For more information: +/** A simple implementation of the ear cutting algorithm to triangulate simple polygons without holes. For more information: * http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Ian/algorithm2.html * http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf * * @author badlogicgames@gmail.com - * @author Nicolas Gramlich (Improved performance. Collinear edges are now - * supported.) - * @author Eric Spitz - */ + * @author Nicolas Gramlich (Improved performance. Collinear edges are now supported.) + * @author Eric Spitz */ public final class EarClippingTriangulator { private static final int CONCAVE = 1; @@ -37,26 +34,20 @@ public final class EarClippingTriangulator { private int concaveVertexCount; - /** - * Triangulates the given (concave) polygon to a list of triangles. The - * resulting triangles have clockwise order. + /** Triangulates the given (concave) polygon to a list of triangles. The resulting triangles have clockwise order. * - * @param polygon - * the polygon - * @return the triangles - */ - public List computeTriangles(final List polygon) { + * @param polygon the polygon + * @return the triangles */ + public List computeTriangles (final List polygon) { // TODO Check if LinkedList performs better final ArrayList triangles = new ArrayList(); - final ArrayList vertices = new ArrayList( - polygon.size()); + final ArrayList vertices = new ArrayList(polygon.size()); vertices.addAll(polygon); /* - * ESpitz: For the sake of performance, we only need to test for eartips - * while the polygon has more than three verts. If there are only three - * verts left to test, or there were only three verts to begin with, - * there is no need to continue with this loop. + * ESpitz: For the sake of performance, we only need to test for eartips while the polygon has more than three verts. If + * there are only three verts left to test, or there were only three verts to begin with, there is no need to continue with + * this loop. */ while (vertices.size() > 3) { // TODO Usually(Always?) only the Types of the vertices next to the @@ -73,8 +64,8 @@ public List computeTriangles(final List polygon) { } /* - * ESpitz: If there are only three verts left to test, or there were - * only three verts to begin with, we have the final triangle. + * ESpitz: If there are only three verts left to test, or there were only three verts to begin with, we have the final + * triangle. */ if (vertices.size() == 3) { triangles.addAll(vertices); @@ -83,15 +74,13 @@ public List computeTriangles(final List polygon) { return triangles; } - private static boolean areVerticesClockwise( - final ArrayList pVertices) { + private static boolean areVerticesClockwise (final ArrayList pVertices) { final int vertexCount = pVertices.size(); float area = 0; for (int i = 0; i < vertexCount; i++) { final Vector2 p1 = pVertices.get(i); - final Vector2 p2 = pVertices.get(EarClippingTriangulator - .computeNextIndex(pVertices, i)); + final Vector2 p2 = pVertices.get(EarClippingTriangulator.computeNextIndex(pVertices, i)); area += p1.x * p2.y - p2.x * p1.y; } @@ -102,13 +91,10 @@ private static boolean areVerticesClockwise( } } - /** - * @param pVertices - * @return An array of length pVertices.size() filled with - * either {@link EarClippingTriangulator#CONCAVE} or - * {@link EarClippingTriangulator#CONVEX}. - */ - private int[] classifyVertices(final ArrayList pVertices) { + /** @param pVertices + * @return An array of length pVertices.size() filled with either {@link EarClippingTriangulator#CONCAVE} or + * {@link EarClippingTriangulator#CONVEX}. */ + private int[] classifyVertices (final ArrayList pVertices) { final int vertexCount = pVertices.size(); final int[] vertexTypes = new int[vertexCount]; @@ -120,18 +106,15 @@ private int[] classifyVertices(final ArrayList pVertices) { } for (int index = 0; index < vertexCount; index++) { - final int previousIndex = EarClippingTriangulator - .computePreviousIndex(pVertices, index); - final int nextIndex = EarClippingTriangulator.computeNextIndex( - pVertices, index); + final int previousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, index); + final int nextIndex = EarClippingTriangulator.computeNextIndex(pVertices, index); final Vector2 previousVertex = pVertices.get(previousIndex); final Vector2 currentVertex = pVertices.get(index); final Vector2 nextVertex = pVertices.get(nextIndex); - if (EarClippingTriangulator.isTriangleConvex(previousVertex.x, - previousVertex.y, currentVertex.x, currentVertex.y, - nextVertex.x, nextVertex.y)) { + if (EarClippingTriangulator.isTriangleConvex(previousVertex.x, previousVertex.y, currentVertex.x, currentVertex.y, + nextVertex.x, nextVertex.y)) { vertexTypes[index] = CONVEX; } else { vertexTypes[index] = CONCAVE; @@ -142,40 +125,33 @@ private int[] classifyVertices(final ArrayList pVertices) { return vertexTypes; } - private static boolean isTriangleConvex(final float pX1, final float pY1, - final float pX2, final float pY2, final float pX3, final float pY3) { - if (EarClippingTriangulator.computeSpannedAreaSign(pX1, pY1, pX2, pY2, - pX3, pY3) < 0) { + private static boolean isTriangleConvex (final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, + final float pY3) { + if (EarClippingTriangulator.computeSpannedAreaSign(pX1, pY1, pX2, pY2, pX3, pY3) < 0) { return false; } else { return true; } } - private static int computeSpannedAreaSign(final float pX1, final float pY1, - final float pX2, final float pY2, final float pX3, final float pY3) { + private static int computeSpannedAreaSign (final float pX1, final float pY1, final float pX2, final float pY2, + final float pX3, final float pY3) { /* - * Espitz: using doubles corrects for very rare cases where we run into - * floating point imprecision in the area test, causing the method to - * return a 0 when it should have returned -1 or 1. + * Espitz: using doubles corrects for very rare cases where we run into floating point imprecision in the area test, causing + * the method to return a 0 when it should have returned -1 or 1. */ double area = 0; - area += (double) pX1 * (pY3 - pY2); - area += (double) pX2 * (pY1 - pY3); - area += (double) pX3 * (pY2 - pY1); + area += (double)pX1 * (pY3 - pY2); + area += (double)pX2 * (pY1 - pY3); + area += (double)pX3 * (pY2 - pY1); - return (int) Math.signum(area); + return (int)Math.signum(area); } - /** - * @return true when the Triangles contains one or more - * vertices, false otherwise. - */ - private static boolean isAnyVertexInTriangle( - final ArrayList pVertices, final int[] pVertexTypes, - final float pX1, final float pY1, final float pX2, final float pY2, - final float pX3, final float pY3) { + /** @return true when the Triangles contains one or more vertices, false otherwise. */ + private static boolean isAnyVertexInTriangle (final ArrayList pVertices, final int[] pVertexTypes, final float pX1, + final float pY1, final float pX2, final float pY2, final float pX3, final float pY3) { int i = 0; final int vertexCount = pVertices.size(); @@ -186,15 +162,12 @@ private static boolean isAnyVertexInTriangle( final float currentVertexX = currentVertex.x; final float currentVertexY = currentVertex.y; - final int areaSign1 = EarClippingTriangulator - .computeSpannedAreaSign(pX1, pY1, pX2, pY2, - currentVertexX, currentVertexY); - final int areaSign2 = EarClippingTriangulator - .computeSpannedAreaSign(pX2, pY2, pX3, pY3, - currentVertexX, currentVertexY); - final int areaSign3 = EarClippingTriangulator - .computeSpannedAreaSign(pX3, pY3, pX1, pY1, - currentVertexX, currentVertexY); + final int areaSign1 = EarClippingTriangulator.computeSpannedAreaSign(pX1, pY1, pX2, pY2, currentVertexX, + currentVertexY); + final int areaSign2 = EarClippingTriangulator.computeSpannedAreaSign(pX2, pY2, pX3, pY3, currentVertexX, + currentVertexY); + final int areaSign3 = EarClippingTriangulator.computeSpannedAreaSign(pX3, pY3, pX1, pY1, currentVertexX, + currentVertexY); if (areaSign1 > 0 && areaSign2 > 0 && areaSign3 > 0) { return true; @@ -207,20 +180,14 @@ private static boolean isAnyVertexInTriangle( return false; } - private boolean isEarTip(final ArrayList pVertices, - final int pEarTipIndex, final int[] pVertexTypes) { + private boolean isEarTip (final ArrayList pVertices, final int pEarTipIndex, final int[] pVertexTypes) { if (this.concaveVertexCount != 0) { - final Vector2 previousVertex = pVertices - .get(EarClippingTriangulator.computePreviousIndex( - pVertices, pEarTipIndex)); + final Vector2 previousVertex = pVertices.get(EarClippingTriangulator.computePreviousIndex(pVertices, pEarTipIndex)); final Vector2 currentVertex = pVertices.get(pEarTipIndex); - final Vector2 nextVertex = pVertices.get(EarClippingTriangulator - .computeNextIndex(pVertices, pEarTipIndex)); + final Vector2 nextVertex = pVertices.get(EarClippingTriangulator.computeNextIndex(pVertices, pEarTipIndex)); - if (EarClippingTriangulator.isAnyVertexInTriangle(pVertices, - pVertexTypes, previousVertex.x, previousVertex.y, - currentVertex.x, currentVertex.y, nextVertex.x, - nextVertex.y)) { + if (EarClippingTriangulator.isAnyVertexInTriangle(pVertices, pVertexTypes, previousVertex.x, previousVertex.y, + currentVertex.x, currentVertex.y, nextVertex.x, nextVertex.y)) { return false; } else { return true; @@ -230,15 +197,11 @@ private boolean isEarTip(final ArrayList pVertices, } } - private void cutEarTip(final ArrayList pVertices, - final int pEarTipIndex, final ArrayList pTriangles) { - final int previousIndex = EarClippingTriangulator.computePreviousIndex( - pVertices, pEarTipIndex); - final int nextIndex = EarClippingTriangulator.computeNextIndex( - pVertices, pEarTipIndex); + private void cutEarTip (final ArrayList pVertices, final int pEarTipIndex, final ArrayList pTriangles) { + final int previousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, pEarTipIndex); + final int nextIndex = EarClippingTriangulator.computeNextIndex(pVertices, pEarTipIndex); - if (!EarClippingTriangulator.isCollinear(pVertices, previousIndex, - pEarTipIndex, nextIndex)) { + if (!EarClippingTriangulator.isCollinear(pVertices, previousIndex, pEarTipIndex, nextIndex)) { pTriangles.add(new Vector2(pVertices.get(previousIndex))); pTriangles.add(new Vector2(pVertices.get(pEarTipIndex))); pTriangles.add(new Vector2(pVertices.get(nextIndex))); @@ -246,68 +209,52 @@ private void cutEarTip(final ArrayList pVertices, pVertices.remove(pEarTipIndex); if (pVertices.size() >= 3) { - EarClippingTriangulator - .removeCollinearNeighborEarsAfterRemovingEarTip(pVertices, - pEarTipIndex); + EarClippingTriangulator.removeCollinearNeighborEarsAfterRemovingEarTip(pVertices, pEarTipIndex); } } - private static void removeCollinearNeighborEarsAfterRemovingEarTip( - final ArrayList pVertices, final int pEarTipCutIndex) { - final int collinearityCheckNextIndex = pEarTipCutIndex - % pVertices.size(); - int collinearCheckPreviousIndex = EarClippingTriangulator - .computePreviousIndex(pVertices, collinearityCheckNextIndex); + private static void removeCollinearNeighborEarsAfterRemovingEarTip (final ArrayList pVertices, + final int pEarTipCutIndex) { + final int collinearityCheckNextIndex = pEarTipCutIndex % pVertices.size(); + int collinearCheckPreviousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, collinearityCheckNextIndex); - if (EarClippingTriangulator.isCollinear(pVertices, - collinearityCheckNextIndex)) { + if (EarClippingTriangulator.isCollinear(pVertices, collinearityCheckNextIndex)) { pVertices.remove(collinearityCheckNextIndex); if (pVertices.size() > 3) { /* Update */ - collinearCheckPreviousIndex = EarClippingTriangulator - .computePreviousIndex(pVertices, - collinearityCheckNextIndex); - if (EarClippingTriangulator.isCollinear(pVertices, - collinearCheckPreviousIndex)) { + collinearCheckPreviousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, collinearityCheckNextIndex); + if (EarClippingTriangulator.isCollinear(pVertices, collinearCheckPreviousIndex)) { pVertices.remove(collinearCheckPreviousIndex); } } - } else if (EarClippingTriangulator.isCollinear(pVertices, - collinearCheckPreviousIndex)) { + } else if (EarClippingTriangulator.isCollinear(pVertices, collinearCheckPreviousIndex)) { pVertices.remove(collinearCheckPreviousIndex); } } - private static boolean isCollinear(final ArrayList pVertices, - final int pIndex) { - final int previousIndex = EarClippingTriangulator.computePreviousIndex( - pVertices, pIndex); - final int nextIndex = EarClippingTriangulator.computeNextIndex( - pVertices, pIndex); + private static boolean isCollinear (final ArrayList pVertices, final int pIndex) { + final int previousIndex = EarClippingTriangulator.computePreviousIndex(pVertices, pIndex); + final int nextIndex = EarClippingTriangulator.computeNextIndex(pVertices, pIndex); - return EarClippingTriangulator.isCollinear(pVertices, previousIndex, - pIndex, nextIndex); + return EarClippingTriangulator.isCollinear(pVertices, previousIndex, pIndex, nextIndex); } - private static boolean isCollinear(final ArrayList pVertices, - final int pPreviousIndex, final int pIndex, final int pNextIndex) { + private static boolean isCollinear (final ArrayList pVertices, final int pPreviousIndex, final int pIndex, + final int pNextIndex) { final Vector2 previousVertex = pVertices.get(pPreviousIndex); final Vector2 vertex = pVertices.get(pIndex); final Vector2 nextVertex = pVertices.get(pNextIndex); - return EarClippingTriangulator.computeSpannedAreaSign(previousVertex.x, - previousVertex.y, vertex.x, vertex.y, nextVertex.x, - nextVertex.y) == 0; + return EarClippingTriangulator.computeSpannedAreaSign(previousVertex.x, previousVertex.y, vertex.x, vertex.y, nextVertex.x, + nextVertex.y) == 0; } - private static int computePreviousIndex(final List pVertices, - final int pIndex) { + private static int computePreviousIndex (final List pVertices, final int pIndex) { return pIndex == 0 ? pVertices.size() - 1 : pIndex - 1; } - private static int computeNextIndex(final List pVertices, - final int pIndex) { + private static int computeNextIndex (final List pVertices, final int pIndex) { return pIndex == pVertices.size() - 1 ? 0 : pIndex + 1; } } diff --git a/gdx/src/com/badlogic/gdx/math/Frustum.java b/gdx/src/com/badlogic/gdx/math/Frustum.java index a93f0df494e..67a153b1f0b 100644 --- a/gdx/src/com/badlogic/gdx/math/Frustum.java +++ b/gdx/src/com/badlogic/gdx/math/Frustum.java @@ -13,73 +13,68 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; -import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.PerspectiveCamera; -import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer10; import com.badlogic.gdx.math.Plane.PlaneSide; import com.badlogic.gdx.math.collision.BoundingBox; public class Frustum { - protected static final Vector3[] clipSpacePlanePoints = { new Vector3(-1, -1, -1), new Vector3(1, -1, -1), new Vector3(1, 1, -1), new Vector3(-1, 1, -1), // near clip - new Vector3(-1, -1, 1), new Vector3(1, -1, 1), new Vector3(1, 1, 1), new Vector3(-1, 1, 1) }; // far clip - protected static final float[] clipSpacePlanePointsArray = new float[8 * 3]; - + protected static final Vector3[] clipSpacePlanePoints = {new Vector3(-1, -1, -1), new Vector3(1, -1, -1), + new Vector3(1, 1, -1), new Vector3(-1, 1, -1), // near clip + new Vector3(-1, -1, 1), new Vector3(1, -1, 1), new Vector3(1, 1, 1), new Vector3(-1, 1, 1)}; // far clip + protected static final float[] clipSpacePlanePointsArray = new float[8 * 3]; + static { int j = 0; - for(Vector3 v: clipSpacePlanePoints) { + for (Vector3 v : clipSpacePlanePoints) { clipSpacePlanePointsArray[j++] = v.x; clipSpacePlanePointsArray[j++] = v.y; clipSpacePlanePointsArray[j++] = v.z; } } - + /** the six clipping planes, near, far, left, right, top, bottm **/ - public final Plane[] planes = new Plane[6]; - + public final Plane[] planes = new Plane[6]; + /** eight points making up the near and far clipping "rectangles". order is counter clockwise, starting at bottom left **/ - public final Vector3[] planePoints = { new Vector3(), new Vector3(), new Vector3(), new Vector3(), - new Vector3(), new Vector3(), new Vector3(), new Vector3() - }; - protected final float[] planePointsArray = new float[8 * 3]; - - public Frustum() { - for(int i = 0; i < 6; i++) { + public final Vector3[] planePoints = {new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), + new Vector3(), new Vector3(), new Vector3()}; + protected final float[] planePointsArray = new float[8 * 3]; + + public Frustum () { + for (int i = 0; i < 6; i++) { planes[i] = new Plane(new Vector3(), 0); } } - - /** - * Updates the clipping plane's based on the given inverse combined projection and view - * matrix, e.g. from an {@link OrthographicCamera} or {@link PerspectiveCamera}. - * @param inverseProjectionView the combined projection and view matrices. - */ - public void update(Matrix4 inverseProjectionView) { + + /** Updates the clipping plane's based on the given inverse combined projection and view matrix, e.g. from an + * {@link OrthographicCamera} or {@link PerspectiveCamera}. + * @param inverseProjectionView the combined projection and view matrices. */ + public void update (Matrix4 inverseProjectionView) { System.arraycopy(clipSpacePlanePointsArray, 0, planePointsArray, 0, clipSpacePlanePointsArray.length); Matrix4.prj(inverseProjectionView.val, planePointsArray, 0, 8, 3); - for(int i = 0, j=0; i < 8; i++) { + for (int i = 0, j = 0; i < 8; i++) { Vector3 v = planePoints[i]; v.x = planePointsArray[j++]; v.y = planePointsArray[j++]; v.z = planePointsArray[j++]; - } - + } + planes[0].set(planePoints[1], planePoints[0], planePoints[2]); planes[1].set(planePoints[4], planePoints[5], planePoints[7]); planes[2].set(planePoints[0], planePoints[4], planePoints[3]); planes[3].set(planePoints[5], planePoints[1], planePoints[6]); planes[4].set(planePoints[2], planePoints[3], planePoints[6]); planes[5].set(planePoints[4], planePoints[0], planePoints[1]); - } - - /** - * Returns wheter the point is in the frustum. + } + + /** Returns wheter the point is in the frustum. * * @param point The point - * @return Wheter the point is in the frustum. - */ + * @return Wheter the point is in the frustum. */ public boolean pointInFrustum (Vector3 point) { for (int i = 0; i < planes.length; i++) { PlaneSide result = planes[i].testPoint(point); @@ -89,13 +84,11 @@ public boolean pointInFrustum (Vector3 point) { return true; } - /** - * Returns wheter the given sphere is in the frustum. + /** Returns wheter the given sphere is in the frustum. * * @param center The center of the sphere * @param radius The radius of the sphere - * @return Wheter the sphere is in the frustum - */ + * @return Wheter the sphere is in the frustum */ public boolean sphereInFrustum (Vector3 center, float radius) { for (int i = 0; i < planes.length; i++) if (planes[i].distance(center) < -radius) return false; @@ -103,13 +96,11 @@ public boolean sphereInFrustum (Vector3 center, float radius) { 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 - */ + * @return Wheter the sphere is in the frustum */ public boolean sphereInFrustumWithoutNearFar (Vector3 center, float radius) { for (int i = 0; i < planes.length; i++) if (planes[i].distance(center) < -radius) return false; @@ -117,12 +108,10 @@ public boolean sphereInFrustumWithoutNearFar (Vector3 center, float radius) { return true; } - /** - * Returns wheter the given {@link BoundingBox} is in the frustum. + /** Returns wheter the given {@link BoundingBox} is in the frustum. * * @param bounds The bounding box - * @return Wheter the bounding box is in the frustum - */ + * @return Wheter the bounding box is in the frustum */ public boolean boundsInFrustum (BoundingBox bounds) { Vector3[] corners = bounds.getCorners(); int len = corners.length; @@ -137,50 +126,50 @@ public boolean boundsInFrustum (BoundingBox bounds) { } 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. -// * -// * @param screen_width The window width in pixels -// * @param screen_height The window height in pixels -// * @param mouse_x The window x-coordinate -// * @param mouse_y The window y-coordinate -// * @param pos The camera position -// * @param dir The camera direction, having unit length -// * @param up The camera up vector, having unit length -// * @return the picking ray. -// */ -// 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; + } + +// /** +// * 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 +// * @param mouse_x The window x-coordinate +// * @param mouse_y The window y-coordinate +// * @param pos The camera position +// * @param dir The camera direction, having unit length +// * @param up The camera up vector, having unit length +// * @return the picking ray. +// */ +// 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); // -// 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()); +// } + +// public static void main(String[] argv) { +// PerspectiveCamera camera = new PerspectiveCamera(45, 2, 2); +// // camera.rotate(90, 0, 1, 0); +// camera.update(); +// System.out.println(camera.direction); +// System.out.println(Arrays.toString(camera.frustum.planes)); // -// return ray.set(near_point.tmp(), near_point.sub(pos).nor()); -// } - -// public static void main(String[] argv) { -// PerspectiveCamera camera = new PerspectiveCamera(45, 2, 2); -//// camera.rotate(90, 0, 1, 0); -// camera.update(); -// System.out.println(camera.direction); -// System.out.println(Arrays.toString(camera.frustum.planes)); -// -// OrthographicCamera camOrtho = new OrthographicCamera(2, 2); -// camOrtho.near = 1; -//// camOrtho.rotate(90, 1, 0, 0); -// camOrtho.update(); -// System.out.println(camOrtho.direction); -// System.out.println(Arrays.toString(camOrtho.frustum.planes)); -// } +// OrthographicCamera camOrtho = new OrthographicCamera(2, 2); +// camOrtho.near = 1; +// // camOrtho.rotate(90, 1, 0, 0); +// camOrtho.update(); +// System.out.println(camOrtho.direction); +// System.out.println(Arrays.toString(camOrtho.frustum.planes)); +// } } diff --git a/gdx/src/com/badlogic/gdx/math/Intersector.java b/gdx/src/com/badlogic/gdx/math/Intersector.java index 6cc7f20bf2d..5cbf81af26e 100644 --- a/gdx/src/com/badlogic/gdx/math/Intersector.java +++ b/gdx/src/com/badlogic/gdx/math/Intersector.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.util.List; @@ -20,22 +21,17 @@ 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. - * - * @author badlogicgames@gmail.com +/** Class offering various static methods for intersection testing between different geometric objects. * - */ + * @author badlogicgames@gmail.com */ 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 + /** 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 - */ + * @return the lowest positive root or Float.Nan */ public static float getLowestPositiveRoot (float a, float b, float c) { float det = b * b - 4 * a * c; if (det < 0) return Float.NaN; @@ -62,16 +58,14 @@ public static float getLowestPositiveRoot (float a, float b, float c) { private final static Vector3 v1 = new Vector3(); private final static Vector3 v2 = new Vector3(); - /** - * Returns whether the given point is inside the triangle. This assumes that the point is on the plane of the triangle. No + /** 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 * @param t2 the second vertex of the triangle * @param t3 the third vertex of the triangle - * @return whether the point is in the triangle - */ + * @return whether the point is in the triangle */ public static boolean isPointInTriangle (Vector3 point, Vector3 t1, Vector3 t2, Vector3 t3) { v0.set(t1).sub(point); v1.set(t2).sub(point); @@ -98,13 +92,11 @@ public static boolean intersectSegmentPlane (Vector3 start, Vector3 end, Plane p 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 point The point - * @return Wheter the point is in the polygon - */ + * @return Wheter the point is in the polygon */ public static boolean isPointInPolygon (List polygon, Vector2 point) { int j = polygon.size() - 1; @@ -123,15 +115,13 @@ public static boolean isPointInPolygon (List polygon, Vector2 point) { return oddNodes; } - /** - * Returns the distance between the given line segment and point. + /** Returns the distance between the given line segment and point. * * @param start The line start point * @param end The line end point * @param point The point * - * @return The distance between the line segment and 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); float l = tmp.len(); @@ -139,38 +129,34 @@ public static float distanceLinePoint (Vector2 start, Vector2 end, Vector2 point 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 * @param center The center of the circle * @param squareRadius The squared radius of the circle - * @return Wheter the line segment and the circle intersect - */ + * @return Wheter the line segment and the circle intersect */ public static boolean intersectSegmentCircle (Vector2 start, Vector2 end, Vector2 center, float squareRadius) { tmp.set(end.x - start.x, end.y - start.y, 0); tmp1.set(center.x - start.x, center.y - start.y, 0); - float l = tmp.len(); + float l = tmp.len(); float u = tmp1.dot(tmp.nor()); if (u <= 0) { tmp2.set(start.x, start.y, 0); } else if (u >= l) { tmp2.set(end.x, end.y, 0); } else { - tmp3.set(tmp.mul(u)); //remember tmp is already normalized + tmp3.set(tmp.mul(u)); // remember tmp is already normalized tmp2.set(tmp3.x + start.x, tmp3.y + start.y, 0); } float x = center.x - tmp2.x; float y = center.y - tmp2.y; - - return x*x + y*y <= squareRadius; - } + return x * x + y * y <= squareRadius; + } - /** - * Checks wheter the line segment and the circle intersect and returns by how much and in what direction the line has to move + /** 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 @@ -178,8 +164,7 @@ public static boolean intersectSegmentCircle (Vector2 start, Vector2 end, Vector * @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); @@ -196,15 +181,13 @@ public static float intersectSegmentCircleDisplace (Vector2 start, Vector2 end, return Float.POSITIVE_INFINITY; } - /** - * Intersects a {@link Ray} and a {@link Plane}. The intersection point is stored in intersection in case an intersection is + /** 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 (optional) - * @return Whether an intersection is present. - */ + * @return Whether an intersection is present. */ public static boolean intersectRayPlane (Ray ray, Plane plane, Vector3 intersection) { float denom = ray.direction.dot(plane.getNormal()); if (denom != 0) { @@ -223,16 +206,14 @@ public static boolean intersectRayPlane (Ray ray, Plane plane, Vector3 intersect private static final Plane p = new Plane(new Vector3(), 0); private static final Vector3 i = new Vector3(); - /** - * 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 * @param t2 The second vertex of the triangle * @param t3 The third vertex of the triangle * @param intersection The intersection point (optional) - * @return True in case an intersection is present. - */ + * @return True in case an intersection is present. */ 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; @@ -265,15 +246,13 @@ public static boolean intersectRayTriangle (Ray ray, Vector3 t1, Vector3 t2, Vec private static final Vector3 dir = new Vector3(); private static final Vector3 start = new Vector3(); - /** - * 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 * @param radius The radius of the sphere * @param intersection The intersection point (optional) - * @return Whether an intersection is present. - */ + * @return Whether an intersection is present. */ public static boolean intersectRaySphere (Ray ray, Vector3 center, float radius, Vector3 intersection) { dir.set(ray.direction).nor(); start.set(ray.origin); @@ -319,13 +298,11 @@ public static boolean intersectRaySphere (Ray ray, Vector3 center, float radius, } } - /** - * 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 box The bounding box - * @return Wheter the ray and the bounding box intersect. - */ + * @return Wheter the ray and the bounding box intersect. */ static public boolean intersectRayBoundsFast (Ray ray, BoundingBox box) { float a, b; float min, max; @@ -374,14 +351,12 @@ static public boolean intersectRayBoundsFast (Ray ray, BoundingBox box) { static Vector3 tmp2 = new Vector3(); 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 successive 3 elements from a vertex * @param intersection The nearest intersection point (optional) - * @return Whether the ray and the triangles intersect. - */ + * @return Whether the ray and the triangles intersect. */ public static boolean intersectRayTriangles (Ray ray, float[] triangles, Vector3 intersection) { float min_dist = Float.MAX_VALUE; boolean hit = false; @@ -411,16 +386,14 @@ public static boolean intersectRayTriangles (Ray ray, float[] triangles, 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 vertices the vertices * @param indices the indices, each successive 3 shorts index the 3 vertices of a triangle * @param vertexSize the size of a vertex in floats * @param intersection The nearest intersection point (optional) - * @return Whether the ray and the triangles intersect. - */ + * @return Whether the ray and the triangles intersect. */ public static boolean intersectRayTriangles (Ray ray, float[] vertices, short[] indices, int vertexSize, Vector3 intersection) { float min_dist = Float.MAX_VALUE; boolean hit = false; @@ -454,14 +427,12 @@ public static boolean intersectRayTriangles (Ray ray, float[] vertices, short[] } } - /** - * 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 (optional) - * @return Whether the ray and the triangles intersect. - */ + * @return Whether the ray and the triangles intersect. */ public static boolean intersectRayTriangles (Ray ray, List triangles, Vector3 intersection) { float min_dist = Float.MAX_VALUE; @@ -487,28 +458,24 @@ public static boolean intersectRayTriangles (Ray ray, List triangles, V } } - /** - * Returns wheter the two rectangles intersect + /** Returns wheter the two rectangles intersect * * @param a The first rectangle * @param b The second rectangle - * @return Wheter the two rectangles intersect - */ + * @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()); } - /** - * 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 * @param p3 The first point of the second line * @param p4 The second point of the second line * @param intersection The intersection point - * @return Whether the two lines intersect - */ + * @return Whether 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; @@ -525,16 +492,14 @@ public static boolean intersectLines (Vector2 p1, Vector2 p2, Vector2 p3, Vector 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 intersection The intersection point (optional) - * @return Whether the two line segments intersect - */ + * @return Whether 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; @@ -558,48 +523,43 @@ static float det (float a, float b, float c, float d) { static double detd (double a, double b, double c, double d) { return a * d - b * c; } - - public static boolean overlapCircles(Circle c1, Circle c2) { - float x = c1.x - c2.x; - float y = c1.y - c2.y; - float distance = x * x + y * y; - float radiusSum = c1.radius + c2.radius; - return distance <= radiusSum * radiusSum; - } - - public static boolean overlapRectangles(Rectangle r1, Rectangle r2) { - if(r1.x < r2.x + r2.width && - r1.x + r1.width > r2.x && - r1.y < r2.y + r2.height && - r1.y + r1.height > r2.y) - return true; - else - return false; - } - - public static boolean overlapCircleRectangle(Circle c, Rectangle r) { - float closestX = c.x; - float closestY = c.y; - - if(c.x < r.x) { - closestX = r.x; - } - else if(c.x > r.x + r.width) { - closestX = r.x + r.width; - } - - if(c.y < r.y) { - closestY = r.y; - } - else if(c.y > r.y + r.height) { - closestY = r.y + r.height; - } - - closestX = closestX - c.x; - closestX *= closestX; - closestY = closestY - c.y; - closestY *= closestY; - - return closestX + closestY < c.radius * c.radius; - } + + public static boolean overlapCircles (Circle c1, Circle c2) { + float x = c1.x - c2.x; + float y = c1.y - c2.y; + float distance = x * x + y * y; + float radiusSum = c1.radius + c2.radius; + return distance <= radiusSum * radiusSum; + } + + public static boolean overlapRectangles (Rectangle r1, Rectangle r2) { + if (r1.x < r2.x + r2.width && r1.x + r1.width > r2.x && r1.y < r2.y + r2.height && r1.y + r1.height > r2.y) + return true; + else + return false; + } + + public static boolean overlapCircleRectangle (Circle c, Rectangle r) { + float closestX = c.x; + float closestY = c.y; + + if (c.x < r.x) { + closestX = r.x; + } else if (c.x > r.x + r.width) { + closestX = r.x + r.width; + } + + if (c.y < r.y) { + closestY = r.y; + } else if (c.y > r.y + r.height) { + closestY = r.y + r.height; + } + + closestX = closestX - c.x; + closestX *= closestX; + closestY = closestY - c.y; + closestY *= closestY; + + return closestX + closestY < c.radius * c.radius; + } } diff --git a/gdx/src/com/badlogic/gdx/math/MathUtils.java b/gdx/src/com/badlogic/gdx/math/MathUtils.java index 2ff8873ed14..8e00c4d35f9 100644 --- a/gdx/src/com/badlogic/gdx/math/MathUtils.java +++ b/gdx/src/com/badlogic/gdx/math/MathUtils.java @@ -13,17 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.util.Random; import com.badlogic.gdx.utils.NumberUtils; -/** - * Utility and fast math functions.
        +/** Utility and fast math functions.
        *
        - * Thanks to Riven on JavaGaming.org for sin/cos/atan2/floor/ceil.
        - */ + * Thanks to Riven on JavaGaming.org for sin/cos/atan2/floor/ceil.
        */ public class MathUtils { static public final float PI = 3.1415927f; @@ -117,9 +116,7 @@ static public final float atan2 (float y, float x) { static public Random random = new Random(); - /** - * Returns a random number between 0 (inclusive) and the specified value (inclusive). - */ + /** Returns a random number between 0 (inclusive) and the specified value (inclusive). */ static public final int random (int range) { return random.nextInt(range + 1); } @@ -166,52 +163,41 @@ static public boolean isPowerOfTwo (int value) { static private final int BIG_ENOUGH_INT = 16 * 1024; static private final double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT; static private final double CEIL = 0.9999999; - static private final double BIG_ENOUGH_CEIL = NumberUtils.longBitsToDouble(NumberUtils.doubleToLongBits(BIG_ENOUGH_INT + 1) - 1); + static private final double BIG_ENOUGH_CEIL = NumberUtils + .longBitsToDouble(NumberUtils.doubleToLongBits(BIG_ENOUGH_INT + 1) - 1); static private final double BIG_ENOUGH_ROUND = BIG_ENOUGH_INT + 0.5f; - /** - * Returns the largest integer less than or equal to the specified float. This method will only properly floor floats from - * -(2^14) to (Float.MAX_VALUE - 2^14). - */ + /** Returns the largest integer less than or equal to the specified float. This method will only properly floor floats from + * -(2^14) to (Float.MAX_VALUE - 2^14). */ static public int floor (float x) { return (int)(x + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT; } - /** - * Returns the largest integer less than or equal to the specified float. This method will only properly floor floats that are - * positive. Note this method simply casts the float to int. - */ + /** Returns the largest integer less than or equal to the specified float. This method will only properly floor floats that are + * positive. Note this method simply casts the float to int. */ static public int floorPositive (float x) { return (int)x; } - /** - * Returns the smallest integer greater than or equal to the specified float. This method will only properly ceil floats from - * -(2^14) to (Float.MAX_VALUE - 2^14). - */ + /** Returns the smallest integer greater than or equal to the specified float. This method will only properly ceil floats from + * -(2^14) to (Float.MAX_VALUE - 2^14). */ static public int ceil (float x) { return (int)(x + BIG_ENOUGH_CEIL) - BIG_ENOUGH_INT; } - /** - * Returns the smallest integer greater than or equal to the specified float. This method will only properly ceil floats that - * are positive. - */ + /** Returns the smallest integer greater than or equal to the specified float. This method will only properly ceil floats that + * are positive. */ static public int ceilPositive (float x) { return (int)(x + CEIL); } - /** - * Returns the closest integer to the specified float. This method will only properly round floats from -(2^14) to - * (Float.MAX_VALUE - 2^14). - */ + /** Returns the closest integer to the specified float. This method will only properly round floats from -(2^14) to + * (Float.MAX_VALUE - 2^14). */ static public int round (float x) { return (int)(x + BIG_ENOUGH_ROUND) - BIG_ENOUGH_INT; } - /** - * Returns the closest integer to the specified float. This method will only properly round floats that are positive. - */ + /** Returns the closest integer to the specified float. This method will only properly round floats that are positive. */ static public int roundPositive (float x) { return (int)(x + 0.5f); } diff --git a/gdx/src/com/badlogic/gdx/math/Matrix3.java b/gdx/src/com/badlogic/gdx/math/Matrix3.java index 876e47495a0..2016ce48689 100644 --- a/gdx/src/com/badlogic/gdx/math/Matrix3.java +++ b/gdx/src/com/badlogic/gdx/math/Matrix3.java @@ -20,12 +20,9 @@ import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * A 3x3 column major matrix for 2D transforms. +/** A 3x3 column major matrix for 2D transforms. * - * @author mzechner - * - */ + * @author mzechner */ public class Matrix3 implements Serializable { private static final long serialVersionUID = 7907569533774959788L; private final static float DEGREE_TO_RAD = (float)Math.PI / 180; @@ -35,10 +32,8 @@ public Matrix3 () { idt(); } - /** - * Sets this matrix to the identity matrix - * @return this matrix - */ + /** Sets this matrix to the identity matrix + * @return this matrix */ public Matrix3 idt () { this.vals[0] = 1; this.vals[1] = 0; @@ -55,10 +50,8 @@ public Matrix3 idt () { return this; } - /** - * Multiplies this matrix with the other matrix in the order this * m. - * @return this matrix - */ + /** Multiplies this matrix with the other matrix in the order this * m. + * @return this matrix */ 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]; @@ -85,11 +78,9 @@ public Matrix3 mul (Matrix3 m) { 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 - */ + * @return this matrix */ public Matrix3 setToRotation (float angle) { angle = DEGREE_TO_RAD * angle; float cos = (float)Math.cos(angle); @@ -110,12 +101,10 @@ public Matrix3 setToRotation (float angle) { return this; } - /** - * Sets this matrix to a translation matrix. + /** Sets this matrix to a translation matrix. * @param x the translation in x * @param y the translation in y - * @return this matrix - */ + * @return this matrix */ public Matrix3 setToTranslation (float x, float y) { this.vals[0] = 1; this.vals[1] = 0; @@ -132,13 +121,11 @@ public Matrix3 setToTranslation (float x, float y) { return this; } - /** - * Sets this matrix to a scaling matrix + /** Sets this matrix to a scaling matrix * * @param sx the scale in x * @param sy the scale in y - * @return this matrix - */ + * @return this matrix */ public Matrix3 setToScaling (float sx, float sy) { this.vals[0] = sx; this.vals[1] = 0; @@ -160,18 +147,14 @@ public String toString () { + vals[2] + "|" + vals[5] + "|" + vals[8] + "]"; } - /** - * @return the determinant of this matrix - */ + /** @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]; } - /** - * Inverts this matrix given that the determinant is != 0 - * @return this matrix - */ + /** 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"); @@ -202,36 +185,36 @@ public Matrix3 inv () { return this; } -// public static void main (String[] argv) { -// float refX = 50, refY = -50; -// float scaleX = 2, scaleY = 1; -// float rotation = 45; -// float x = -232, y = 123; +// 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(); +// 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()); +// 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)); +// 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(); -// 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)); -// } +// 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)); +// } public Matrix3 set (Matrix3 mat) { vals[0] = mat.vals[0]; @@ -246,23 +229,19 @@ public Matrix3 set (Matrix3 mat) { return this; } - /** - * Adds a translational component to the matrix in the 3rd column. The other columns are untouched. + /** Adds a translational component to the matrix in the 3rd column. The other columns are untouched. * @param vector The translation vector - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix3 trn (Vector3 vector) { vals[6] += vector.x; vals[7] += vector.y; return this; } - /** - * Adds a translational component to the matrix in the 3rd column. The other columns are untouched. + /** Adds a translational component to the matrix in the 3rd column. The other columns are untouched. * @param x The x-component of the translation vector * @param y The y-component of the translation vector - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix3 trn (float x, float y) { vals[6] += x; vals[7] += y; diff --git a/gdx/src/com/badlogic/gdx/math/Matrix4.java b/gdx/src/com/badlogic/gdx/math/Matrix4.java index ed6f94fe649..eff08ac80bd 100644 --- a/gdx/src/com/badlogic/gdx/math/Matrix4.java +++ b/gdx/src/com/badlogic/gdx/math/Matrix4.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.io.Serializable; -/** - * Encapsulates a column major 4 by 4 matrix. You can access the linear array for use with OpenGL via the public +/** 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 - * - */ + * @author badlogicgames@gmail.com */ public class Matrix4 implements Serializable { private static final long serialVersionUID = -2717655254359579617L; public static final int M00 = 0;// 0; @@ -46,9 +44,7 @@ public class Matrix4 implements Serializable { public final float tmp[] = new float[16]; public final float val[] = new float[16]; - /** - * Constructs an identity matrix - */ + /** Constructs an identity matrix */ public Matrix4 () { val[M00] = 1f; val[M11] = 1f; @@ -56,47 +52,37 @@ public Matrix4 () { val[M33] = 1f; } - /** - * Constructs a matrix from the given matrix + /** Constructs a matrix from the given matrix * - * @param matrix The 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 - */ + /** 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 - */ + /** 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. + /** Sets the matrix to the given matrix. * * @param matrix The matrix - * @return This matrix for chaining - */ + * @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. + /** 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 - */ + * @return This matrix for chaining */ public Matrix4 set (float[] values) { val[M00] = values[M00]; val[M10] = values[M10]; @@ -117,13 +103,11 @@ public Matrix4 set (float[] values) { return this; } - /** - * Sets the matrix to a rotation matrix representing the quaternion. + /** Sets the matrix to a rotation matrix representing the quaternion. * * @param quaternion The quaternion - * @return This matrix for chaining - */ - public Matrix4 set (Quaternion 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; @@ -154,15 +138,13 @@ public Matrix4 set (Quaternion quaternion) { 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 + /** 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 - */ + * @param pos The translation vector */ public void set (Vector3 xAxis, Vector3 yAxis, Vector3 zAxis, Vector3 pos) { val[M00] = xAxis.x; val[M01] = xAxis.y; @@ -182,19 +164,15 @@ public void set (Vector3 xAxis, Vector3 yAxis, Vector3 zAxis, Vector3 pos) { val[M33] = 1; } - /** - * @return a copy of this matrix - */ + /** @return a copy of this matrix */ public Matrix4 cpy () { return new Matrix4(this); } - /** - * Adds a translational component to the matrix in the 4th column. The other columns are untouched. + /** Adds a translational component to the matrix in the 4th column. The other columns are untouched. * * @param vector The translation vector - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix4 trn (Vector3 vector) { val[M03] += vector.x; val[M13] += vector.y; @@ -202,14 +180,12 @@ public Matrix4 trn (Vector3 vector) { return this; } - /** - * Adds a translational component to the matrix in the 4th column. The other columns are untouched. + /** Adds a translational component to the matrix in the 4th column. The other columns are untouched. * * @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 - */ + * @return This matrix for chaining */ public Matrix4 trn (float x, float y, float z) { val[M03] += x; val[M13] += y; @@ -217,19 +193,15 @@ public Matrix4 trn (float x, float y, float z) { return this; } - /** - * @return the backing float array - */ + /** @return the backing float array */ public float[] getValues () { return val; } - /** - * Multiplies this matrix with the given matrix, storing the result in this matrix. + /** Multiplies this matrix with the given matrix, storing the result in this matrix. * * @param matrix The other matrix - * @return This matrix for chaining. - */ + * @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]; @@ -264,13 +236,11 @@ public Matrix4 mul (Matrix4 matrix) { 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 + /** Transposes the matrix * - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix4 tra () { tmp[M00] = val[M00]; tmp[M01] = val[M10]; @@ -291,11 +261,9 @@ public Matrix4 tra () { return this.set(tmp); } - /** - * Sets the matrix to an identity matrix + /** Sets the matrix to an identity matrix * - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix4 idt () { val[M00] = 1; val[M01] = 0; @@ -316,21 +284,19 @@ public Matrix4 idt () { return this; } - /** - * Inverts the matrix. Throws a RuntimeException in case the matrix is not invertible. Stores the result in this matrix + /** Inverts the matrix. Throws a RuntimeException in case the matrix is not invertible. Stores the result in this matrix * - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix4 inv () { float l_det = 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]; + * 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]; if (l_det == 0f) throw new RuntimeException("non-invertible matrix"); float inv_det = 1.0f / l_det; tmp[M00] = val[M12] * val[M23] * val[M31] - val[M13] * val[M22] * val[M31] + val[M13] * val[M21] * val[M32] - val[M11] @@ -364,7 +330,7 @@ public Matrix4 inv () { 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]; + * val[M12] * val[M21] - val[M01] * val[M10] * val[M22] + val[M00] * val[M11] * val[M22]; val[M00] = tmp[M00] * inv_det; val[M01] = tmp[M01] * inv_det; val[M02] = tmp[M02] * inv_det; @@ -382,11 +348,9 @@ public Matrix4 inv () { val[M32] = tmp[M32] * inv_det; val[M33] = tmp[M33] * inv_det; return this; - } + } - /** - * @return The determinant of this matrix - */ + /** @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] @@ -399,16 +363,14 @@ public float det () { * 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. + /** 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) { + * @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) / (near - far); @@ -429,27 +391,24 @@ public Matrix4 setToProjection (float near, float far, float fov, float aspectRa 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 + /** 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 - */ + * @return This matrix for chaining */ public Matrix4 setToOrtho2D (float x, float y, float width, float height) { setToOrtho(x, x + width, y, y + 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 + /** 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 @@ -458,15 +417,13 @@ public Matrix4 setToOrtho2D (float x, float y, float width, float height) { * @param height The height * @param near The near plane * @param far The far plane - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix4 setToOrtho2D (float x, float y, float width, float height, float near, float far) { setToOrtho(x, x + width, y, y + 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 + /** 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 @@ -475,8 +432,7 @@ public Matrix4 setToOrtho2D (float x, float y, float width, float height, float * @param top The top clipping plane * @param near The near clipping plane * @param far The far clipping plane - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix4 setToOrtho (float left, float right, float bottom, float top, float near, float far) { this.idt(); @@ -508,13 +464,11 @@ public Matrix4 setToOrtho (float left, float right, float bottom, float top, flo return this; } - /** - * Sets this matrix to a translation matrix, overwriting it first by an identity matrix and then setting the 4th column to the + /** 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 - */ + * @return This matrix for chaining */ public Matrix4 setToTranslation (Vector3 vector) { this.idt(); val[M03] = vector.x; @@ -523,15 +477,13 @@ public Matrix4 setToTranslation (Vector3 vector) { return this; } - /** - * Sets this matrix to a translation matrix, overwriting it first by an identity matrix and then setting the 4th column to the + /** 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 - */ + * @return This matrix for chaining */ public Matrix4 setToTranslation (float x, float y, float z) { idt(); val[M03] = x; @@ -540,14 +492,12 @@ public Matrix4 setToTranslation (float x, float y, float z) { return this; } - /** - * Sets this matrix to a translation and scaling matrix by first overwritting it with an identity and then setting the + /** 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 - */ + * @return This matrix for chaining */ public Matrix4 setToTranslationAndScaling (Vector3 translation, Vector3 scaling) { idt(); val[M03] = translation.x; @@ -559,8 +509,7 @@ public Matrix4 setToTranslationAndScaling (Vector3 translation, Vector3 scaling) return this; } - /** - * Sets this matrix to a translation and scaling matrix by first overwritting it with an identity and then setting the + /** 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 @@ -569,8 +518,7 @@ public Matrix4 setToTranslationAndScaling (Vector3 translation, Vector3 scaling) * @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 - */ + * @return This matrix for chaining */ public Matrix4 setToTranslationAndScaling (float translationX, float translationY, float translationZ, float scalingX, float scalingY, float scalingZ) { this.idt(); @@ -585,54 +533,47 @@ public Matrix4 setToTranslationAndScaling (float translationX, float translation static Quaternion quat = new Quaternion(); - /** - * Sets the matrix to a rotation matrix around the given axis. + /** 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 - */ + * @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 the matrix to a rotation matrix around the given axis. + + /** Sets the matrix to a rotation matrix around the given axis. * * @param axisX The x-component of the axis * @param axisY The y-component of the axis * @param axisZ The z-component of the axis * @param angle The angle in degrees - * @return This matrix for chaining - */ + * @return This matrix for chaining */ public Matrix4 setToRotation (float axisX, float axisY, float axisZ, float angle) { idt(); if (angle == 0) return this; return this.set(quat.set(tmpV.set(axisX, axisY, axisZ), angle)); } + static final Vector3 tmpV = new Vector3(); - /** - * Sets this matrix to a rotation matrix from the given euler angles. + /** 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 - */ + * @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 + /** Sets this matrix to a scaling matrix * * @param vector The scaling vector - * @return This matrix for chaining. - */ + * @return This matrix for chaining. */ public Matrix4 setToScaling (Vector3 vector) { idt(); val[M00] = vector.x; @@ -641,14 +582,12 @@ public Matrix4 setToScaling (Vector3 vector) { return this; } - /** - * Sets this matrix to a scaling matrix + /** 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. - */ + * @return This matrix for chaining. */ public Matrix4 setToScaling (float x, float y, float z) { idt(); val[M00] = x; @@ -661,14 +600,12 @@ public Matrix4 setToScaling (float x, float y, float z) { 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 + /** 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 - */ + * @return This matrix for chaining */ public Matrix4 setToLookAt (Vector3 direction, Vector3 up) { l_vez.set(direction).nor(); l_vex.set(direction).nor(); @@ -691,14 +628,12 @@ public Matrix4 setToLookAt (Vector3 direction, Vector3 up) { static final Vector3 tmpVec = new Vector3(); static final Matrix4 tmpMat = new Matrix4(); - /** - * Sets this matrix to a look at matrix with the given position, target and up vector. + /** 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 - */ + * @return this matrix */ public Matrix4 setToLookAt (Vector3 position, Vector3 target, Vector3 up) { tmpVec.set(target).sub(position); setToLookAt(tmpVec, up); @@ -720,29 +655,23 @@ public Matrix4 setToWorld (Vector3 position, Vector3 forward, Vector3 up) { return this; } - /** - * {@inheritDoc} - */ + /** {@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 + /** 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] - */ + * @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 - */ + /** 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) { val[0] = mat.vals[0]; val[1] = mat.vals[1]; @@ -778,126 +707,95 @@ public void getTranslation (Vector3 position) { public void getRotation (Quaternion rotation) { rotation.setFromMatrix(this); } - - /** - * removes the translational part and transposes the - * matrix. - */ - public Matrix4 toNormalMatrix() { + + /** removes the translational part and transposes the matrix. */ + public Matrix4 toNormalMatrix () { val[M03] = 0; val[M13] = 0; val[M23] = 0; inv(); return tra(); } - - /** - * Multiplies the matrix mata with matrix matb, storing the result in mata. The - * arrays are assumed to hold 4x4 column major matrices as you can get from {@link Matrix4#val}. - * This is the same as {@link Matrix4#mul(Matrix4)}. + + /** Multiplies the matrix mata with matrix matb, storing the result in mata. The arrays are assumed to hold 4x4 column major + * matrices as you can get from {@link Matrix4#val}. This is the same as {@link Matrix4#mul(Matrix4)}. * * @param mata the first matrix. - * @param matb the second matrix. - */ - public static native void mul(float[] mata, float[] matb) /*-{ }-*/; - - /** - * Multiplies the vector with the given matrix. The matrix array is assumed to hold a - * 4x4 column major matrix as you can get from {@link Matrix4#val}. The vector array is - * assumed to hold a 3-component vector, with x being the first element, y being the second - * and z being the last component. The result is stored in the vector array. This is the - * same as {@link Vector3#mul(Matrix4)}. + * @param matb the second matrix. */ + public static native void mul (float[] mata, float[] matb) /*-{ }-*/; + + /** Multiplies the vector with the given matrix. The matrix array is assumed to hold a 4x4 column major matrix as you can get + * from {@link Matrix4#val}. The vector array is assumed to hold a 3-component vector, with x being the first element, y being + * the second and z being the last component. The result is stored in the vector array. This is the same as + * {@link Vector3#mul(Matrix4)}. * @param mat the matrix - * @param vec the vector. - */ - public static native void mulVec(float[] mat, float[] vec) /*-{ }-*/; - - /** - * Multiplies the vectors with the given matrix. The matrix array is assumed to hold a 4x4 - * column major matrix as you can get from {@link Matrix4#val}. The vectors array is assumed - * to hold 3-component vectors. Offset specifies the offset into the array where the x-component - * of the first vector is located. The numVecs parameter specifies the number of vectors stored - * in the vectors array. The stride parameter specifies the number of floats between subsequent - * vectors and must be >= 3. This is the same as {@link Vector3#mul(Matrix4)} applied to multiple - * vectors. - * + * @param vec the vector. */ + public static native void mulVec (float[] mat, float[] vec) /*-{ }-*/; + + /** Multiplies the vectors with the given matrix. The matrix array is assumed to hold a 4x4 column major matrix as you can get + * from {@link Matrix4#val}. The vectors array is assumed to hold 3-component vectors. Offset specifies the offset into the + * array where the x-component of the first vector is located. The numVecs parameter specifies the number of vectors stored in + * the vectors array. The stride parameter specifies the number of floats between subsequent vectors and must be >= 3. This is + * the same as {@link Vector3#mul(Matrix4)} applied to multiple vectors. + * * @param mat the matrix * @param vecs the vectors * @param offset the offset into the vectors array * @param numVecs the number of vectors - * @param stride the stride between vectors in floats - */ - public static native void mulVec(float[] mat, float[] vecs, int offset, int numVecs, int stride) /*-{ }-*/; - - /** - * Multiplies the vector with the given matrix, performing a division by w. The matrix array is assumed to hold a - * 4x4 column major matrix as you can get from {@link Matrix4#val}. The vector array is - * assumed to hold a 3-component vector, with x being the first element, y being the second - * and z being the last component. The result is stored in the vector array. This is the same as - * {@link Vector3#prj(Matrix4)}. + * @param stride the stride between vectors in floats */ + public static native void mulVec (float[] mat, float[] vecs, int offset, int numVecs, int stride) /*-{ }-*/; + + /** Multiplies the vector with the given matrix, performing a division by w. The matrix array is assumed to hold a 4x4 column + * major matrix as you can get from {@link Matrix4#val}. The vector array is assumed to hold a 3-component vector, with x being + * the first element, y being the second and z being the last component. The result is stored in the vector array. This is the + * same as {@link Vector3#prj(Matrix4)}. * @param mat the matrix - * @param vec the vector. - */ - public static native void prj(float[] mat, float[] vec) /*-{ }-*/; - - /** - * Multiplies the vectors with the given matrix, , performing a division by w. The matrix array is assumed to hold a 4x4 - * column major matrix as you can get from {@link Matrix4#val}. The vectors array is assumed - * to hold 3-component vectors. Offset specifies the offset into the array where the x-component - * of the first vector is located. The numVecs parameter specifies the number of vectors stored - * in the vectors array. The stride parameter specifies the number of floats between subsequent - * vectors and must be >= 3. This is the same as {@link Vector3#prj(Matrix4)} applied to multiple - * vectors. - * + * @param vec the vector. */ + public static native void prj (float[] mat, float[] vec) /*-{ }-*/; + + /** Multiplies the vectors with the given matrix, , performing a division by w. The matrix array is assumed to hold a 4x4 column + * major matrix as you can get from {@link Matrix4#val}. The vectors array is assumed to hold 3-component vectors. Offset + * specifies the offset into the array where the x-component of the first vector is located. The numVecs parameter specifies + * the number of vectors stored in the vectors array. The stride parameter specifies the number of floats between subsequent + * vectors and must be >= 3. This is the same as {@link Vector3#prj(Matrix4)} applied to multiple vectors. + * * @param mat the matrix * @param vecs the vectors * @param offset the offset into the vectors array * @param numVecs the number of vectors - * @param stride the stride between vectors in floats - */ - public static native void prj(float[] mat, float[] vecs, int offset, int numVecs, int stride) /*-{ }-*/; - - /** - * Multiplies the vector with the top most 3x3 sub-matrix of the given matrix. The matrix array is assumed to hold a - * 4x4 column major matrix as you can get from {@link Matrix4#val}. The vector array is - * assumed to hold a 3-component vector, with x being the first element, y being the second - * and z being the last component. The result is stored in the vector array. This is the same as - * {@link Vector3#rot(Matrix4)}. + * @param stride the stride between vectors in floats */ + public static native void prj (float[] mat, float[] vecs, int offset, int numVecs, int stride) /*-{ }-*/; + + /** Multiplies the vector with the top most 3x3 sub-matrix of the given matrix. The matrix array is assumed to hold a 4x4 column + * major matrix as you can get from {@link Matrix4#val}. The vector array is assumed to hold a 3-component vector, with x being + * the first element, y being the second and z being the last component. The result is stored in the vector array. This is the + * same as {@link Vector3#rot(Matrix4)}. * @param mat the matrix - * @param vec the vector. - */ - public static native void rot(float[] mat, float[] vec) /*-{ }-*/; - - /** - * Multiplies the vectors with the top most 3x3 sub-matrix of the given matrix. The matrix array is assumed to hold a 4x4 - * column major matrix as you can get from {@link Matrix4#val}. The vectors array is assumed - * to hold 3-component vectors. Offset specifies the offset into the array where the x-component - * of the first vector is located. The numVecs parameter specifies the number of vectors stored - * in the vectors array. The stride parameter specifies the number of floats between subsequent - * vectors and must be >= 3. This is the same as {@link Vector3#rot(Matrix4)} applied to multiple - * vectors. - * + * @param vec the vector. */ + public static native void rot (float[] mat, float[] vec) /*-{ }-*/; + + /** Multiplies the vectors with the top most 3x3 sub-matrix of the given matrix. The matrix array is assumed to hold a 4x4 + * column major matrix as you can get from {@link Matrix4#val}. The vectors array is assumed to hold 3-component vectors. + * Offset specifies the offset into the array where the x-component of the first vector is located. The numVecs parameter + * specifies the number of vectors stored in the vectors array. The stride parameter specifies the number of floats between + * subsequent vectors and must be >= 3. This is the same as {@link Vector3#rot(Matrix4)} applied to multiple vectors. + * * @param mat the matrix * @param vecs the vectors * @param offset the offset into the vectors array * @param numVecs the number of vectors - * @param stride the stride between vectors in floats - */ - public static native void rot(float[] mat, float[] vecs, int offset, int numVecs, int stride) /*-{ }-*/; - - /** - * Computes the inverse of the given matrix. The matrix array is assumed to hold a 4x4 - * column major matrix as you can get from {@link Matrix4#val}. + * @param stride the stride between vectors in floats */ + public static native void rot (float[] mat, float[] vecs, int offset, int numVecs, int stride) /*-{ }-*/; + + /** Computes the inverse of the given matrix. The matrix array is assumed to hold a 4x4 column major matrix as you can get from + * {@link Matrix4#val}. * @param values the matrix values. - * @return false in case the inverse could not be calculated, true otherwise. - */ - public static native boolean inv(float[] values) /*-{ }-*/; - - /** - * Computes the determinante of the given matrix. The matrix array is assumed to hold a 4x4 - * column major matrix as you can get from {@link Matrix4#val}. + * @return false in case the inverse could not be calculated, true otherwise. */ + public static native boolean inv (float[] values) /*-{ }-*/; + + /** Computes the determinante of the given matrix. The matrix array is assumed to hold a 4x4 column major matrix as you can get + * from {@link Matrix4#val}. * @param values the matrix values. - * @return the determinante. - */ - public static native float det(float[] values) /*-{ }-*/; + * @return the determinante. */ + public static native float det (float[] values) /*-{ }-*/; } diff --git a/gdx/src/com/badlogic/gdx/math/Plane.java b/gdx/src/com/badlogic/gdx/math/Plane.java index 42bb05f75c0..4d13db57a6a 100644 --- a/gdx/src/com/badlogic/gdx/math/Plane.java +++ b/gdx/src/com/badlogic/gdx/math/Plane.java @@ -13,26 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.io.Serializable; -/** - * 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 +/** A plane defined via a unit length normal and the distance from the origin, as you learned in your math class. * - */ -public class Plane implements Serializable { + * @author badlogicgames@gmail.com */ +public class Plane implements Serializable { private static final long serialVersionUID = -1240652082930747866L; - /** - * Enum specifying on which side a point lies respective to the plane and it's normal. {@link PlaneSide#Front} is the side to + /** 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 - * - */ + * @author mzechner */ public enum PlaneSide { OnPlane, Back, Front } @@ -40,48 +35,40 @@ public enum PlaneSide { 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 - */ + * @param d The distance to the origin */ 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 - */ + * @param point The point on the plane */ public Plane (Vector3 normal, Vector3 point) { this.normal.set(normal).nor(); 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 + /** 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 point2 The second point - * @param point3 The third point - */ + * @param point3 The third point */ 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. + /** 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 - */ + * @param point3 */ public void set (Vector3 point1, Vector3 point2, Vector3 point3) { Vector3 l = point1.tmp().sub(point2); Vector3 r = point2.tmp2().sub(point3); @@ -90,36 +77,30 @@ public void set (Vector3 point1, Vector3 point2, Vector3 point3) { d = -point1.dot(nor); } - /** - * Sets the plane normal and distance + /** Sets the plane normal and distance * * @param nx normal x-component * @param ny normal y-component * @param nz normal z-component - * @param d distance to origin - */ + * @param d distance to origin */ 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 - */ + * @return the shortest signed distance between the plane and the point */ 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 + /** 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 - */ + * @return The side the point lies relative to the plane */ public PlaneSide testPoint (Vector3 point) { float dist = normal.dot(point) + d; @@ -131,48 +112,38 @@ else if (dist < 0) return PlaneSide.Front; } - /** - * Returns whether the plane is facing the direction vector. Think of the direction vector as the direction a camera looks in. + /** 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 - */ + * @return whether the plane is front facing */ public boolean isFrontFacing (Vector3 direction) { float dot = normal.dot(direction); return dot <= 0; } - /** - * @return The normal - */ + /** @return The normal */ public Vector3 getNormal () { return normal; } - /** - * @return The distance to the origin - */ + /** @return The distance to the origin */ public float getD () { return d; } - /** - * Sets the plane to the given point and normal. + /** Sets the plane to the given point and normal. * * @param point the point on the plane - * @param normal the normal of the plane - */ + * @param normal the normal of the plane */ public void set (Vector3 point, Vector3 normal) { this.normal.set(normal); d = -point.dot(normal); } - /** - * Sets this plane from the given plane + /** Sets this plane from the given plane * - * @param plane the plane - */ + * @param plane the plane */ public void set (Plane plane) { this.normal.set(plane.normal); this.d = plane.d; diff --git a/gdx/src/com/badlogic/gdx/math/Polygon.java b/gdx/src/com/badlogic/gdx/math/Polygon.java index 325bf235f50..06848d67520 100644 --- a/gdx/src/com/badlogic/gdx/math/Polygon.java +++ b/gdx/src/com/badlogic/gdx/math/Polygon.java @@ -1,11 +1,10 @@ + package com.badlogic.gdx.math; import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.math.MathUtils; -import com.badlogic.gdx.math.Rectangle; public class Polygon { - + private final float[] vertices; private float x, y; private float originX, originY; @@ -13,57 +12,56 @@ public class Polygon { private float scaleX = 1, scaleY = 1; private boolean dirty; private Rectangle bounds = new Rectangle(); - + public Polygon (float[] vertices) { - if (vertices.length < 6) - throw new IllegalArgumentException("polygons must contain at least 3 points."); + if (vertices.length < 6) throw new IllegalArgumentException("polygons must contain at least 3 points."); this.vertices = vertices; } - - public float[] getVertices () { + + public float[] getVertices () { if (!dirty) return vertices; - + float[] vertices = this.vertices; final int numFloats = vertices.length; - + final float translateX = x + originX; final float translateY = y + originY; final float cos = MathUtils.cosDeg(rotation); final float sin = MathUtils.sinDeg(rotation); float x, y; - for (int i=0; i vertices[i] ? vertices[i] : minX; - minY = minY > vertices[i+1] ? vertices[i+1] : minY; + minY = minY > vertices[i + 1] ? vertices[i + 1] : minY; maxX = maxX < vertices[i] ? vertices[i] : maxX; - maxY = maxY < vertices[i+1] ? vertices[i+1] : maxY; + maxY = maxY < vertices[i + 1] ? vertices[i + 1] : maxY; } - + bounds.x = minX; bounds.y = minY; bounds.width = maxX - minX; bounds.height = maxY - minY; - + return bounds; } - + public boolean contains (float x, float y) { final float[] vertices = getVertices(); final int numFloats = vertices.length; int intersects = 0; - - for (int i=0; i NORMALIZATION_TOLERANCE)) { - len = (float) Math.sqrt(len); + if (len != 0.f && (Math.abs(len - 1.0f) > NORMALIZATION_TOLERANCE)) { + len = (float)Math.sqrt(len); w /= len; x /= len; y /= len; @@ -181,25 +153,21 @@ public Quaternion nor() { return this; } - /** - * Conjugate the quaternion. - * - * @return This quaternion for chaining - */ - public Quaternion conjugate() { + /** Conjugate the quaternion. + * + * @return This quaternion for chaining */ + public Quaternion conjugate () { x = -x; y = -y; z = -z; return this; } - //TODO : this would better fit into the vector3 class - /** - * Transforms the given vector using this quaternion - * - * @param v Vector to transform - */ - public void transform(Vector3 v) { + // TODO : this would better fit into the vector3 class + /** Transforms the given vector using this quaternion + * + * @param v Vector to transform */ + public void transform (Vector3 v) { tmp2.set(this); tmp2.conjugate(); tmp2.mulLeft(tmp1.set(v.x, v.y, v.z, 0)).mulLeft(this); @@ -209,13 +177,11 @@ public void transform(Vector3 v) { v.z = tmp2.z; } - /** - * Multiplies this quaternion with another one - * + /** Multiplies this quaternion with another one + * * @param q Quaternion to multiply with - * @return This quaternion for chaining - */ - public Quaternion mul(Quaternion q) { + * @return This quaternion for chaining */ + public Quaternion mul (Quaternion q) { float newX = w * q.x + x * q.w + y * q.z - z * q.y; float newY = w * q.y + y * q.w + z * q.x - x * q.z; float newZ = w * q.z + z * q.w + x * q.y - y * q.x; @@ -227,13 +193,11 @@ public Quaternion mul(Quaternion q) { return this; } - /** - * Multiplies this quaternion with another one in the form of q * this - * + /** Multiplies this quaternion with another one in the form of q * this + * * @param q Quaternion to multiply with - * @return This quaternion for chaining - */ - public Quaternion mulLeft(Quaternion q) { + * @return This quaternion for chaining */ + public Quaternion mulLeft (Quaternion q) { float newX = q.w * x + q.x * w + q.y * z - q.z * y; float newY = q.w * y + q.y * w + q.z * x - q.x * z; float newZ = q.w * z + q.z * w + q.x * y - q.y * x; @@ -245,13 +209,12 @@ public Quaternion mulLeft(Quaternion q) { return this; } - //TODO : the matrix4 set(quaternion) doesnt set the last row+col of the matrix to 0,0,0,1 so... that's why there is this method - /** - * Fills a 4x4 matrix with the rotation matrix represented by this quaternion. - * - * @param matrix Matrix to fill - */ - public void toMatrix(float[] matrix) { + // TODO : the matrix4 set(quaternion) doesnt set the last row+col of the matrix to 0,0,0,1 so... that's why there is this +// method + /** Fills a 4x4 matrix with the rotation matrix represented by this quaternion. + * + * @param matrix Matrix to fill */ + public void toMatrix (float[] matrix) { float xx = x * x; float xy = x * y; float xz = x * z; @@ -280,60 +243,57 @@ public void toMatrix(float[] matrix) { matrix[Matrix4.M33] = 1; } - /** - * Returns the identity quaternion x,y,z = 0 and w=1 - * - * @return Identity quaternion - */ - public static Quaternion idt() { + /** Returns the identity quaternion x,y,z = 0 and w=1 + * + * @return Identity quaternion */ + public static Quaternion idt () { return new Quaternion(0, 0, 0, 1); } - //todo : the setFromAxis(v3,float) method should replace the set(v3,float) method - /** - * Sets the quaternion components from the given axis and angle around that axis. - * + // todo : the setFromAxis(v3,float) method should replace the set(v3,float) method + /** 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 setFromAxis(Vector3 axis, float angle) { + * @return This quaternion for chaining. */ + public Quaternion setFromAxis (Vector3 axis, float angle) { return setFromAxis(axis.x, axis.y, axis.z, angle); } - /** - * Sets the quaternion components from the given axis and angle around that axis. - * + /** Sets the quaternion components from the given axis and angle around that axis. + * * @param x X direction of the axis * @param y Y direction of the axis * @param z Z direction of the axis * @param angle The angle in degrees - * @return This quaternion for chaining. - */ - public Quaternion setFromAxis(float x, float y, float z, float angle) { + * @return This quaternion for chaining. */ + public Quaternion setFromAxis (float x, float y, float z, float angle) { float l_ang = angle * MathUtils.degreesToRadians; float l_sin = MathUtils.sin(l_ang / 2); float l_cos = MathUtils.cos(l_ang / 2); return this.set(x * l_sin, y * l_sin, z * l_sin, l_cos).nor(); } - -// fromRotationMatrix(xAxis.x, yAxis.x, zAxis.x, xAxis.y, yAxis.y, zAxis.y, -// xAxis.z, yAxis.z, zAxis.z); - -// final float m00, final float m01, final float m02, final float m10, -// final float m11, final float m12, final float m20, final float m21, final float m22 - - public Quaternion setFromMatrix(Matrix4 matrix) { - return setFromAxes(matrix.val[Matrix4.M00], matrix.val[Matrix4.M01], matrix.val[Matrix4.M02], - matrix.val[Matrix4.M10], matrix.val[Matrix4.M11], matrix.val[Matrix4.M12], - matrix.val[Matrix4.M20], matrix.val[Matrix4.M21], matrix.val[Matrix4.M22]); + +// fromRotationMatrix(xAxis.x, yAxis.x, zAxis.x, xAxis.y, yAxis.y, zAxis.y, +// xAxis.z, yAxis.z, zAxis.z); + +// final float m00, final float m01, final float m02, final float m10, +// final float m11, final float m12, final float m20, final float m21, final float m22 + + public Quaternion setFromMatrix (Matrix4 matrix) { + return setFromAxes(matrix.val[Matrix4.M00], matrix.val[Matrix4.M01], matrix.val[Matrix4.M02], matrix.val[Matrix4.M10], + matrix.val[Matrix4.M11], matrix.val[Matrix4.M12], matrix.val[Matrix4.M20], matrix.val[Matrix4.M21], + matrix.val[Matrix4.M22]); } - - /** - *

        Sets the Quaternion from the given x-, y- and z-axis which have to be orthonormal.

        + + /**

        + * Sets the Quaternion from the given x-, y- and z-axis which have to be orthonormal. + *

        * - *

        Taken from Bones framework for JPCT, see http://www.aptalkarga.com/bones/ which - * in turn took it from Graphics Gem code at ftp://ftp.cis.upenn.edu/pub/graphics/shoemake/quatut.ps.Z.

        + *

        + * Taken from Bones framework for JPCT, see http://www.aptalkarga.com/bones/ which in turn took it from Graphics Gem code at + * ftp://ftp.cis.upenn.edu/pub/graphics/shoemake/quatut.ps.Z. + *

        * * @param xx x-axis x-coordinate * @param xy x-axis y-coordinate @@ -343,135 +303,124 @@ public Quaternion setFromMatrix(Matrix4 matrix) { * @param yz y-axis z-coordinate * @param zx z-axis x-coordinate * @param zy z-axis y-coordinate - * @param zz z-axis z-coordinate - */ - public Quaternion setFromAxes(float xx, float xy, float xz, - float yx, float yy, float yz, - float zx, float zy, float zz) { - // the trace is the sum of the diagonal elements; see - // http://mathworld.wolfram.com/MatrixTrace.html + * @param zz z-axis z-coordinate */ + public Quaternion setFromAxes (float xx, float xy, float xz, float yx, float yy, float yz, float zx, float zy, float zz) { + // the trace is the sum of the diagonal elements; see + // http://mathworld.wolfram.com/MatrixTrace.html final float m00 = xx, m01 = yx, m02 = zx; final float m10 = xy, m11 = yy, m12 = zy; final float m20 = xz, m21 = yz, m22 = zz; - final float t = m00 + m11 + m22; - - // we protect the division by s by ensuring that s>=1 - double x, y, z, w; - if (t >= 0) { // |w| >= .5 - double s = Math.sqrt(t + 1); // |s|>=1 ... - w = 0.5 * s; - s = 0.5 / s; // so this division isn't bad - x = (m21 - m12) * s; - y = (m02 - m20) * s; - z = (m10 - m01) * s; - } else if ((m00 > m11) && (m00 > m22)) { - double s = Math.sqrt(1.0 + m00 - m11 - m22); // |s|>=1 - x = s * 0.5; // |x| >= .5 - s = 0.5 / s; - y = (m10 + m01) * s; - z = (m02 + m20) * s; - w = (m21 - m12) * s; - } else if (m11 > m22) { - double s = Math.sqrt(1.0 + m11 - m00 - m22); // |s|>=1 - y = s * 0.5; // |y| >= .5 - s = 0.5 / s; - x = (m10 + m01) * s; - z = (m21 + m12) * s; - w = (m02 - m20) * s; - } else { - double s = Math.sqrt(1.0 + m22 - m00 - m11); // |s|>=1 - z = s * 0.5; // |z| >= .5 - s = 0.5 / s; - x = (m02 + m20) * s; - y = (m21 + m12) * s; - w = (m10 - m01) * s; - } - - return set((float)x, (float)y, (float)z, (float)w); + final float t = m00 + m11 + m22; + + // we protect the division by s by ensuring that s>=1 + double x, y, z, w; + if (t >= 0) { // |w| >= .5 + double s = Math.sqrt(t + 1); // |s|>=1 ... + w = 0.5 * s; + s = 0.5 / s; // so this division isn't bad + x = (m21 - m12) * s; + y = (m02 - m20) * s; + z = (m10 - m01) * s; + } else if ((m00 > m11) && (m00 > m22)) { + double s = Math.sqrt(1.0 + m00 - m11 - m22); // |s|>=1 + x = s * 0.5; // |x| >= .5 + s = 0.5 / s; + y = (m10 + m01) * s; + z = (m02 + m20) * s; + w = (m21 - m12) * s; + } else if (m11 > m22) { + double s = Math.sqrt(1.0 + m11 - m00 - m22); // |s|>=1 + y = s * 0.5; // |y| >= .5 + s = 0.5 / s; + x = (m10 + m01) * s; + z = (m21 + m12) * s; + w = (m02 - m20) * s; + } else { + double s = Math.sqrt(1.0 + m22 - m00 - m11); // |s|>=1 + z = s * 0.5; // |z| >= .5 + s = 0.5 / s; + x = (m02 + m20) * s; + y = (m21 + m12) * s; + w = (m10 - m01) * s; + } + + return set((float)x, (float)y, (float)z, (float)w); } - - /** - * Spherical linear interpolation between this quaternion and the other - * quaternion, based on the alpha value in the range [0,1]. Taken - * from. Taken from Bones framework for JPCT, see http://www.aptalkarga.com/bones/ + + /** Spherical linear interpolation between this quaternion and the other quaternion, based on the alpha value in the range + * [0,1]. Taken from. Taken from Bones framework for JPCT, see http://www.aptalkarga.com/bones/ * @param end the end quaternion * @param alpha alpha in the range [0,1] - * @return this quaternion for chaining - */ - public Quaternion slerp(Quaternion end, float alpha) { - if (this.equals(end)) { - return this; - } - - float result = dot(end); - - if (result < 0.0) { - // Negate the second quaternion and the result of the dot product - end.mul(-1); - result = -result; - } - - // Set the first and second scale for the interpolation - float scale0 = 1 - alpha; - float scale1 = alpha; - - // Check if the angle between the 2 quaternions was big enough to - // warrant such calculations - if ((1 - result) > 0.1) {// Get the angle between the 2 quaternions, - // and then store the sin() of that angle - final double theta = Math.acos(result); - final double invSinTheta = 1f / Math.sin(theta); - - // Calculate the scale for q1 and q2, according to the angle and - // it's sine value - scale0 = (float) (Math.sin((1 - alpha) * theta) * invSinTheta); - scale1 = (float) (Math.sin((alpha * theta)) * invSinTheta); - } - - // Calculate the x, y, z and w values for the quaternion by using a - // special form of linear interpolation for quaternions. - final float x = (scale0 * this.x) + (scale1 * end.x); - final float y = (scale0 * this.y) + (scale1 * end.y); - final float z = (scale0 * this.z) + (scale1 * end.z); - final float w = (scale0 * this.w) + (scale1 * end.w); - set(x, y, z, w); - - // Return the interpolated quaternion - return this; + * @return this quaternion for chaining */ + public Quaternion slerp (Quaternion end, float alpha) { + if (this.equals(end)) { + return this; + } + + float result = dot(end); + + if (result < 0.0) { + // Negate the second quaternion and the result of the dot product + end.mul(-1); + result = -result; + } + + // Set the first and second scale for the interpolation + float scale0 = 1 - alpha; + float scale1 = alpha; + + // Check if the angle between the 2 quaternions was big enough to + // warrant such calculations + if ((1 - result) > 0.1) {// Get the angle between the 2 quaternions, + // and then store the sin() of that angle + final double theta = Math.acos(result); + final double invSinTheta = 1f / Math.sin(theta); + + // Calculate the scale for q1 and q2, according to the angle and + // it's sine value + scale0 = (float)(Math.sin((1 - alpha) * theta) * invSinTheta); + scale1 = (float)(Math.sin((alpha * theta)) * invSinTheta); + } + + // Calculate the x, y, z and w values for the quaternion by using a + // special form of linear interpolation for quaternions. + final float x = (scale0 * this.x) + (scale1 * end.x); + final float y = (scale0 * this.y) + (scale1 * end.y); + final float z = (scale0 * this.z) + (scale1 * end.z); + final float w = (scale0 * this.w) + (scale1 * end.w); + set(x, y, z, w); + + // Return the interpolated quaternion + return this; + } + + public boolean equals (final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Quaternion)) { + return false; + } + final Quaternion comp = (Quaternion)o; + return this.x == comp.x && this.y == comp.y && this.z == comp.z && this.w == comp.w; + + } + + /** Dot product between this and the other quaternion. + * @param other the other quaternion. + * @return this quaternion for chaining. */ + public float dot (Quaternion other) { + return x * other.x + y * other.y + z * other.z + w * other.w; + } + + /** Multiplies the components of this quaternion with the given scalar. + * @param scalar the scalar. + * @return this quaternion for chaining. */ + public Quaternion mul (float scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; } - - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Quaternion)) { - return false; - } - final Quaternion comp = (Quaternion) o; - return this.x == comp.x && this.y == comp.y && this.z == comp.z && this.w == comp.w; - - } - - /** - * Dot product between this and the other quaternion. - * @param other the other quaternion. - * @return this quaternion for chaining. - */ - public float dot(Quaternion other) { - return x * other.x + y * other.y + z * other.z + w * other.w; - } - - /** - * Multiplies the components of this quaternion with the - * given scalar. - * @param scalar the scalar. - * @return this quaternion for chaining. - */ - public Quaternion mul(float scalar) { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; - return this; - } } diff --git a/gdx/src/com/badlogic/gdx/math/Rectangle.java b/gdx/src/com/badlogic/gdx/math/Rectangle.java index 245aad17aaf..f625c63f570 100644 --- a/gdx/src/com/badlogic/gdx/math/Rectangle.java +++ b/gdx/src/com/badlogic/gdx/math/Rectangle.java @@ -15,30 +15,23 @@ import java.io.Serializable; -/** - * Encapsulates a 2D rectangle defined by it's bottom corner point and its extends in x (width) and y (height). - * @author badlogicgames@gmail.com - * - */ +/** 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 class Rectangle implements Serializable { private static final long serialVersionUID = 5733252015138115702L; public float x, y; public float width, height; - /** - * Constructs a new rectangle with all values set to zero - */ + /** Constructs a new rectangle with all values set to zero */ 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 - */ + * @param height The height */ public Rectangle (float x, float y, float width, float height) { this.x = x; this.y = y; @@ -46,10 +39,8 @@ public Rectangle (float x, float y, float width, float height) { this.height = height; } - /** - * Constructs a rectangle based on the given rectangle - * @param rect The rectangle - */ + /** Constructs a rectangle based on the given rectangle + * @param rect The rectangle */ public Rectangle (Rectangle rect) { x = rect.x; y = rect.y; @@ -57,70 +48,52 @@ public Rectangle (Rectangle rect) { height = rect.height; } - /** - * @return the x-coordinate of the bottom left corner - */ + /** @return the x-coordinate of the bottom left corner */ public float getX () { return x; } - /** - * Sets the x-coordinate of the bottom left corner - * @param x The x-coordinate - */ + /** Sets the x-coordinate of the bottom left corner + * @param x The x-coordinate */ public void setX (float x) { this.x = x; } - /** - * @return the y-coordinate of the bottom left corner - */ + /** @return the y-coordinate of the bottom left corner */ public float getY () { return y; } - /** - * Sets the y-coordinate of the bottom left corner - * @param y The y-coordinate - */ + /** Sets the y-coordinate of the bottom left corner + * @param y The y-coordinate */ public void setY (float y) { this.y = y; } - /** - * @return the width - */ + /** @return the width */ public float getWidth () { return width; } - /** - * Sets the width of this rectangle - * @param width The width - */ + /** Sets the width of this rectangle + * @param width The width */ public void setWidth (float width) { this.width = width; } - /** - * @return the height - */ + /** @return the height */ public float getHeight () { return height; } - /** - * Sets the height of this rectangle - * @param height The height - */ + /** Sets the height of this rectangle + * @param height The height */ public void setHeight (float height) { this.height = height; } - /** - * @param rectangle the other {@link Rectangle}. - * @return whether the other rectangle is contained in this rectangle. - */ + /** @param rectangle the other {@link Rectangle}. + * @return whether the other rectangle is contained in this rectangle. */ public boolean contains (Rectangle rectangle) { float xmin = rectangle.x; float xmax = xmin + rectangle.width; @@ -131,45 +104,36 @@ public boolean contains (Rectangle rectangle) { return ((xmin > x && xmin < x + width) || (xmax > x && xmax < x + width)) && ((ymin > y && ymin < y + height) || (ymax > y && ymax < y + height)); } - - /** - * @param rectangle the other {@link Rectangle} - * @return whether this rectangle overlaps the other rectangle. - */ - public boolean overlaps(Rectangle rectangle) { - return !(x > rectangle.x + rectangle.width || - x + width < rectangle.x || - y > rectangle.y + rectangle.height || - y + height < rectangle.y); + + /** @param rectangle the other {@link Rectangle} + * @return whether this rectangle overlaps the other rectangle. */ + public boolean overlaps (Rectangle rectangle) { + return !(x > rectangle.x + rectangle.width || x + width < rectangle.x || y > rectangle.y + rectangle.height || y + height < rectangle.y); } public void set (float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; - this.height = height; + this.height = height; } - /** - * @param x point x coordinate + /** @param x point x coordinate * @param y point y coordinate - * @return whether the point is contained in the rectangle - */ + * @return whether the point is contained in the rectangle */ public boolean contains (float x, float y) { return this.x < x && this.x + this.width > x && this.y < y && this.y + this.height > y; } - /** - * Sets the values of the given rectangle to this rectangle. - * @param rect the other rectangle - */ + /** Sets the values of the given rectangle to this rectangle. + * @param rect the other rectangle */ public void set (Rectangle rect) { this.x = rect.x; this.y = rect.y; this.width = rect.width; - this.height = rect.height; + this.height = rect.height; } - + public String toString () { return x + "," + y + "," + width + "," + height; } diff --git a/gdx/src/com/badlogic/gdx/math/Vector2.java b/gdx/src/com/badlogic/gdx/math/Vector2.java index 17400ce2864..2125e6be875 100644 --- a/gdx/src/com/badlogic/gdx/math/Vector2.java +++ b/gdx/src/com/badlogic/gdx/math/Vector2.java @@ -13,17 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.io.Serializable; - -/** - * Encapsulates a 2D vector. Allows chaining methods by returning a reference to itself - * @author badlogicgames@gmail.com - * - */ -public class Vector2 implements Serializable { +/** Encapsulates a 2D vector. Allows chaining methods by returning a reference to itself + * @author badlogicgames@gmail.com */ +public class Vector2 implements Serializable { private static final long serialVersionUID = 913902788239530931L; /** static temporary vector **/ @@ -34,90 +31,70 @@ public class Vector2 implements Serializable { /** the y-component of this vector **/ public float y; - /** - * Constructs a new vector at (0,0) - */ + /** Constructs a new vector at (0,0) */ public Vector2 () { } - /** - * Constructs a vector with the given components + /** Constructs a vector with the given components * @param x The x-component - * @param y The y-component - */ + * @param y The y-component */ public Vector2 (float x, float y) { this.x = x; this.y = y; } - /** - * Constructs a vector from the given vector - * @param v The vector - */ + /** Constructs a vector from the given vector + * @param v The vector */ public Vector2 (Vector2 v) { set(v); } - /** - * @return a copy of this vector - */ + /** @return a copy of this vector */ public Vector2 cpy () { return new Vector2(this); } - /** - * @return The euclidian length - */ + /** @return The euclidian length */ public float len () { return (float)Math.sqrt(x * x + y * y); } - /** - * @return The squared euclidian length - */ + /** @return The squared euclidian length */ public float len2 () { return x * x + y * y; } - /** - * Sets this vector from the given vector + /** Sets this vector from the given vector * @param v The vector - * @return This vector for chaining - */ + * @return This vector for chaining */ public Vector2 set (Vector2 v) { x = v.x; y = v.y; return this; } - /** - * Sets the components of this vector + /** Sets the components of this vector * @param x The x-component * @param y The y-component - * @return This vector for chaining - */ + * @return This vector for chaining */ public Vector2 set (float x, float y) { this.x = x; this.y = y; return this; } - /** - * Substracts the given vector from this vector. + /** Substracts the given vector from this vector. * @param v The vector - * @return This vector for chaining - */ + * @return This vector for chaining */ public Vector2 sub (Vector2 v) { x -= v.x; y -= v.y; return this; } - /** - * Normalizes this vector - * @return This vector for chaining - */ + /** Normalizes this vector + * @return This vector for chaining */ public Vector2 nor () { float len = len(); if (len != 0) { @@ -127,73 +104,59 @@ public Vector2 nor () { return this; } - /** - * Adds the given vector to this vector + /** Adds the given vector to this vector * @param v The vector - * @return This vector for chaining - */ + * @return This vector for chaining */ 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 - */ + * @return This vector for chaining */ 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 - */ + /** @param v The other vector + * @return The dot product between this and the other vector */ public float dot (Vector2 v) { return x * v.x + y * v.y; } - /** - * Multiplies this vector by a scalar + /** Multiplies this vector by a scalar * @param scalar The scalar - * @return This vector for chaining - */ + * @return This vector for chaining */ public Vector2 mul (float scalar) { x *= scalar; y *= scalar; return this; } - /** - * @param v The other vector - * @return the distance between this and the other vector - */ + /** @param v The other vector + * @return the distance between this and the other vector */ public float dst (Vector2 v) { final float x_d = v.x - x; final float y_d = v.y - y; return (float)Math.sqrt(x_d * x_d + y_d * y_d); } - /** - * @param x The x-component of the other vector + /** @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 - */ + * @return the distance between this and the other vector */ public float dst (float x, float y) { final float x_d = x - this.x; final float y_d = y - this.y; 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 - */ + /** @param v The other vector + * @return the squared distance between this and the other vector */ public float dst2 (Vector2 v) { final float x_d = v.x - x; final float y_d = v.y - y; @@ -204,31 +167,25 @@ public String toString () { return "[" + x + ":" + y + "]"; } - /** - * Substracts the other vector from this vector. + /** Substracts the other vector from this vector. * @param x The x-component of the other vector * @param y The y-component of the other vector - * @return This vector for chaining - */ + * @return This vector for chaining */ 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 () { return tmp.set(this); } - /** - * Multiplies this vector by the given matrix + /** Multiplies this vector by the given matrix * @param mat the matrix - * @return this vector - */ + * @return this vector */ 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]; @@ -236,65 +193,53 @@ public Vector2 mul (Matrix3 mat) { this.y = y; return this; } - - /** - * Calculates the 2D cross product between this - * and the given vector. + + /** Calculates the 2D cross product between this and the given vector. * @param v the other vector - * @return the cross product - */ - public float crs(Vector2 v) { + * @return the cross product */ + public float crs (Vector2 v) { return this.x * v.y - this.y * v.x; } - - /** - * Calculates the 2D cross product between this - * and the given vector. + + /** Calculates the 2D cross product between this and the given vector. * @param x the x-coordinate of the other vector * @param y the y-coordinate of the other vector - * @return the cross product - */ - public float crs(float x, float y) { - return this.x * y - this.y * x; + * @return the cross product */ + public float crs (float x, float y) { + return this.x * y - this.y * x; } - - /** - * @return the angle in degrees of this vector (point) relative to the x-axis. Angles are counter-clockwise and between 0 and 360. - */ - public float angle() { - float angle = (float)Math.atan2(y, x) * MathUtils.radiansToDegrees; - if(angle < 0) - angle += 360; - return angle; - } - - /** - * Rotates the Vector2 by the given angle, counter-clockwise. + + /** @return the angle in degrees of this vector (point) relative to the x-axis. Angles are counter-clockwise and between 0 and + * 360. */ + public float angle () { + float angle = (float)Math.atan2(y, x) * MathUtils.radiansToDegrees; + if (angle < 0) angle += 360; + return angle; + } + + /** Rotates the Vector2 by the given angle, counter-clockwise. * @param angle the angle in degrees - * @return the - */ - public Vector2 rotate(float angle) { - float rad = angle * MathUtils.degreesToRadians; - float cos = (float)Math.cos(rad); - float sin = (float)Math.sin(rad); - - float newX = this.x * cos - this.y * sin; - float newY = this.x * sin + this.y * cos; - - this.x = newX; - this.y = newY; - - return this; - } - - /** - * Linearly interpolates between this vector and the target vector by alpha which is in the range [0,1]. The result is stored + * @return the */ + public Vector2 rotate (float angle) { + float rad = angle * MathUtils.degreesToRadians; + float cos = (float)Math.cos(rad); + float sin = (float)Math.sin(rad); + + float newX = this.x * cos - this.y * sin; + float newY = this.x * sin + this.y * cos; + + this.x = newX; + this.y = newY; + + return this; + } + + /** 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. - */ + * @return This vector for chaining. */ public Vector2 lerp (Vector2 target, float alpha) { Vector2 r = this.mul(1.0f - alpha); r.add(target.tmp().mul(alpha)); diff --git a/gdx/src/com/badlogic/gdx/math/Vector3.java b/gdx/src/com/badlogic/gdx/math/Vector3.java index 2ec42cd94f9..3b8d7ddbc94 100644 --- a/gdx/src/com/badlogic/gdx/math/Vector3.java +++ b/gdx/src/com/badlogic/gdx/math/Vector3.java @@ -13,18 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math; import java.io.Serializable; import com.badlogic.gdx.utils.NumberUtils; -/** - * Encapsulates a 3D vector. Allows chaining operations by returning a reference to it self in all modification methods. - * - * @author badlogicgames@gmail.com +/** Encapsulates a 3D vector. Allows chaining operations by returning a reference to it self in all modification methods. * - */ + * @author badlogicgames@gmail.com */ public class Vector3 implements Serializable { private static final long serialVersionUID = 3840054589595372522L; /** the x-component of this vector **/ @@ -41,49 +39,39 @@ public class Vector3 implements Serializable { public static Vector3 Y = new Vector3(0, 1, 0); public static Vector3 Z = new Vector3(0, 0, 1); - /** - * Constructs a vector at (0,0,0) - */ + /** Constructs a vector at (0,0,0) */ public Vector3 () { } - /** - * Creates a vector with the given components + /** Creates a vector with the given components * * @param x The x-component * @param y The y-component - * @param z The z-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 + /** Creates a vector from the given vector * - * @param vector The 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. + /** Creates a vector from the given array. The array must have at least 3 elements. * - * @param values The array - */ + * @param values The array */ public Vector3 (float[] values) { this.set(values[0], values[1], values[2]); } - /** - * Sets the vector to the given components + /** 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 - */ + * @return this vector for chaining */ public Vector3 set (float x, float y, float z) { this.x = x; this.y = y; @@ -91,169 +79,133 @@ public Vector3 set (float x, float y, float z) { return this; } - /** - * Sets the components of the given vector + /** Sets the components of the given vector * * @param vector The vector - * @return This vector for chaining - */ + * @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 + /** Sets the components from the array. The array must have at least 3 elements * * @param values The array - * @return this vector for chaining - */ + * @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 - */ + /** @return a copy of this vector */ public Vector3 cpy () { return new Vector3(this); } - /** - * NEVER EVER SAVE THIS REFERENCE! + /** NEVER EVER SAVE THIS REFERENCE! * - * @return a temporary copy of this vector - */ + * @return a temporary copy of this vector */ public Vector3 tmp () { return tmp.set(this); } - /** - * NEVER EVER SAVE THIS REFERENCE! + /** NEVER EVER SAVE THIS REFERENCE! * - * @return a temporary copy of this vector - */ + * @return a temporary copy of this vector */ public Vector3 tmp2 () { return tmp2.set(this); } - /** - * NEVER EVER SAVE THIS REFERENCE! + /** NEVER EVER SAVE THIS REFERENCE! * - * @return a temporary copy of this vector - */ + * @return a temporary copy of this vector */ Vector3 tmp3 () { return tmp3.set(this); } - /** - * Adds the given vector to this vector + /** Adds the given vector to this vector * * @param vector The other vector - * @return This vector for chaining - */ + * @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 + /** 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. - */ + * @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. + /** Adds the given value to all three components of the vector. * * @param values The value - * @return This vector for chaining - */ + * @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 + /** Subtracts the given vector from this vector * @param a_vec The other vector - * @return This vector for chaining - */ + * @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. + /** 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 - */ + * @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 + /** Subtracts the given value from all components of this vector * * @param value The value - * @return This vector for chaining - */ + * @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 + /** Multiplies all components of this vector by the given value * * @param value The value - * @return This vector for chaining - */ + * @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 + /** Divides all components of this vector by the given value * * @param value The value - * @return This vector for chaining - */ + * @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 - */ + /** @return The euclidian length */ public float len () { return (float)Math.sqrt(x * x + y * y + z * z); } - /** - * @return The squared euclidian length - */ + /** @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 - */ + /** @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 - */ + /** @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; @@ -266,53 +218,43 @@ public float dst (Vector3 vector) { return (float)Math.sqrt(a + b + c); } - /** - * Normalizes this vector to unit length + /** Normalizes this vector to unit length * - * @return This vector for chaining - */ + * @return This vector for chaining */ public Vector3 nor () { float len = this.len(); - if(len == 0) { + if (len == 0) { return this; } else { return this.div(len); } } - /** - * @param vector The other vector - * @return The dot product between this and the other vector - */ + /** @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. + /** Sets this vector to the cross product between it and the other vector. * @param vector The other vector - * @return This vector for chaining - */ + * @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. + /** 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 - */ + * @return This vector for chaining */ public Vector3 crs (float x, float y, float z) { return this.set(this.y * z - this.z * y, this.z * x - this.x * z, this.x * y - this.y * x); } - /** - * Multiplies the vector by the given matrix. + /** Multiplies the vector by the given matrix. * @param matrix The matrix - * @return This vector for chaining - */ + * @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 @@ -320,13 +262,11 @@ public Vector3 mul (Matrix4 matrix) { * 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 + /** 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 - */ + * @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]; @@ -335,54 +275,44 @@ public Vector3 prj (Matrix4 matrix) { / 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. + /** 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 - */ + * @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 - */ + /** @return Wether this vector is a unit length vector */ public boolean isUnit () { return this.len() == 1; } - /** - * @return Wether this vector is a zero vector - */ + /** @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 + /** 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. - */ + * @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 + /** 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. - */ + * @return This vector for chaining. */ public Vector3 slerp (Vector3 target, float alpha) { float dot = dot(target); if (dot > 0.99995 || dot < 0.9995) { @@ -401,31 +331,25 @@ public Vector3 slerp (Vector3 target, float alpha) { return this.mul((float)Math.cos(theta)).add(v2.mul((float)Math.sin(theta))).nor(); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ public String toString () { return x + "," + y + "," + z; } - /** - * Returns the dot product between this and the given vector. + /** 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 - */ + * @return The dot product */ public float dot (float x, float y, float z) { return this.x * x + this.y * y + this.z * z; } - /** - * Returns the squared distance between this point and the given point + /** Returns the squared distance between this point and the given point * * @param point The other point - * @return The squared distance - */ + * @return The squared distance */ public float dst2 (Vector3 point) { float a = point.x - x; @@ -439,14 +363,12 @@ public float dst2 (Vector3 point) { return a + b + c; } - /** - * Returns the squared distance between this point and the given point + /** Returns the squared distance between this point and the given point * * @param x The x-component of the other point * @param y The y-component of the other point * @param z The z-component of the other point - * @return The squared distance - */ + * @return The squared distance */ public float dst2 (float x, float y, float z) { float a = x - this.x; float b = y - this.y; @@ -463,10 +385,9 @@ public float dst (float x, float y, float z) { return (float)Math.sqrt(dst2(x, y, z)); } - /** - * {@inheritDoc} - */ - @Override public int hashCode () { + /** {@inheritDoc} */ + @Override + public int hashCode () { final int prime = 31; int result = 1; result = prime * result + NumberUtils.floatToIntBits(x); @@ -475,10 +396,9 @@ public float dst (float x, float y, float z) { return result; } - /** - * {@inheritDoc} - */ - @Override public boolean equals (Object obj) { + /** {@inheritDoc} */ + @Override + public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @@ -489,17 +409,15 @@ public float dst (float x, float y, float z) { return true; } - /** - * Scales the vector components by the given scalars. + /** Scales the vector components by the given scalars. * * @param scalarX * @param scalarY - * @param scalarZ - */ + * @param scalarZ */ public Vector3 scale (float scalarX, float scalarY, float scalarZ) { x *= scalarX; y *= scalarY; z *= scalarZ; return this; - } + } } diff --git a/gdx/src/com/badlogic/gdx/math/WindowedMean.java b/gdx/src/com/badlogic/gdx/math/WindowedMean.java index 7c90e704db4..f13fe765fce 100644 --- a/gdx/src/com/badlogic/gdx/math/WindowedMean.java +++ b/gdx/src/com/badlogic/gdx/math/WindowedMean.java @@ -13,16 +13,14 @@ * 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 +/** 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 - * - */ + * @author badlogicgames@gmail.com */ public final class WindowedMean { float values[]; int added_values = 0; @@ -30,26 +28,20 @@ public final class WindowedMean { 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 + /** 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 - */ + * @param window_size size of the sample window */ public WindowedMean (int window_size) { values = new float[window_size]; } - /** - * @return wheter the value returned will be meaningfull - */ + /** @return wheter the value returned will be meaningfull */ 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 () { added_values = 0; last_value = 0; @@ -58,11 +50,9 @@ public void clear () { 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 - */ + * @param value The value to add */ public void addValue (float value) { added_values++; values[last_value++] = value; @@ -70,11 +60,9 @@ public void addValue (float value) { dirty = true; } - /** - * returns the mean of the samples added to this instance. only returns meaningfull results when at least window_size samples + /** 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 - */ + * @return the mean */ public float getMean () { if (hasEnoughData()) { if (dirty == true) { @@ -90,23 +78,17 @@ public float getMean () { return 0; } - /** - * @return the oldest value in the window - */ + /** @return the oldest value in the window */ public float getOldest () { return last_value == values.length - 1 ? values[0] : values[last_value + 1]; } - /** - * @return the value last added - */ + /** @return the value last added */ public float getLatest () { return values[last_value - 1 == -1 ? values.length - 1 : last_value - 1]; } - /** - * @return The standard deviation - */ + /** @return The standard deviation */ public float standardDeviation () { if (!hasEnoughData()) return 0; diff --git a/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java b/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java index 9e9a516abbc..60bc3f4f6db 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java +++ b/gdx/src/com/badlogic/gdx/math/collision/BoundingBox.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import java.io.Serializable; @@ -21,13 +22,10 @@ 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 +/** 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 - * - */ + * @author badlogicgames@gmail.com */ public class BoundingBox implements Serializable { private static final long serialVersionUID = -1286036817192127343L; final Vector3 crn[] = new Vector3[8]; @@ -37,9 +35,7 @@ public class BoundingBox implements Serializable { final Vector3 dim = new Vector3(); boolean crn_dirty = true; - /** - * @return the center of the bounding box - */ + /** @return the center of the bounding box */ public Vector3 getCenter () { return cnt; } @@ -58,38 +54,28 @@ protected void updateCorners () { crn_dirty = false; } - /** - * @return the corners of this bounding box - */ + /** @return the corners of this bounding box */ public Vector3[] getCorners () { updateCorners(); return crn; } - /** - * @return The dimensions of this bounding box on all three axis - */ + /** @return The dimensions of this bounding box on all three axis */ public Vector3 getDimensions () { return dim; } - /** - * @return The minimum vector - */ + /** @return The minimum vector */ public Vector3 getMin () { return min; } - /** - * @return The maximum vector - */ + /** @return The maximum vector */ public synchronized Vector3 getMax () { return max; } - /** - * Constructs a new bounding box with the minimum and maximum vector set to zeros. - */ + /** 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++) @@ -97,11 +83,9 @@ public BoundingBox () { clr(); } - /** - * Constructs a new bounding box from the given bounding box. + /** Constructs a new bounding box from the given bounding box. * - * @param bounds The bounding box to copy - */ + * @param bounds The bounding box to copy */ public BoundingBox (BoundingBox bounds) { crn_dirty = true; for (int l_idx = 0; l_idx < 8; l_idx++) @@ -109,12 +93,10 @@ public BoundingBox (BoundingBox bounds) { this.set(bounds); } - /** - * Constructs the new bounding box using the given minimum and maximum vector. + /** Constructs the new bounding box using the given minimum and maximum vector. * * @param minimum The minimum vector - * @param maximum The maximum 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++) @@ -122,24 +104,20 @@ public BoundingBox (Vector3 minimum, Vector3 maximum) { this.set(minimum, maximum); } - /** - * Sets the given bounding box. + /** Sets the given bounding box. * * @param bounds The bounds. - * @return This bounding box for chaining. - */ + * @return This bounding box for chaining. */ public BoundingBox set (BoundingBox bounds) { crn_dirty = true; return this.set(bounds.min, bounds.max); } - /** - * Sets the given minimum and maximum vector. + /** Sets the given minimum and maximum vector. * * @param minimum The minimum vector * @param maximum The maximum vector - * @return This bounding box for chaining. - */ + * @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); @@ -151,12 +129,10 @@ public BoundingBox set (Vector3 minimum, Vector3 maximum) { return this; } - /** - * Sets the bounding box minimum and maximum vector from the given points. + /** Sets the bounding box minimum and maximum vector from the given points. * * @param points The points. - * @return This bounding box for chaining. - */ + * @return This bounding box for chaining. */ public BoundingBox set (Vector3[] points) { this.inf(); for (Vector3 l_point : points) @@ -165,12 +141,10 @@ public BoundingBox set (Vector3[] points) { return this; } - /** - * Sets the bounding box minimum and maximum vector from the given points. + /** Sets the bounding box minimum and maximum vector from the given points. * * @param points The points. - * @return This bounding box for chaining. - */ + * @return This bounding box for chaining. */ public BoundingBox set (List points) { this.inf(); for (Vector3 l_point : points) @@ -179,11 +153,9 @@ public BoundingBox set (List points) { return this; } - /** - * Sets the minimum and maximum vector to positive and negative infinity. + /** Sets the minimum and maximum vector to positive and negative infinity. * - * @return This bounding box for chaining. - */ + * @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); @@ -193,56 +165,46 @@ public BoundingBox inf () { return this; } - /** - * Extends the bounding box to incorporate the given {@link Vector3}. + /** Extends the bounding box to incorporate the given {@link Vector3}. * * @param point The vector - * @return This bounding box for chaining. - */ + * @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 + /** Sets the minimum and maximum vector to zeros * - * @return This bounding box for chaining. - */ + * @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. + /** 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 - */ + * @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. + /** Extends this bounding box by the given bounding box. * * @param a_bounds The bounding box - * @return This bounding box for chaining. - */ + * @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 + /** 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. - */ + * @return This bounding box for chaining. */ public BoundingBox mul (Matrix4 matrix) { updateCorners(); this.inf(); @@ -255,11 +217,9 @@ public BoundingBox mul (Matrix4 matrix) { return this.set(min, max); } - /** - * Returns wheter the given bounding box is contained in this bounding box. + /** 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 - */ + * @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; @@ -271,11 +231,9 @@ public boolean contains (BoundingBox bounds) { return true; } - /** - * Returns wheter the given vector is contained in this bounding box. + /** Returns wheter the given vector is contained in this bounding box. * @param v The vector - * @return Wheter the vector is contained or not. - */ + * @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; @@ -291,14 +249,12 @@ public String toString () { return "[" + min + "|" + max + "]"; } - /** - * Extends the bounding box by the given vector. + /** 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. - */ + * @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))); diff --git a/gdx/src/com/badlogic/gdx/math/collision/Ray.java b/gdx/src/com/badlogic/gdx/math/collision/Ray.java index ca2d271de61..2fef259642c 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/Ray.java +++ b/gdx/src/com/badlogic/gdx/math/collision/Ray.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import java.io.Serializable; @@ -20,53 +21,42 @@ import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; -/** - * Encapsulates a ray having a starting position and a unit length direction. - * - * @author badlogicgames@gmail.com +/** Encapsulates a ray having a starting position and a unit length direction. * - */ -public class Ray implements Serializable { + * @author badlogicgames@gmail.com */ +public class Ray implements Serializable { private static final long serialVersionUID = -620692054835390878L; public final Vector3 origin = 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 - */ + * @param direction The direction */ public Ray (Vector3 origin, Vector3 direction) { this.origin.set(origin); this.direction.set(direction).nor(); } - /** - * @return a copy of this ray. - */ + /** @return a copy of this ray. */ 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 - */ + * @return The end point */ public Vector3 getEndPoint (float distance) { return new Vector3(origin).add(direction.tmp().mul(distance)); } 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 - * @return This ray for chaining. - */ + * @return This ray for chaining. */ public Ray mul (Matrix4 matrix) { tmp.set(origin).add(direction); tmp.mul(matrix); @@ -75,28 +65,23 @@ public Ray mul (Matrix4 matrix) { return this; } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ 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 - */ + * @return this ray for chaining */ 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 @@ -104,20 +89,17 @@ public Ray set (Vector3 origin, Vector3 direction) { * @param dx The x-component of the direction * @param dy The y-component of the direction * @param dz The z-component of the direction - * @return this ray for chaining - */ + * @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); return this; } - /** - * Sets the starting position and direction from the given ray + /** Sets the starting position and direction from the given ray * * @param ray The ray - * @return This ray for chaining - */ + * @return This ray for chaining */ public Ray set (Ray ray) { this.origin.set(ray.origin); diff --git a/gdx/src/com/badlogic/gdx/math/collision/Segment.java b/gdx/src/com/badlogic/gdx/math/collision/Segment.java index 27411364e44..8928e176291 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/Segment.java +++ b/gdx/src/com/badlogic/gdx/math/collision/Segment.java @@ -13,19 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import java.io.Serializable; import com.badlogic.gdx.math.Vector3; -/** - * A Segment is a line in 3-space having a staring and an ending position. - * - * @author mzechner +/** A Segment is a line in 3-space having a staring and an ending position. * - */ -public class Segment implements Serializable { + * @author mzechner */ +public class Segment implements Serializable { private static final long serialVersionUID = 2739667069736519602L; /** the starting position **/ @@ -34,26 +32,22 @@ public class Segment implements Serializable { /** the ending position **/ 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 - */ + * @param b the second point */ public Segment (Vector3 a, Vector3 b) { this.a.set(a); this.b.set(b); } - /** - * Constructs a new Segment from the two points given. + /** Constructs a new Segment from the two points given. * @param aX the x-coordinate of the first point * @param aY the y-coordinate of the first point * @param aZ the z-coordinate of the first point * @param bX the x-coordinate of the second point * @param bY the y-coordinate of the second point - * @param bZ the z-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); diff --git a/gdx/src/com/badlogic/gdx/math/collision/Sphere.java b/gdx/src/com/badlogic/gdx/math/collision/Sphere.java index 2af17892957..3b790d29c26 100644 --- a/gdx/src/com/badlogic/gdx/math/collision/Sphere.java +++ b/gdx/src/com/badlogic/gdx/math/collision/Sphere.java @@ -13,40 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.math.collision; import java.io.Serializable; import com.badlogic.gdx.math.Vector3; -/** - * Encapsulates a 3D sphere with a center and a radius - * - * @author badlogicgames@gmail.com +/** Encapsulates a 3D sphere with a center and a radius * - */ -public class Sphere implements Serializable { + * @author badlogicgames@gmail.com */ +public class Sphere implements Serializable { private static final long serialVersionUID = -6487336868908521596L; /** 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 + /** Constructs a sphere with the given center and radius * @param center The center - * @param radius The radius - */ + * @param radius The radius */ public Sphere (Vector3 center, float radius) { this.center = new Vector3(center); this.radius = radius; } - - /** - * @param sphere the other sphere - * @return whether this and the other sphere overlap - */ - public boolean overlaps(Sphere sphere) { + + /** @param sphere the other sphere + * @return whether this and the other sphere overlap */ + public boolean overlaps (Sphere sphere) { return center.dst2(sphere.center) < radius * radius + sphere.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 afbb8f336d4..6a37cd97e48 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Body.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Body.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import java.util.ArrayList; @@ -20,11 +21,8 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; -/** - * A rigid body. These are created via World.CreateBody. - * @author mzechner - * - */ +/** A rigid body. These are created via World.CreateBody. + * @author mzechner */ public class Body { /** the address of the body **/ protected long addr; @@ -44,37 +42,32 @@ public class Body { /** user data **/ private Object userData; - /** - * Constructs a new body with the given address + /** Constructs a new body with the given address * @param world the world - * @param addr the address - */ + * @param addr the address */ protected Body (World world, long addr) { this.world = world; - this.addr = addr; + this.addr = addr; } - - /** - * Resets this body after fetching it from the {@link World#freeBodies} Pool. - */ - protected void reset(long addr) { + + /** Resets this body after fetching it from the {@link World#freeBodies} Pool. */ + protected void reset (long addr) { this.addr = addr; this.userData = null; - for(int i = 0; i < fixtures.size(); i++) this.world.freeFixtures.free(fixtures.get(i)); + for (int i = 0; i < fixtures.size(); i++) + this.world.freeFixtures.free(fixtures.get(i)); fixtures.clear(); this.joints.clear(); } - /** - * Creates a fixture and attach it to this body. Use this function if you need to set some fixture parameters, like friction. + /** 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. - */ + * @warning This function is locked during callbacks. */ public Fixture createFixture (FixtureDef def) { - long fixtureAddr = jniCreateFixture(addr, def.shape.addr, def.friction, def.restitution, def.density, - def.isSensor, def.filter.categoryBits, def.filter.maskBits, def.filter.groupIndex); + long fixtureAddr = jniCreateFixture(addr, def.shape.addr, def.friction, def.restitution, def.density, def.isSensor, + def.filter.categoryBits, def.filter.maskBits, def.filter.groupIndex); Fixture fixture = this.world.freeFixtures.obtain(); fixture.reset(this, fixtureAddr); this.world.fixtures.put(fixture.addr, fixture); @@ -85,14 +78,12 @@ public Fixture createFixture (FixtureDef def) { 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 + /** 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) { long fixtureAddr = jniCreateFixture(addr, shape.addr, density); Fixture fixture = this.world.freeFixtures.obtain(); @@ -104,13 +95,11 @@ public Fixture createFixture (Shape shape, 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. + /** 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); this.world.fixtures.remove(fixture.addr); @@ -120,33 +109,26 @@ public void destroyFixture (Fixture 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 + /** 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. - */ + * @param angle the world rotation in radians. */ public void setTransform (Vector2 position, float angle) { jniSetTransform(addr, position.x, position.y, angle); } - - /** - * Set the position of the body's origin and rotation. This breaks any contacts and wakes the other bodies. Manipulating a + + /** 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 x the world position on the x-axis * @param y the world position on the y-axis - * @param angle the world rotation in radians. - */ - public void setTransform(float x, float y, float angle) { + * @param angle the world rotation in radians. */ + public void setTransform (float x, float y, float angle) { jniSetTransform(addr, x, y, angle); } - private native void jniSetTransform (long addr, float positionX, float positionY, float angle); - /** - * Get the body transform for the body's origin. FIXME - */ + /** Get the body transform for the body's origin. FIXME */ private final Transform transform = new Transform(); public Transform getTransform () { @@ -158,10 +140,8 @@ public Transform getTransform () { private final Vector2 position = new Vector2(); - /** - * Get the world body origin position. - * @return the world position of the body's origin. - */ + /** Get the world body origin position. + * @return the world position of the body's origin. */ public Vector2 getPosition () { jniGetPosition(addr, tmp); position.x = tmp[0]; @@ -171,19 +151,15 @@ public Vector2 getPosition () { private native void jniGetPosition (long addr, float[] position); - /** - * Get the angle in radians. - * @return the current world rotation angle in radians. - */ + /** Get the angle in radians. + * @return the current world rotation angle in radians. */ public float getAngle () { return jniGetAngle(addr); } private native float jniGetAngle (long addr); - /** - * Get the world position of the center of mass. - */ + /** Get the world position of the center of mass. */ private final Vector2 worldCenter = new Vector2(); public Vector2 getWorldCenter () { @@ -195,9 +171,7 @@ public Vector2 getWorldCenter () { private native void jniGetWorldCenter (long addr, float[] worldCenter); - /** - * Get the local position of the center of mass. - */ + /** Get the local position of the center of mass. */ private final Vector2 localCenter = new Vector2(); public Vector2 getLocalCenter () { @@ -209,25 +183,19 @@ public Vector2 getLocalCenter () { 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); } - - /** - * Set the linear velocity of the center of mass. - */ + + /** Set the linear velocity of the center of mass. */ public void setLinearVelocity (float vX, float vY) { jniSetLinearVelocity(addr, vX, vY); } private native void jniSetLinearVelocity (long addr, float x, float y); - /** - * Get the linear velocity of the center of mass. - */ + /** Get the linear velocity of the center of mass. */ private final Vector2 linearVelocity = new Vector2(); public Vector2 getLinearVelocity () { @@ -239,107 +207,87 @@ public Vector2 getLinearVelocity () { private native void jniGetLinearVelocity (long addr, float[] tmpLinearVelocity); - /** - * Set the angular velocity. - */ + /** Set the angular velocity. */ public void setAngularVelocity (float omega) { jniSetAngularVelocity(addr, omega); } private native void jniSetAngularVelocity (long addr, float omega); - /** - * Get the angular velocity. - */ + /** Get the angular velocity. */ public float getAngularVelocity () { return jniGetAngularVelocity(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 + /** 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. - */ + * @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); } - - /** - * 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 + + /** 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 forceX the world force vector on x, usually in Newtons (N). * @param forceY the world force vector on y, usually in Newtons (N). * @param pointX the world position of the point of application on x. - * @param pointY the world position of the point of application on y. - */ + * @param pointY the world position of the point of application on y. */ public void applyForce (float forceX, float forceY, float pointX, float pointY) { jniApplyForce(addr, forceX, forceY, pointX, 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 + /** 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. - */ + * @param torque about the z-axis (out of the screen), usually in N-m. */ public void applyTorque (float torque) { jniApplyTorque(addr, 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 + /** 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. - */ + * @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); } - - /** - * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of + + /** 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 impulseX the world impulse vector on the x-axis, usually in N-seconds or kg-m/s. * @param impulseY the world impulse vector on the y-axis, usually in N-seconds or kg-m/s. * @param pointX the world position of the point of application on the x-axis. - * @param pointY the world position of the point of application on the y-axis. - */ - public void applyLinearImpulse(float impulseX, float impulseY, float pointX, float pointY) { + * @param pointY the world position of the point of application on the y-axis. */ + public void applyLinearImpulse (float impulseX, float impulseY, float pointX, float pointY) { jniApplyLinearImpulse(addr, impulseX, impulseY, pointX, 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 - */ + /** Apply an angular impulse. + * @param impulse the angular impulse in units of kg*m*m/s */ public void applyAngularImpulse (float impulse) { jniApplyAngularImpulse(addr, impulse); } private native void jniApplyAngularImpulse (long addr, float impulse); - /** - * Get the total mass of the body. - * @return the mass, usually in kilograms (kg). - */ + /** Get the total mass of the body. + * @return the mass, usually in kilograms (kg). */ public float getMass () { return jniGetMass(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. - */ + /** 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); } @@ -348,10 +296,8 @@ public float getInertia () { private final MassData massData = new MassData(); - /** - * Get the mass data of the body. - * @return a struct containing the mass, inertia and center of the body. - */ + /** Get the mass data of the body. + * @return a struct containing the mass, inertia and center of the body. */ public MassData getMassData () { jniGetMassData(addr, tmp); massData.mass = tmp[0]; @@ -363,21 +309,17 @@ public MassData getMassData () { 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. + /** 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 data the mass properties. - */ + * @param data the mass properties. */ 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); - /** - * 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); } @@ -386,11 +328,9 @@ public void resetMassData () { private final Vector2 localPoint = new Vector2(); - /** - * 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. - */ + * @return the same point expressed in world coordinates. */ public Vector2 getWorldPoint (Vector2 localPoint) { jniGetWorldPoint(addr, localPoint.x, localPoint.y, tmp); this.localPoint.x = tmp[0]; @@ -402,11 +342,9 @@ public Vector2 getWorldPoint (Vector2 localPoint) { private final Vector2 worldVector = new Vector2(); - /** - * 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. - */ + * @return the same vector expressed in world coordinates. */ public Vector2 getWorldVector (Vector2 localVector) { jniGetWorldVector(addr, localVector.x, localVector.y, tmp); worldVector.x = tmp[0]; @@ -418,11 +356,9 @@ public Vector2 getWorldVector (Vector2 localVector) { public final Vector2 localPoint2 = new Vector2(); - /** - * 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 worldPoint a point in world coordinates. - * @return the corresponding local point relative to the body's origin. - */ + * @return the corresponding local point relative to the body's origin. */ public Vector2 getLocalPoint (Vector2 worldPoint) { jniGetLocalPoint(addr, worldPoint.x, worldPoint.y, tmp); localPoint2.x = tmp[0]; @@ -434,11 +370,9 @@ public Vector2 getLocalPoint (Vector2 worldPoint) { public final Vector2 localVector = new Vector2(); - /** - * Gets a local vector given a world vector. + /** Gets a local vector given a world vector. * @param worldVector a vector in world coordinates. - * @return the corresponding local vector. - */ + * @return the corresponding local vector. */ public Vector2 getLocalVector (Vector2 worldVector) { jniGetLocalVector(addr, worldVector.x, worldVector.y, tmp); localVector.x = tmp[0]; @@ -450,11 +384,9 @@ public Vector2 getLocalVector (Vector2 worldVector) { public final Vector2 linVelWorld = new Vector2(); - /** - * 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 worldPoint a point in world coordinates. - * @return the world velocity of a point. - */ + * @return the world velocity of a point. */ public Vector2 getLinearVelocityFromWorldPoint (Vector2 worldPoint) { jniGetLinearVelocityFromWorldPoint(addr, worldPoint.x, worldPoint.y, tmp); linVelWorld.x = tmp[0]; @@ -466,11 +398,9 @@ public Vector2 getLinearVelocityFromWorldPoint (Vector2 worldPoint) { public final Vector2 linVelLoc = new Vector2(); - /** - * Get the world velocity of a local point. + /** Get the world velocity of a local point. * @param localPoint a point in local coordinates. - * @return the world velocity of a point. - */ + * @return the world velocity of a point. */ public Vector2 getLinearVelocityFromLocalPoint (Vector2 localPoint) { jniGetLinearVelocityFromLocalPoint(addr, localPoint.x, localPoint.y, tmp); linVelLoc.x = tmp[0]; @@ -480,54 +410,42 @@ public Vector2 getLinearVelocityFromLocalPoint (Vector2 localPoint) { 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); } 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); } private native void jniSetLinearDamping (long addr, float linearDamping); - /** - * Get the angular damping of the body. - */ + /** Get the angular damping of the body. */ public float getAngularDamping () { return jniGetAngularDamping(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); } 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()); } private native void jniSetType (long addr, int type); - /** - * Get the type of this body. - */ + /** Get the type of this body. */ public BodyType getType () { int type = jniGetType(addr); if (type == 0) return BodyType.StaticBody; @@ -538,144 +456,112 @@ public BodyType getType () { private native int jniGetType (long addr); - /** - * Should this body be treated like a bullet for continuous collision detection? - */ + /** Should this body be treated like a bullet for continuous collision detection? */ public void setBullet (boolean flag) { jniSetBullet(addr, 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); } 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); } 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); } private native boolean jniIsSleepingAllowed (long addr); - /** - * 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. - */ + /** 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); } private native void jniSetAwake (long addr, boolean flag); - /** - * Get the sleeping state of this body. - * @return true if the body is sleeping. - */ + /** Get the sleeping state of this body. + * @return true if the body is sleeping. */ public boolean isAwake () { return jniIsAwake(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 + /** 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. - */ + * body is still owned by a b2World object and remains in the body list. */ public void setActive (boolean flag) { jniSetActive(addr, 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); } 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); } private native void jniSetFixedRotation (long addr, boolean flag); - /** - * Does this body have fixed rotation? - */ + /** Does this body have fixed rotation? */ public boolean isFixedRotation () { return jniIsFixedRotation(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 () { 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 () { return joints; } - /** - * Get the list of all contacts attached to this body. + /** 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! - */ + * modify the returned list! */ // ArrayList getContactList() // { // return contacts; // } - /** - * Get the parent world of this body. - */ + /** Get the parent world of this body. */ public World getWorld () { return world; } - /** - * Get the user data - */ + /** Get the user data */ public Object getUserData () { return userData; } - /** - * Set the user data - */ + /** Set the user data */ 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 df4a894c2da..f603946df23 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/BodyDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/BodyDef.java @@ -13,22 +13,18 @@ * 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 +/** 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 - * - */ + * @author mzechner */ 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); @@ -43,14 +39,10 @@ public int getValue () { } }; - /** - * 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. **/ @@ -62,21 +54,15 @@ public int getValue () { /** 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? **/ @@ -85,11 +71,9 @@ public int getValue () { /** 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 + /** 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. - **/ + * @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 3eae225eeb3..1a91c5062cd 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import java.util.Iterator; @@ -53,9 +54,7 @@ public Box2DDebugRenderer () { 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); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java b/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java index 8a0b49b0ae7..e52b02b4d0e 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/CircleShape.java @@ -13,15 +13,13 @@ * 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 circle shape. - * @author mzechner - * - */ +/** A circle shape. + * @author mzechner */ public class CircleShape extends Shape { public CircleShape () { addr = newCircleShape(); @@ -33,16 +31,13 @@ protected CircleShape (long addr) { this.addr = addr; } - /** - * {@inheritDoc} - */ - @Override public Type getType () { + /** {@inheritDoc} */ + @Override + public Type getType () { return Type.Circle; } - /** - * Returns the position of the shape - */ + /** Returns the position of the shape */ private final float[] tmp = new float[2]; private final Vector2 position = new Vector2(); @@ -55,9 +50,7 @@ public Vector2 getPosition () { private native void jniGetPosition (long addr, float[] position); - /** - * Sets the position of the shape - */ + /** Sets the position of the shape */ public void setPosition (Vector2 position) { jniSetPosition(addr, position.x, position.y); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java b/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java index f35625a22f7..e2550c657c0 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Contact.java @@ -13,16 +13,14 @@ * 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 +/** 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 - * - */ + * @author mzechner */ public class Contact { /** the address **/ protected long addr; @@ -38,9 +36,7 @@ protected Contact (World world, long addr) { this.world = world; } - /** - * Get the world manifold. - */ + /** Get the world manifold. */ private final float[] tmp = new float[6]; public WorldManifold getWorldManifold () { @@ -65,37 +61,29 @@ public boolean isTouching () { 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); } private native void jniSetEnabled (long addr, boolean flag); - /** - * Has this contact been disabled? - */ + /** Has this contact been disabled? */ public boolean isEnabled () { return jniIsEnabled(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); - /** - * Get the second fixture in this contact. - */ + /** Get the second fixture in this contact. */ public Fixture getFixtureB () { return world.fixtures.get(jniGetFixtureB(addr)); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java b/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java index 3e5e5a5851f..9c4414150bb 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/ContactFilter.java @@ -13,14 +13,12 @@ * 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 +/** 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 - * - */ + * @author mzechner */ public interface ContactFilter { boolean shouldCollide (Fixture fixtureA, Fixture fixtureB); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/ContactImpulse.java b/gdx/src/com/badlogic/gdx/physics/box2d/ContactImpulse.java index ca7493cd5e6..a8858cb4195 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/ContactImpulse.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/ContactImpulse.java @@ -1,6 +1,5 @@ -package com.badlogic.gdx.physics.box2d; -import com.badlogic.gdx.math.Vector2; +package com.badlogic.gdx.physics.box2d; public class ContactImpulse { final World world; @@ -8,23 +7,23 @@ public class ContactImpulse { float[] tmp = new float[2]; final float[] normalImpulses = new float[2]; final float[] tangentImpulses = new float[2]; - - protected ContactImpulse(World world, long addr) { + + protected ContactImpulse (World world, long addr) { this.world = world; this.addr = addr; } - - public float[] getNormalImpulses() { - jniGetNormalImpulses(addr, normalImpulses); + + public float[] getNormalImpulses () { + jniGetNormalImpulses(addr, normalImpulses); return normalImpulses; } - - private native void jniGetNormalImpulses(long addr, float[] values); - - public float[] getTangentImpulses() { - jniGetTangentImpulses(addr, tangentImpulses); + + private native void jniGetNormalImpulses (long addr, float[] values); + + public float[] getTangentImpulses () { + jniGetTangentImpulses(addr, tangentImpulses); return tangentImpulses; } - - private native void jniGetTangentImpulses(long addr, float[] values); + + private native void jniGetTangentImpulses (long addr, float[] values); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java b/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java index d9e6e2f673a..f7e813f0690 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/ContactListener.java @@ -13,37 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; public interface ContactListener { - /** - * Called when two fixtures begin to touch. - */ + /** Called when two fixtures begin to touch. */ public void beginContact (Contact contact); - /** - * Called when two fixtures cease to touch. - */ + /** Called when two fixtures cease to touch. */ public void endContact (Contact contact); - - /* - This is called after a contact is updated. This allows you to inspect a - contact before it goes to the solver. If you are careful, you can modify the - contact manifold (e.g. disable contact). - A copy of the old manifold is provided so that you can detect changes. - Note: this is called only for awake bodies. - Note: this is called even when the number of contact points is zero. - Note: this is not called for sensors. - Note: if you set the number of contact points to zero, you will not - get an EndContact callback. However, you may get a BeginContact callback - the next step. */ - public void preSolve(Contact contact, Manifold oldManifold); - /* This lets you inspect a contact after the solver is finished. This is useful - for inspecting impulses. - Note: the contact manifold does not include time of impact impulses, which can be - arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly - in a separate data structure. - Note: this is only called for contacts that are touching, solid, and awake. */ - public void postSolve(Contact contact, ContactImpulse impulse); + /* + * This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are + * careful, you can modify the contact manifold (e.g. disable contact). A copy of the old manifold is provided so that you can + * detect changes. Note: this is called only for awake bodies. Note: this is called even when the number of contact points is + * zero. Note: this is not called for sensors. Note: if you set the number of contact points to zero, you will not get an + * EndContact callback. However, you may get a BeginContact callback the next step. + */ + public void preSolve (Contact contact, Manifold oldManifold); + + /* + * This lets you inspect a contact after the solver is finished. This is useful for inspecting impulses. Note: the contact + * manifold does not include time of impact impulses, which can be arbitrarily large if the sub-step is small. Hence the + * impulse is provided explicitly in a separate data structure. Note: this is only called for contacts that are touching, + * solid, and awake. + */ + public void postSolve (Contact contact, ContactImpulse impulse); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java b/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java index e6f0b9f4f17..6cddb7b497a 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/DestructionListener.java @@ -13,6 +13,7 @@ * 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 1d63d322bf3..22d696253e4 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Filter.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Filter.java @@ -13,27 +13,19 @@ * 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 - * - */ +/** This holds contact filtering data. + * @author mzechner */ public class Filter { - /** - * The collision category bits. Normally you would just set one bit. - */ + /** 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 7a67a32a1e5..185616daa84 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Fixture.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Fixture.java @@ -13,6 +13,7 @@ * 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; @@ -31,26 +32,22 @@ public class Fixture { /** user specified data **/ protected Object userData; - /** - * Constructs a new fixture - * @param addr the address of the fixture - */ + /** Constructs a new fixture + * @param addr the address of the fixture */ protected Fixture (Body body, long addr) { this.body = body; this.addr = addr; } - protected void reset(Body body, long addr) { + protected void reset (Body body, long addr) { this.body = body; this.addr = addr; this.shape = null; this.userData = null; } - - /** - * Get the type of the child shape. You can use this to down cast to the concrete shape. - * @return the shape type. - */ + + /** 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) @@ -61,9 +58,7 @@ public Type getType () { private native int jniGetType (long addr); - /** - * Returns the shape of this fixture - */ + /** Returns the shape of this fixture */ public Shape getShape () { if (shape == null) { long shapeAddr = jniGetShape(addr); @@ -80,38 +75,30 @@ public Shape getShape () { 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); } private native void jniSetSensor (long addr, boolean sensor); - /** - * Is this fixture a sensor (non-solid)? - * @return the true if the shape is a sensor. - */ + /** Is this fixture a sensor (non-solid)? + * @return the true if the shape is a sensor. */ public boolean isSensor () { return jniIsSensor(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); } 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(); @@ -125,27 +112,21 @@ public Filter getFilterData () { 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 () { return body; } - /** - * Test a point for containment in this fixture. - * @param p a point in world coordinates. - */ + /** 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); } - - /** - * Test a point for containment in this fixture. + + /** Test a point for containment in this fixture. * @param x the x-coordinate - * @param y the y-coordinate - */ - public boolean testPoint(float x, float y) { + * @param y the y-coordinate */ + public boolean testPoint (float x, float y) { return jniTestPoint(addr, x, y); } @@ -175,55 +156,43 @@ public boolean testPoint(float x, float y) { // /// 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); } 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); } private native float jniGetDensity (long addr); - /** - * Get the coefficient of friction. - */ + /** Get the coefficient of friction. */ public float getFriction () { return jniGetFriction(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); } private native void jniSetFriction (long addr, float friction); - /** - * Get the coefficient of restitution. - */ + /** Get the coefficient of restitution. */ public float getRestitution () { return jniGetRestitution(addr); } private native float jniGetRestitution (long addr); - /** - * Set the coefficient of restitution. - */ + /** Set the coefficient of restitution. */ public void setRestitution (float restitution) { jniSetRestitution(addr, restitution); } @@ -235,16 +204,12 @@ public void setRestitution (float restitution) { // /// the body transform. // const b2AABB& GetAABB() const; - /** - * Sets custom user data. - */ + /** Sets custom user data. */ public void setUserData (Object userData) { this.userData = userData; } - /** - * @return custom user data - */ + /** @return custom user data */ public Object getUserData () { return userData; } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java index 70275fd1987..5e3a1804561 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/FixtureDef.java @@ -13,18 +13,14 @@ * 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 +/** A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture * definitions safely. - * @author mzechner - * - */ + * @author mzechner */ 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]. **/ @@ -36,9 +32,7 @@ public class FixtureDef { /** 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. **/ diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java b/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java index c782daba4c0..5f3652e2c83 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Joint.java @@ -13,6 +13,7 @@ * 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; @@ -34,18 +35,14 @@ public abstract class Joint { /** joint edge b **/ protected JointEdge jointEdgeB; - /** - * Constructs a new joint - * @param addr the address of the joint - */ + /** Constructs a new joint + * @param addr the address of the joint */ 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) @@ -56,27 +53,21 @@ public JointType getType () { 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); - /** - * 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); - /** - * 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 () { @@ -88,9 +79,7 @@ public Vector2 getAnchorA () { private native void jniGetAnchorA (long addr, float[] anchorA); - /** - * Get the anchor point on bodyB in world coordinates. - */ + /** Get the anchor point on bodyB in world coordinates. */ private final Vector2 anchorB = new Vector2(); public Vector2 getAnchorB () { @@ -102,9 +91,7 @@ public Vector2 getAnchorB () { private native void jniGetAnchorB (long addr, float[] anchorB); - /** - * Get the reaction force on body2 at the joint anchor in Newtons. - */ + /** Get the reaction force on body2 at the joint anchor in Newtons. */ private final Vector2 reactionForce = new Vector2(); public Vector2 getReactionForce (float inv_dt) { @@ -116,9 +103,7 @@ public Vector2 getReactionForce (float inv_dt) { 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); } @@ -134,9 +119,7 @@ public float getReactionTorque (float inv_dt) { // /// 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); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java b/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java index a89c2f5b1e5..2204fdcf02f 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/JointDef.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; public class JointDef { diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java b/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java index f6840f687f5..f61ccfe3f8a 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/JointEdge.java @@ -13,13 +13,12 @@ * 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 +/** 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. - */ + * each attached body. */ public class JointEdge { public final Body other; public final Joint joint; diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Manifold.java b/gdx/src/com/badlogic/gdx/physics/box2d/Manifold.java index 105c8000cf8..c49952ecb85 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Manifold.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Manifold.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.physics.box2d; import com.badlogic.gdx.math.Vector2; @@ -5,54 +6,54 @@ public class Manifold { final World world; long addr; - final ManifoldPoint[] points = new ManifoldPoint[] { new ManifoldPoint(), new ManifoldPoint() }; + final ManifoldPoint[] points = new ManifoldPoint[] {new ManifoldPoint(), new ManifoldPoint()}; final Vector2 localNormal = new Vector2(); - final Vector2 localPoint = new Vector2(); - + final Vector2 localPoint = new Vector2(); + final int[] tmpInt = new int[2]; final float[] tmpFloat = new float[4]; - - protected Manifold(World world, long addr) { + + protected Manifold (World world, long addr) { this.world = world; this.addr = addr; } - - public ManifoldType getType() { + + public ManifoldType getType () { int type = jniGetType(addr); - if(type == 0) return ManifoldType.Circle; - if(type == 1) return ManifoldType.FaceA; - if(type == 2) return ManifoldType.FaceB; + if (type == 0) return ManifoldType.Circle; + if (type == 1) return ManifoldType.FaceA; + if (type == 2) return ManifoldType.FaceB; return ManifoldType.Circle; } - - private native int jniGetType(long addr); - - public int getPointCount() { + + private native int jniGetType (long addr); + + public int getPointCount () { return jniGetPointCount(addr); } - - private native int jniGetPointCount(long addr); - - public Vector2 getLocalNormal() { + + private native int jniGetPointCount (long addr); + + public Vector2 getLocalNormal () { jniGetLocalNormal(addr, tmpFloat); localNormal.set(tmpFloat[0], tmpFloat[1]); return localNormal; } - - private native void jniGetLocalNormal(long addr, float[] values); - - public Vector2 getLocalPoint() { + + private native void jniGetLocalNormal (long addr, float[] values); + + public Vector2 getLocalPoint () { jniGetLocalPoint(addr, tmpFloat); localPoint.set(tmpFloat[0], tmpFloat[1]); return localPoint; } - - private native void jniGetLocalPoint(long addr, float[] values); - - public ManifoldPoint[] getPoints() { + + private native void jniGetLocalPoint (long addr, float[] values); + + public ManifoldPoint[] getPoints () { int count = jniGetPointCount(addr); - - for(int i = 0; i < count; i++) { + + for (int i = 0; i < count; i++) { int contactID = jniGetPoint(addr, tmpFloat, i); ManifoldPoint point = points[i]; point.contactID = contactID; @@ -60,26 +61,24 @@ public ManifoldPoint[] getPoints() { point.normalImpulse = tmpFloat[2]; point.tangentImpulse = tmpFloat[3]; } - + return points; } - - private native int jniGetPoint(long addr, float[] values, int i); - + + private native int jniGetPoint (long addr, float[] values, int i); + public class ManifoldPoint { public final Vector2 localPoint = new Vector2(); public float normalImpulse; public float tangentImpulse; public int contactID = 0; - - public String toString() { - return "id: " + contactID + ", " + localPoint + ", " + normalImpulse + ", " + tangentImpulse; + + public String toString () { + return "id: " + contactID + ", " + localPoint + ", " + normalImpulse + ", " + tangentImpulse; } } - + public enum ManifoldType { - Circle, - FaceA, - FaceB - } + Circle, FaceA, FaceB + } } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java b/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java index e2ec89606c7..dc4691617c2 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/MassData.java @@ -13,15 +13,13 @@ * 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; -/** - * This holds the mass data computed for a shape. - * @author mzechner - * - */ +/** This holds the mass data computed for a shape. + * @author mzechner */ 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 da7c030da67..bc6272c0997 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/PolygonShape.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/PolygonShape.java @@ -13,14 +13,13 @@ * 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 { - /** - * Constructs a new polygon - */ + /** Constructs a new polygon */ public PolygonShape () { addr = newPolygonShape(); } @@ -31,17 +30,14 @@ protected PolygonShape (long addr) { private native long newPolygonShape (); - /** - * {@inheritDoc} - */ - @Override public Type getType () { + /** {@inheritDoc} */ + @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++) { @@ -53,42 +49,34 @@ public void set (Vector2[] vertices) { private native void jniSet (long addr, float[] verts); - /** - * Build vertices to represent an axis-aligned box. + /** Build vertices to represent an axis-aligned box. * @param hx the half-width. - * @param hy the half-height. - */ + * @param hy the half-height. */ public void setAsBox (float hx, float hy) { jniSetAsBox(addr, hx, 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 in radians of the box in local coordinates. - */ + * @param angle the rotation in radians 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); } private native void jniSetAsBox (long addr, float hx, float hy, float centerX, float centerY, float angle); - /** - * Set this as a single edge. - */ + /** Set this as a single edge. */ 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); - /** - * @return the number of vertices - */ + /** @return the number of vertices */ public int getVertexCount () { return jniGetVertexCount(addr); } @@ -97,11 +85,9 @@ public int getVertexCount () { private static float[] verts = new float[2]; - /** - * Returns the vertex at the given position. + /** Returns the vertex at the given position. * @param index the index of the vertex 0 <= index < getVertexCount( ) - * @param vertex vertex - */ + * @param vertex vertex */ public void getVertex (int index, Vector2 vertex) { jniGetVertex(addr, index, verts); vertex.x = verts[0]; diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java b/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java index a03cbd1d05a..994a4d21d61 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/QueryCallback.java @@ -13,15 +13,12 @@ * 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 { - /** - * Called for each fixture found in the query AABB. - * @return false to terminate the query. - */ + /** Called for each fixture found in the query AABB. + * @return false to terminate the query. */ public boolean reportFixture (Fixture fixture); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/RayCastCallback.java b/gdx/src/com/badlogic/gdx/physics/box2d/RayCastCallback.java index 9fd1421ec7d..ae148f87a41 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/RayCastCallback.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/RayCastCallback.java @@ -13,30 +13,23 @@ * 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; -/** - * Callback class for ray casts. +/** Callback class for ray casts. * @see World#rayCast(RayCastCallback, Vector2, Vector2) - * @author mzechner - * - */ + * @author mzechner */ public interface RayCastCallback { - - /** Called for each fixture found in the query. You control how the ray cast - proceeds by returning a float: - return -1: ignore this fixture and continue - return 0: terminate the ray cast - return fraction: clip the ray to this point - return 1: don't clip the ray and continue - @param fixture the fixture hit by the ray - @param point the point of initial intersection - @param normal the normal vector at the point of intersection - @return -1 to filter, 0 to terminate, fraction to clip the ray for - closest hit, 1 to continue - **/ - public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction); + + /** Called for each fixture found in the query. You control how the ray cast proceeds by returning a float: return -1: ignore + * this fixture and continue return 0: terminate the ray cast return fraction: clip the ray to this point return 1: don't clip + * the ray and continue + * @param fixture the fixture hit by the ray + * @param point the point of initial intersection + * @param normal the normal vector at the point of intersection + * @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue **/ + public float reportRayFixture (Fixture fixture, Vector2 point, Vector2 normal, float fraction); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java b/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java index 7025badd604..e3c40aa9813 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Shape.java @@ -13,22 +13,17 @@ * 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 +/** 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(); - * @author mzechner - * - */ + * @author mzechner */ public abstract class Shape { - /** - * Enum describing the type of a shape - * @author mzechner - * - */ + /** Enum describing the type of a shape + * @author mzechner */ public enum Type { Circle, Polygon, }; @@ -36,33 +31,25 @@ public enum Type { /** 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. - * @return the shape type. - */ + /** 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 (); - /** - * Returns the radius of this shape - */ + /** Returns the radius of this shape */ public float getRadius () { return jniGetRadius(addr); } private native float jniGetRadius (long addr); - /** - * Sets the radius of this shape - */ + /** Sets the radius of this shape */ public void setRadius (float radius) { jniSetRadius(addr, 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); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java b/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java index 5e35a3b1601..ebca60ef431 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/Transform.java @@ -13,17 +13,15 @@ * 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 +/** 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 - * - */ + * @author mzechner */ public class Transform { public static final int POS_X = 0; public static final int POS_Y = 1; @@ -40,20 +38,16 @@ 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 - */ + * @param angle the angle in radians */ public Transform (Vector2 position, float angle) { setPosition(position); setRotation(angle); } - /** - * Transforms the given vector by this transform - * @param v the vector - */ + /** Transforms the given vector by this transform + * @param v the vector */ 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; @@ -63,17 +57,13 @@ public Vector2 mul (Vector2 v) { return v; } - /** - * @return the position, modification of the vector has no effect on the Transform - */ + /** @return the position, modification of the vector has no effect on the Transform */ public Vector2 getPosition () { return position.set(vals[0], vals[1]); } - /** - * Sets the rotation of this transform - * @param angle angle in radians - */ + /** 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; @@ -82,10 +72,8 @@ public void setRotation (float angle) { vals[COL2_Y] = c; } - /** - * Sets the position of this transform - * @param pos the position - */ + /** Sets the position of this transform + * @param pos the position */ 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 65df9cd3208..8f873979e06 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/World.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/World.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.physics.box2d; import java.util.ArrayList; @@ -43,26 +44,26 @@ import com.badlogic.gdx.utils.LongMap; import com.badlogic.gdx.utils.Pool; -/** - * The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient +/** The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient * memory management facilities. - * @author mzechner - */ + * @author mzechner */ public final class World implements Disposable { /** pool for bodies **/ protected final Pool freeBodies = new Pool(100, 200) { - @Override protected Body newObject () { + @Override + protected Body newObject () { return new Body(World.this, 0); - } + } }; - + /** pool for fixtures **/ protected final Pool freeFixtures = new Pool(100, 200) { - @Override protected Fixture newObject () { + @Override + protected Fixture newObject () { return new Fixture(null, 0); - } + } }; - + /** the address of the world instance **/ private final long addr; @@ -81,38 +82,32 @@ public final class World implements Disposable { /** Contact listener **/ protected ContactListener contactListener = null; - /** - * Ray-cast the world for all fixtures in the path of the ray. - * The ray-cast ignores shapes that contain the starting point. + /** Ray-cast the world for all fixtures in the path of the ray. 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 - */ - public void rayCast(RayCastCallback callback, Vector2 point1, Vector2 point2) - { + * @param point2 the ray ending point */ + public void rayCast (RayCastCallback callback, Vector2 point1, Vector2 point2) { rayCastCallback = callback; jniRayCast(addr, point1.x, point1.y, point2.x, point2.y); } - + private RayCastCallback rayCastCallback = null; - + private native void jniRayCast (long addr, float aX, float aY, float bX, float bY); private Vector2 rayPoint = new Vector2(); private Vector2 rayNormal = new Vector2(); - + private float reportRayFixture (long addr, float pX, float pY, float nX, float nY, float fraction) { - if (rayCastCallback != null) - return rayCastCallback.reportRayFixture(fixtures.get(addr), rayPoint.set(pX, pY), rayNormal.set(nX, nY), fraction); - else - return 0.0f; - } - - /** - * Construct a world object. + if (rayCastCallback != null) + return rayCastCallback.reportRayFixture(fixtures.get(addr), rayPoint.set(pX, pY), rayNormal.set(nX, nY), fraction); + else + return 0.0f; + } + + /** Construct a world object. * @param gravity the world gravity vector. - * @param doSleep improve performance by not simulating inactive bodies. - */ + * @param doSleep improve performance by not simulating inactive bodies. */ public World (Vector2 gravity, boolean doSleep) { addr = newWorld(gravity.x, gravity.y, doSleep); @@ -125,36 +120,28 @@ public World (Vector2 gravity, 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) { } - /** - * 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. - */ + /** 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) { this.contactListener = listener; } - /** - * Create a rigid body given a definition. No reference to the definition is retained. - * @warning This function is locked during callbacks. - */ + /** 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) { - long bodyAddr = 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); + long bodyAddr = 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); Body body = freeBodies.obtain(); body.reset(bodyAddr); this.bodies.put(body.addr, body); @@ -165,12 +152,10 @@ private native long jniCreateBody (long addr, int type, float positionX, float p 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 + /** 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. - */ + * @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++) @@ -183,11 +168,9 @@ public void destroyBody (Body body) { 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 + /** 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. - */ + * @warning This function is locked during callbacks. */ public Joint createJoint (JointDef def) { long jointAddr = createProperJoint(def); Joint joint = null; @@ -297,10 +280,8 @@ private native long jniCreateRevoluteJoint (long addr, long bodyA, long bodyB, b 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. - */ + /** Destroy a joint. This may cause the connected bodies to begin colliding. + * @warning This function is locked during callbacks. */ public void destroyJoint (Joint joint) { joints.remove(joint.addr); joint.jointEdgeA.other.joints.remove(joint.jointEdgeB); @@ -310,95 +291,75 @@ public void destroyJoint (Joint joint) { 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. - */ + * @param positionIterations for the position constraint solver. */ 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); - /** - * Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you + /** 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 - * {@link #setAutoClearForces(boolean)} - */ + * {@link #setAutoClearForces(boolean)} */ public void clearForces () { jniClearForces(addr); } private native void jniClearForces (long addr); - /** - * Enable/disable warm starting. For testing. - */ + /** Enable/disable warm starting. For testing. */ public void setWarmStarting (boolean flag) { jniSetWarmStarting(addr, flag); } private native void jniSetWarmStarting (long addr, boolean flag); - /** - * Enable/disable continuous physics. For testing. - */ + /** Enable/disable continuous physics. For testing. */ public void setContinuousPhysics (boolean flag) { jniSetContiousPhysics(addr, flag); } private native void jniSetContiousPhysics (long addr, boolean flag); - /** - * Get the number of broad-phase proxies. - */ + /** Get the number of broad-phase proxies. */ public int getProxyCount () { return jniGetProxyCount(addr); } private native int jniGetProxyCount (long addr); - /** - * Get the number of bodies. - */ + /** Get the number of bodies. */ public int getBodyCount () { return jniGetBodyCount(addr); } private native int jniGetBodyCount (long addr); - /** - * Get the number of joints. - */ + /** Get the number of joints. */ public int getJointCount () { return jniGetJointcount(addr); } private native int jniGetJointcount (long addr); - /** - * Get the number of contacts (each may have 0 or more contact points). - */ + /** Get the number of contacts (each may have 0 or more contact points). */ public int getContactCount () { return jniGetContactCount(addr); } private native int jniGetContactCount (long addr); - /** - * Change the global gravity vector. - */ + /** Change the global gravity vector. */ public void setGravity (Vector2 gravity) { jniSetGravity(addr, gravity.x, gravity.y); } private native void jniSetGravity (long addr, float gravityX, float gravityY); - /** - * Get the global gravity vector. - */ + /** Get the global gravity vector. */ final float[] tmpGravity = new float[2]; final Vector2 gravity = new Vector2(); @@ -411,41 +372,33 @@ public Vector2 getGravity () { private native void jniGetGravity (long addr, float[] gravity); - /** - * Is the world locked (in the middle of a time step). - */ + /** Is the world locked (in the middle of a time step). */ public boolean isLocked () { return jniIsLocked(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) { jniSetAutoClearForces(addr, 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); } 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 lowerX the x coordinate of the lower left corner * @param lowerY the y coordinate of the lower left corner * @param upperX the x coordinate of the upper right corner - * @param upperY the y coordinate of the upper right corner - */ + * @param upperY the y coordinate of the upper right corner */ public void QueryAABB (QueryCallback callback, float lowerX, float lowerY, float upperX, float upperY) { queryCallback = callback; jniQueryAABB(addr, lowerX, lowerY, upperX, upperY); @@ -474,16 +427,13 @@ public void QueryAABB (QueryCallback callback, float lowerX, float lowerY, float private final ArrayList contacts = new ArrayList(); private final ArrayList freeContacts = new ArrayList(); - /** - * Returns the list of {@link Contact} instances produced by the last - * call to {@link #step(float, int, int)}. Note that the returned list - * will have O(1) access times when using indexing. - * @return the contact list - */ + /** Returns the list of {@link Contact} instances produced by the last call to {@link #step(float, int, int)}. Note that the + * returned list will have O(1) access times when using indexing. + * @return the contact list */ public List getContactList () { int numContacts = getContactCount(); if (numContacts > contactAddrs.length) { - int newSize = 2*numContacts; + int newSize = 2 * numContacts; contactAddrs = new long[newSize]; contacts.ensureCapacity(newSize); freeContacts.ensureCapacity(newSize); @@ -505,16 +455,12 @@ public List getContactList () { return contacts; } - /** - * @return all bodies currently in the simulation - */ + /** @return all bodies currently in the simulation */ public Iterator getBodies () { return bodies.values(); } - /** - * @return all joints currently in the simulation - */ + /** @return all joints currently in the simulation */ public Iterator getJoints () { return joints.values(); } @@ -527,12 +473,10 @@ public void dispose () { private native void jniDispose (long addr); - /** - * Internal method called from JNI in case a contact happens + /** Internal method called from JNI in case a contact happens * @param fixtureA * @param fixtureB - * @return whether the things collided - */ + * @return whether the things collided */ private boolean contactFilter (long fixtureA, long fixtureB) { if (contactFilter != null) return contactFilter.shouldCollide(fixtures.get(fixtureA), fixtures.get(fixtureB)); @@ -559,19 +503,18 @@ private void beginContact (long contactAddr) { } private void endContact (long contactAddr) { - contact.addr = contactAddr; + contact.addr = contactAddr; if (contactListener != null) contactListener.endContact(contact); } - private void preSolve (long contactAddr, long manifoldAddr) { contact.addr = contactAddr; manifold.addr = manifoldAddr; if (contactListener != null) contactListener.preSolve(contact, manifold); } - + private void postSolve (long contactAddr, long impulseAddr) { - contact.addr = contactAddr; + contact.addr = contactAddr; impulse.addr = impulseAddr; if (contactListener != null) contactListener.postSolve(contact, impulse); } @@ -582,15 +525,11 @@ private boolean reportFixture (long addr) { else return false; } - - /** - * Sets the box2d velocity threshold globally, for all World instances. - * @param threshold the threshold, default 1.0f - */ - public static native void setVelocityThreshold(float threshold); - - /** - * @return the global box2d velocity threshold. - */ - public static native float getVelocityThreshold(); + + /** Sets the box2d velocity threshold globally, for all World instances. + * @param threshold the threshold, default 1.0f */ + public static native void setVelocityThreshold (float threshold); + + /** @return the global box2d velocity threshold. */ + public static native float getVelocityThreshold (); } diff --git a/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java b/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java index e0d429e1f2b..f9340839372 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/WorldManifold.java @@ -13,13 +13,12 @@ * 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; -/** - * This is used to compute the current state of a contact manifold. - */ +/** This is used to compute the current state of a contact manifold. */ public class WorldManifold { protected final Vector2 normal = new Vector2(); protected final Vector2[] points = {new Vector2(), new Vector2()}; @@ -28,24 +27,18 @@ public class WorldManifold { protected WorldManifold () { } - /** - * Returns the normal of this manifold - */ + /** Returns the normal of this manifold */ 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 () { return points; } - /** - * @return the number of contact points - */ + /** @return the number of contact points */ 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 79f547f1f42..82d4dc9012b 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJoint.java @@ -13,68 +13,55 @@ * 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); } - /** - * 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); } 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); } private native float jniGetLength (long addr); - /** - * Set/get frequency in Hz. - */ + /** Set/get frequency in Hz. */ public void setFrequency (float hz) { jniSetFrequency(addr, hz); } private native void jniSetFrequency (long addr, float hz); - /** - * Set/get frequency in Hz. - */ + /** Set/get frequency in Hz. */ public float getFrequency () { return jniGetFrequency(addr); } private native float jniGetFrequency (long addr); - /** - * Set/get damping ratio. - */ + /** Set/get damping ratio. */ public void setDampingRatio (float ratio) { jniSetDampingRatio(addr, ratio); } private native void jniSetDampingRatio (long addr, float ratio); - /** - * Set/get damping ratio. - */ + /** Set/get damping ratio. */ public float getDampingRatio () { return jniGetDampingRatio(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 4fd73d465e9..4d406b54e24 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/DistanceJointDef.java @@ -13,26 +13,23 @@ * 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; -/** - * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. +/** 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. - */ + * @warning Do not use a zero or short length. */ 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) { this.bodyA = bodyA; this.bodyB = bodyB; @@ -41,28 +38,18 @@ public void initialize (Body bodyA, Body bodyB, Vector2 anchorA, Vector2 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. - */ + /** The damping ratio. 0 = no damping, 1 = critical damping. */ public float dampingRatio = 0; } 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 77146901703..116558b19cf 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJoint.java @@ -13,49 +13,40 @@ * 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); } - /** - * Set the maximum friction force in N. - */ + /** Set the maximum friction force in N. */ public void setMaxForce (float force) { jniSetMaxForce(addr, 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); } private native float jniGetMaxForce (long addr); - /** - * Set the maximum friction torque in N*m. - */ + /** Set the maximum friction torque in N*m. */ public void setMaxTorque (float torque) { jniSetMaxTorque(addr, 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); } 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 0faa1e2e0df..ac8ecf08d56 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/FrictionJointDef.java @@ -13,24 +13,21 @@ * 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; -/** - * Friction joint definition. - */ +/** Friction joint definition. */ 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) { this.bodyA = bodyA; this.bodyB = bodyB; @@ -38,23 +35,15 @@ public void initialize (Body bodyA, Body bodyB, Vector2 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 49c63a39454..83a0d4c682a 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJoint.java @@ -13,35 +13,30 @@ * 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 +/** 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). - */ + * @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); } - /** - * Set/Get the gear ratio. - */ + /** Set/Get the gear ratio. */ public void setRatio (float ratio) { jniSetRatio(addr, 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); } 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 0432c3f7def..123496e3efe 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/GearJointDef.java @@ -13,33 +13,26 @@ * 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 () { 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. - * @see GearJoint for explanation. - */ + /** 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 44343a91b75..cd2715378a4 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJoint.java @@ -13,140 +13,111 @@ * 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); } - /** - * Get the current joint translation, usually in meters. - */ + /** Get the current joint translation, usually in meters. */ public float getJointTranslation () { return jniGetJointTranslation(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); } private native float jniGetJointSpeed (long addr); - /** - * Is the joint limit enabled? - */ + /** Is the joint limit enabled? */ public boolean isLimitEnabled () { return jniIsLimitEnabled(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); } 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); } 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); } 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); } 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); } private native boolean jniIsMotorEnabled (long addr); - /** - * Enable/disable the joint motor. - */ + /** Enable/disable the joint motor. */ public void enableMotor (boolean flag) { jniEnableMotor(addr, 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); } 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); } private native float jniGetMotorSpeed (long addr); - /** - * Set/Get the maximum motor force, usually in N. - */ + /** Set/Get the maximum motor force, usually in N. */ 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. - */ + /** 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); } private native float jniGetMaxMotorForce (long addr); - /** - * Get the current motor force, usually in N. - */ + /** Get the current motor force, usually in N. */ public float getMotorForce () { return jniGetMotorForce(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 52d5514ea74..1e42d1dd663 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/LineJointDef.java @@ -13,26 +13,23 @@ * 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; -/** - * Line joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local +/** 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. - */ + * game. */ 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) { this.bodyA = bodyA; this.bodyB = bodyB; @@ -41,48 +38,30 @@ public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) { 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(); - /** - * 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 local translation axis in body1. - */ + /** The local translation axis in body1. */ 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 05716ff3afa..b46160f6354 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJoint.java @@ -13,34 +13,29 @@ * 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.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. +/** 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. - */ + * 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) { super(world, addr); } - /** - * 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); } 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(); @@ -53,54 +48,42 @@ public Vector2 getTarget () { 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); } 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); } private native float jniGetMaxForce (long addr); - /** - * Set/get the frequency in Hertz. - */ + /** Set/get the frequency in Hertz. */ public void setFrequency (float hz) { jniSetFrequency(addr, hz); } private native void jniSetFrequency (long addr, float hz); - /** - * Set/get the frequency in Hertz. - */ + /** Set/get the frequency in Hertz. */ public float getFrequency () { return jniGetFrequency(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); } 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); } 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 2e9a8f2fc53..2fb34bf678d 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/MouseJointDef.java @@ -13,37 +13,28 @@ * 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 () { 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(); - /** - * 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 c1def89f8ed..2dd61292fc9 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJoint.java @@ -13,132 +13,105 @@ * 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 +/** 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. - */ + * friction. */ public class PrismaticJoint extends Joint { public PrismaticJoint (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); } 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); } private native float jniGetJointSpeed (long addr); - /** - * Is the joint limit enabled? - */ + /** Is the joint limit enabled? */ public boolean isLimitEnabled () { return jniIsLimitEnabled(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); } 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); } 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); } 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); } 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); } private native boolean jniIsMotorEnabled (long addr); - /** - * Enable/disable the joint motor. - */ + /** Enable/disable the joint motor. */ public void enableMotor (boolean flag) { jniEnableMotor(addr, 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); } 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); } 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); } 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); } 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 e8843f21e3c..169a4b8850f 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PrismaticJointDef.java @@ -13,27 +13,24 @@ * 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; -/** - * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses +/** 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. - */ + * @warning at least one body should by dynamic with a non-fixed rotation. */ 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) { this.bodyA = bodyA; this.bodyB = bodyB; @@ -44,53 +41,33 @@ public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 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(); - /** - * 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 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 3f1f3f5a309..5ca41772dd9 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJoint.java @@ -13,25 +13,22 @@ * 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.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 +/** 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. - */ + * 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); } - /** - * Get the first ground anchor. - */ + /** Get the first ground anchor. */ private final float[] tmp = new float[2]; private final Vector2 groundAnchorA = new Vector2(); @@ -43,9 +40,7 @@ public Vector2 getGroundAnchorA () { 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 () { @@ -56,27 +51,21 @@ public Vector2 getGroundAnchorB () { 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 () { return jniGetLength1(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 () { return jniGetLength2(addr); } private native float jniGetLength2 (long addr); - /** - * Get the pulley ratio. - */ + /** Get the pulley ratio. */ public float getRatio () { return jniGetRatio(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 f07c42e2417..e6a8db1bf40 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/PulleyJointDef.java @@ -13,16 +13,15 @@ * 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 { private final static float minPulleyLength = 2.0f; @@ -31,9 +30,7 @@ public PulleyJointDef () { 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) { this.bodyA = bodyA; @@ -51,48 +48,30 @@ public void initialize (Body bodyA, Body bodyB, Vector2 groundAnchorA, Vector2 g } - /** - * 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); - /** - * 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); - /** - * 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); - /** - * 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); - /** - * 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 72cb14aefba..c4b3a4b9f7d 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJoint.java @@ -13,134 +13,107 @@ * 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 +/** 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. - */ + * provided so that infinite forces are not generated. */ 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); } 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); } private native float jniGetJointSpeed (long addr); - /** - * Is the joint limit enabled? - */ + /** Is the joint limit enabled? */ public boolean isLimitEnabled () { return jniIsLimitEnabled(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); } 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); } private native float jniGetLowerLimit (long addr); - /** - * Get the upper joint limit in radians. - */ + /** Get the upper joint limit in radians. */ public float getUpperLimit () { return jniGetUpperLimit(addr); } private native float jniGetUpperLimit (long addr); - /** - * Set the joint limits in radians. - * @param upper - */ + /** Set the joint limits in radians. + * @param upper */ public void setLimits (float lower, float upper) { jniSetLimits(addr, lower, 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); } private native boolean jniIsMotorEnabled (long addr); - /** - * Enable/disable the joint motor. - */ + /** Enable/disable the joint motor. */ public void enableMotor (boolean flag) { jniEnableMotor(addr, 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); } 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); } 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); } 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); } 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 8c4d7dd21f8..f30064cc31e 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/RevoluteJointDef.java @@ -13,27 +13,24 @@ * 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; -/** - * Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor +/** 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. - */ + * from a body and recompute the mass, the joints will be broken. */ 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) { this.bodyA = bodyA; this.bodyB = bodyB; @@ -42,48 +39,30 @@ public void initialize (Body bodyA, Body bodyB, Vector2 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(); - /** - * 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; - /** - * 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 389e51fb8af..75bd0e47d62 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJoint.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJoint.java @@ -13,15 +13,14 @@ * 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); 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 91e6fe6183a..8201952a0bb 100644 --- a/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJointDef.java +++ b/gdx/src/com/badlogic/gdx/physics/box2d/joints/WeldJointDef.java @@ -13,6 +13,7 @@ * 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; diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java index db2159f4a81..dc21a3a34d9 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Action.java @@ -13,89 +13,66 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; -/** - * An Action is used with an {@link Actor} and modifes the Actor's attributes over time. - * - * @author mzechner +/** An Action is used with an {@link Actor} and modifes the Actor's attributes over time. * - */ + * @author mzechner */ public abstract class Action { protected OnActionCompleted listener = null; - /** - * Sets the {@link Actor} of this action. Will be called when the Action is added to an Actor via {@link Actor#action(Action)} + /** Sets the {@link Actor} of this action. Will be called when the Action is added to an Actor via {@link Actor#action(Action)} * before any other call to this interface. * - * @param actor the actor. - */ + * @param actor the actor. */ public abstract void setTarget (Actor actor); - /** - * @return the {@link Actor} this action targets. - */ - public abstract Actor getTarget(); - - /** - * Apply the action. + /** @return the {@link Actor} this action targets. */ + public abstract Actor getTarget (); + + /** Apply the action. * - * @param delta delta time in seconds - */ + * @param delta delta time in seconds */ public abstract void act (float delta); - /** - * @return whether the action is done or not - */ + /** @return whether the action is done or not */ public abstract 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 () { if (listener != null) { listener.completed(this); } } - - /** - * Calls the {@link OnActionCompleted} listener and sets it to null so it won't - * be called again. - */ - public void callActionCompletedListener() { + + /** Calls the {@link OnActionCompleted} listener and sets it to null so it won't be called again. */ + public void callActionCompletedListener () { if (listener != null) { listener.completed(this); } listener = null; } - /** - * 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(Actor)} 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(Actor)} on it without any side effects. */ public abstract Action copy (); - /** - * Sets the listener to be invoked when the action is finished. + /** Sets the listener to be invoked when the action is finished. * @param listener - * @return this - */ + * @return this */ public Action setCompletionListener (final OnActionCompleted listener) { this.listener = listener; return this; } - /** - * @return the {@link OnActionCompleted} listener or null. - */ + /** @return the {@link OnActionCompleted} listener or null. */ public OnActionCompleted getCompletionListener () { return listener; } - /** - * Sets the Action back to a vanilla state. - */ + /** Sets the Action back to a vanilla state. */ public void reset () { listener = null; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java index f79389e01ba..e8d2238b660 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; -import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; @@ -23,8 +23,7 @@ import com.badlogic.gdx.scenes.scene2d.actions.FadeIn; import com.badlogic.gdx.utils.PooledLinkedList; -/** - *

        +/**

        * An Actor is part of a {@link Stage} or a {@link Group} within a Stage. It has a position, a rectangular size given as width and * height, a rotation angle, a scale in x and y and an origin relative to the position which is used for rotation and scaling. *

        @@ -70,9 +69,7 @@ * rotation. Actions can be chained and make for rather sophisticated time based behaviour. *

        * - * @author mzechner - * - */ + * @author mzechner */ public abstract class Actor { public Group parent; public final String name; @@ -97,14 +94,12 @@ public Actor (String name) { this.name = name; } - /** - * Draws the Actor. The spriteBatch is configured so that the Actor can draw in its parents coordinate system. The parent's + /** Draws the Actor. The spriteBatch is configured so that the Actor can draw in its parents coordinate system. The parent's * alpha is passed to the method in order for the Actor to multiply it with its own alpha. This will allow {@link FadeIn} and * other Actions to have an effect even if they are only set on the parent of the Actor. * * @param batch the spritebatch to render with - * @param parentAlpha the parent's alpha value. - */ + * @param parentAlpha the parent's alpha value. */ public abstract void draw (SpriteBatch batch, float parentAlpha); public abstract boolean touchDown (float x, float y, int pointer); @@ -116,30 +111,27 @@ public Actor (String name) { public boolean touchMoved (float x, float y) { return false; } - - public boolean scrolled(int amount) { + + public boolean scrolled (int amount) { return false; } - - public boolean keyDown (int keycode) { + + public boolean keyDown (int keycode) { return false; } - - public boolean keyUp(int keycode) { + + public boolean keyUp (int keycode) { return false; } - - public boolean keyTyped(char character) { + + public boolean keyTyped (char character) { return false; - } + } - public abstract Actor hit (float x, float y); - /** - * Transforms the given point in stage coordinates to the Actor's local coordinate system. - * @param point the point - */ + /** Transforms the given point in stage coordinates to the Actor's local coordinate system. + * @param point the point */ public void toLocalCoordinates (Vector2 point) { if (parent == null) { return; @@ -149,9 +141,7 @@ public void toLocalCoordinates (Vector2 point) { Group.toChildCoordinates(this, point.x, point.y, point); } - /** - * Removes this actor from the Stage - */ + /** Removes this actor from the Stage */ public void remove () { parent.removeActor(this); } @@ -169,46 +159,39 @@ public void act (float delta) { } } - /** - * Adds an {@link Action} to the Actor. Actions will be automatically performed in the order added to the Actor and will be + /** Adds an {@link Action} to the Actor. Actions will be automatically performed in the order added to the Actor and will be * removed when they are done. * - * @param action the action - */ + * @param action the action */ public void action (Action action) { action.setTarget(this); actions.add(action); } - /** - * Clears all actions of this Actor. - */ + /** Clears all actions of this Actor. */ public void clearActions () { actions.clear(); } - @Override public String toString () { + @Override + public String toString () { return name + ": [x=" + x + ", y=" + y + ", refX=" + originX + ", refY=" + originY + ", width=" + width + ", height=" + height + "]"; } - /** - * Marks the {@link Actor} to be removed by its parent. + /** Marks the {@link Actor} to be removed by its parent. *

        * The actual removal happens in the {@link Group#act(float)} method of the parent and after the parent has called * {@link #act(float)} on this {@link Actor}. * - * @param remove whether the parent is supposed to remove this {@link Actor} - */ + * @param remove whether the parent is supposed to remove this {@link Actor} */ public void markToRemove (final boolean remove) { toRemove = remove; } - /** - * States if this actor is to be removed by its parent. + /** States if this actor is to be removed by its parent. * - * @return true when the actor is to be removed or false otherwise - */ + * @return true when the actor is to be removed or false otherwise */ public boolean isMarkedToRemove () { return toRemove; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/AnimationAction.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/AnimationAction.java index 1ad4476b701..1b0cf01f577 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/AnimationAction.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/AnimationAction.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; -/** - * An {@link AnimationAction} performs a transformation on its target {@link Actor}. These transformations physically change the +/** An {@link AnimationAction} performs a transformation on its target {@link Actor}. These transformations physically change the * Actor itself. * - * @author Moritz Post - */ + * @author Moritz Post */ public abstract class AnimationAction extends Action { protected float duration; @@ -31,23 +30,23 @@ public abstract class AnimationAction extends Action { protected Interpolator interpolator; - @Override public boolean isDone () { + @Override + public boolean isDone () { return done; } - @Override public void finish () { + @Override + public void finish () { super.finish(); if (interpolator != null) { interpolator.finished(); } } - /** - * Sets an {@link Interpolator} to modify the progression of the animations. + /** Sets an {@link Interpolator} to modify the progression of the animations. * * @param interpolator the interpolator to use during the animation - * @return an instance of self so that the call can be easily chained - */ + * @return an instance of self so that the call can be easily chained */ public AnimationAction setInterpolator (Interpolator interpolator) { this.interpolator = interpolator; return this; @@ -66,12 +65,13 @@ protected float createInterpolatedAlpha (float delta) { return interpolatedTime * invDuration; } } - + public Actor getTarget () { return target; } - @Override public void reset () { + @Override + public void reset () { super.reset(); interpolator = null; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/CompositeAction.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/CompositeAction.java index 1294e40857b..d046b54823f 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/CompositeAction.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/CompositeAction.java @@ -13,24 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; import java.util.ArrayList; -/** - * A base class for composite actions which deals with multiple child {@link Action}. +/** A base class for composite actions which deals with multiple child {@link Action}. * - * @author Moritz Post - */ + * @author Moritz Post */ public abstract class CompositeAction extends Action { protected final ArrayList actions = new ArrayList(); - /** - * Gets all target {@link Action}s which are affected by the composite action. + /** Gets all target {@link Action}s which are affected by the composite action. * - * @return the {@link Action}s orchestrated by this {@link CompositeAction} - */ + * @return the {@link Action}s orchestrated by this {@link CompositeAction} */ public ArrayList getActions () { return actions; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java index b1f9e901acb..87c6f9ab484 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Group.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; import java.util.ArrayList; @@ -28,12 +29,9 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.ObjectMap; -/** - * A group is an Actor that contains other Actors (also other Groups which are Actors). - * - * @author mzechner +/** A group is an Actor that contains other Actors (also other Groups which are Actors). * - */ + * @author mzechner */ public class Group extends Actor { public static Texture debugTexture; public static boolean debug = false; @@ -58,10 +56,8 @@ public Group () { this(null); } - /** - * Creates a new Group with the given name. - * @param name the name of the group - */ + /** Creates a new Group with the given name. + * @param name the name of the group */ public Group (String name) { super(name); this.transform = new Matrix3(); @@ -105,14 +101,15 @@ public void act (float delta) { } - @Override public void draw (SpriteBatch batch, float parentAlpha) { - if(!visible) return; - setupTransform(batch); + @Override + public void draw (SpriteBatch batch, float parentAlpha) { + if (!visible) return; + setupTransform(batch); drawChildren(batch, parentAlpha); resetTransform(batch); } - protected void setupTransform(SpriteBatch batch) { + protected void setupTransform (SpriteBatch batch) { updateTransform(); tmp4.set(scenetransform); @@ -125,31 +122,31 @@ protected void setupTransform(SpriteBatch batch) { batch.setTransformMatrix(tmp4); batch.begin(); } - - protected void drawChildren(SpriteBatch batch, float parentAlpha) { + + protected void drawChildren (SpriteBatch batch, float parentAlpha) { int len = children.size(); - for (int i = 0; i < len; i++){ + for (int i = 0; i < len; i++) { Actor child = children.get(i); - if(child.visible){ + if (child.visible) { child.draw(batch, parentAlpha * color.a); } } batch.flush(); } - - protected void drawChild(Actor child, SpriteBatch batch, float parentAlpha) { - if(child.visible){ + + protected void drawChild (Actor child, SpriteBatch batch, float parentAlpha) { + if (child.visible) { child.draw(batch, parentAlpha * color.a); } batch.flush(); } - - protected void resetTransform(SpriteBatch batch) { + + protected void resetTransform (SpriteBatch batch) { batch.end(); batch.setTransformMatrix(oldBatchTransform); batch.begin(); } - + final Vector2 point = new Vector2(); static final Vector2 xAxis = new Vector2(); @@ -157,13 +154,11 @@ protected void resetTransform(SpriteBatch batch) { static final Vector2 p = new Vector2(); static final Vector2 ref = new Vector2(); - /** - * Transforms the coordinates given in the child's parent coordinate system to the child {@link Actor}'s coordinate system. + /** Transforms the coordinates given in the child's parent coordinate system to the child {@link Actor}'s coordinate system. * @param child the child Actor * @param x the x-coordinate in the Group's coordinate system * @param y the y-coordinate in the Group's coordinate system - * @param out the output {@link Vector2} - */ + * @param out the output {@link Vector2} */ public static void toChildCoordinates (Actor child, float x, float y, Vector2 out) { if (child.rotation == 0) { if (child.scaleX == 1 && child.scaleY == 1) { @@ -243,14 +238,15 @@ public static void toChildCoordinates (Actor child, float x, float y, Vector2 ou } } - @Override public boolean touchDown (float x, float y, int pointer) { + @Override + public boolean touchDown (float x, float y, int pointer) { if (!touchable) return false; if (debug) Gdx.app.log("Group", name + ": " + x + ", " + y); if (focusedActor[pointer] != null) { point.x = x; - point.y = y; + point.y = y; focusedActor[pointer].toLocalCoordinates(point); focusedActor[pointer].touchDown(point.x, point.y, pointer); return true; @@ -275,13 +271,14 @@ public static void toChildCoordinates (Actor child, float x, float y, Vector2 ou return false; } - @Override public boolean touchUp (float x, float y, int pointer) { + @Override + public boolean touchUp (float x, float y, int pointer) { if (!touchable) return false; if (focusedActor[pointer] != null) { point.x = x; point.y = y; - focusedActor[pointer].toLocalCoordinates(point); + focusedActor[pointer].toLocalCoordinates(point); focusedActor[pointer].touchUp(point.x, point.y, pointer); return true; } @@ -297,8 +294,9 @@ public static void toChildCoordinates (Actor child, float x, float y, Vector2 ou } return false; } - - @Override public boolean touchMoved (float x, float y) { + + @Override + public boolean touchMoved (float x, float y) { if (!touchable) return false; int len = children.size() - 1; @@ -313,14 +311,14 @@ public static void toChildCoordinates (Actor child, float x, float y, Vector2 ou return false; } - - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { if (!touchable) return false; if (focusedActor[pointer] != null) { point.x = x; point.y = y; - focusedActor[pointer].toLocalCoordinates(point); + focusedActor[pointer].toLocalCoordinates(point); focusedActor[pointer].touchDragged(point.x, point.y, pointer); return true; } @@ -336,28 +334,34 @@ public static void toChildCoordinates (Actor child, float x, float y, Vector2 ou } return false; } - + @Override - public boolean scrolled(int amount) { - if(scrollFocusedActor != null) scrollFocusedActor.scrolled(amount); + public boolean scrolled (int amount) { + if (scrollFocusedActor != null) scrollFocusedActor.scrolled(amount); return false; } - + public boolean keyDown (int keycode) { - if(keyboardFocusedActor != null) return keyboardFocusedActor.keyDown(keycode); - else return false; - } - - public boolean keyUp(int keycode) { - if(keyboardFocusedActor != null) return keyboardFocusedActor.keyUp(keycode); - else return false; - } - - public boolean keyTyped(char character) { - if(keyboardFocusedActor != null) return keyboardFocusedActor.keyTyped(character); - else return false; - } - + if (keyboardFocusedActor != null) + return keyboardFocusedActor.keyDown(keycode); + else + return false; + } + + public boolean keyUp (int keycode) { + if (keyboardFocusedActor != null) + return keyboardFocusedActor.keyUp(keycode); + else + return false; + } + + public boolean keyTyped (char character) { + if (keyboardFocusedActor != null) + return keyboardFocusedActor.keyTyped(character); + else + return false; + } + public Actor hit (float x, float y) { int len = children.size() - 1; for (int i = len; i >= 0; i--) { @@ -373,10 +377,8 @@ public Actor hit (float x, float y) { return null; } - /** - * Adds an {@link Actor} to this Group. The order Actors are added is reversed for hit testing and rendering. - * @param actor the Actor - */ + /** Adds an {@link Actor} to this Group. The order Actors are added is reversed for hit testing and rendering. + * @param actor the Actor */ public void addActor (Actor actor) { children.add(actor); if (actor instanceof Group) groups.add((Group)actor); @@ -384,11 +386,9 @@ public void addActor (Actor actor) { actor.parent = this; } - /** - * Adds an {@link Actor} at the given index in the group. The first Actor added will be at index 0 and so on. Throws an + /** Adds an {@link Actor} at the given index in the group. The first Actor added will be at index 0 and so on. Throws an * IndexOutOfBoundsException in case the index is invalid. - * @param index the index to add the actor at. - */ + * @param index the index to add the actor at. */ public void addActorAt (int index, Actor actor) { children.add(index, actor); if (actor instanceof Group) groups.add((Group)actor); @@ -396,11 +396,9 @@ public void addActorAt (int index, Actor actor) { actor.parent = this; } - /** - * Adds an {@link Actor} before the given Actor. + /** Adds an {@link Actor} before the given Actor. * @param actorBefore the Actor to add the other actor in front of - * @param actor the Actor to add - */ + * @param actor the Actor to add */ public void addActorBefore (Actor actorBefore, Actor actor) { int index = children.indexOf(actorBefore); children.add(index, actor); @@ -409,11 +407,9 @@ public void addActorBefore (Actor actorBefore, Actor actor) { actor.parent = this; } - /** - * Adds an {@link Actor} after the given Actor. + /** Adds an {@link Actor} after the given Actor. * @param actorAfter the Actor to add the other Actor behind - * @param actor the Actor to add - */ + * @param actor the Actor to add */ public void addActorAfter (Actor actorAfter, Actor actor) { int index = children.indexOf(actorAfter); if (index == children.size()) @@ -425,40 +421,33 @@ public void addActorAfter (Actor actorAfter, Actor actor) { actor.parent = this; } - /** - * Removes an {@link Actor} from this Group. - * @param actor - */ - public void removeActor (Actor actor) { + /** Removes an {@link Actor} from this Group. + * @param actor */ + public void removeActor (Actor actor) { children.remove(actor); if (actor instanceof Group) groups.remove((Group)actor); if (actor.name != null) namesToActors.remove(actor.name); unfocusAll(actor); } - /** - * Removes an {@link Actor} from this Group recursively by checking - * if the Actor is in this group or one of its child-groups. - * @param actor the Actor - */ - public void removeActorRecursive(Actor actor) { - if(children.remove(actor)) { + /** Removes an {@link Actor} from this Group recursively by checking if the Actor is in this group or one of its child-groups. + * @param actor the Actor */ + public void removeActorRecursive (Actor actor) { + if (children.remove(actor)) { if (actor instanceof Group) groups.remove((Group)actor); if (actor.name != null) namesToActors.remove(actor.name); unfocusAll(actor); return; } - - for(int i = 0; i < groups.size(); i++) { + + for (int i = 0; i < groups.size(); i++) { groups.get(i).removeActorRecursive(actor); } } - - /** - * Finds the {@link Actor} with the given name in this Group and its children. + + /** Finds the {@link Actor} with the given name in this Group and its children. * @param name the name of the Actor - * @return the Actor or null - */ + * @return the Actor or null */ public Actor findActor (String name) { Actor actor = namesToActors.get(name); if (actor == null) { @@ -472,12 +461,10 @@ public Actor findActor (String name) { return actor; } - /** - * Swap two actors' sort order by index. 0 is lowest while getActors().size() - 1 is largest. + /** Swap two actors' sort order by index. 0 is lowest while getActors().size() - 1 is largest. * @param first first Actor index * @param second second Actor index - * @return false if indices are out of bound. - */ + * @return false if indices are out of bound. */ public boolean swapActor (int first, int second) { int maxIndex = children.size(); if (first < 0 || first >= maxIndex) return false; @@ -486,12 +473,10 @@ public boolean swapActor (int first, int second) { return true; } - /** - * Swap two actors' sort order by reference. + /** Swap two actors' sort order by reference. * @param first first Actor * @param second second Actor - * @return false if any of the Actors is not the child of this Group. - */ + * @return false if any of the Actors is not the child of this Group. */ public boolean swapActor (Actor first, Actor second) { int firstIndex = children.indexOf(first); int secondIndex = children.indexOf(second); @@ -500,49 +485,39 @@ public boolean swapActor (Actor first, Actor second) { return true; } - /** - * @return all child {@link Actor}s as an ordered list. - */ + /** @return all child {@link Actor}s as an ordered list. */ public List getActors () { return immutableChildren; } - /** - * @return all child {@link Group}s as an unordered list. - */ + /** @return all child {@link Group}s as an unordered list. */ public List getGroups () { return immutableGroups; } - /** - * Sets the focus to the given child {@link Actor}. All subsequent touch events with the given pointer id will be passed to this child Actor. To unset - * the focus simply pass null. + /** Sets the focus to the given child {@link Actor}. All subsequent touch events with the given pointer id will be passed to + * this child Actor. To unset the focus simply pass null. * - * @param actor the Actor - */ + * @param actor the Actor */ public void focus (Actor actor, int pointer) { focusedActor[pointer] = actor; if (parent != null) parent.focus(actor, pointer); } - - /** - * Sets the keyboard focus to the given child {@link Actor}. All subsequent keyboard events will be passed to that actor. - * To unfocus an actor simply pass null. - * @param actor the Actor - */ - public void keyboardFocus(Actor actor) { + + /** Sets the keyboard focus to the given child {@link Actor}. All subsequent keyboard events will be passed to that actor. To + * unfocus an actor simply pass null. + * @param actor the Actor */ + public void keyboardFocus (Actor actor) { keyboardFocusedActor = actor; - if(parent != null) parent.keyboardFocus(actor); - } - - /** - * Sets the scroll focus to the given child {@link Actor}. All subsequent scroll events will be passed to that actor. - * To unfocus an actor simply pass null. - * @param actor the Actor. - */ - public void scrollFocus(Actor actor) { + if (parent != null) parent.keyboardFocus(actor); + } + + /** Sets the scroll focus to the given child {@link Actor}. All subsequent scroll events will be passed to that actor. To + * unfocus an actor simply pass null. + * @param actor the Actor. */ + public void scrollFocus (Actor actor) { scrollFocusedActor = actor; - if(parent != null) parent.scrollFocus(actor); + if (parent != null) parent.scrollFocus(actor); } public static void enableDebugging (String debugTextureFile) { @@ -555,55 +530,45 @@ public static void disableDebugging () { debug = false; } - /** - * Clears this Group, removing all contained {@link Actor}s. - */ + /** Clears this Group, removing all contained {@link Actor}s. */ public void clear () { this.children.clear(); this.groups.clear(); this.namesToActors.clear(); } - /** - * Sorts the children via the given {@link Comparator}. - * @param comparator the comparator. - */ + /** Sorts the children via the given {@link Comparator}. + * @param comparator the comparator. */ public void sortChildren (Comparator comparator) { Collections.sort(this.children, comparator); } - - /** - * Unfocuses all {@link Actor} instance currently focused for touch and keyboard events. You should - * call this in case your app resumes to clear up any pressed states. - * Make sure the Actors forget their states as well! This will be applied - * to all child groups recursively. - */ - public void unfocusAll() { - for(int i = 0; i < focusedActor.length; i++) { + + /** Unfocuses all {@link Actor} instance currently focused for touch and keyboard events. You should call this in case your app + * resumes to clear up any pressed states. Make sure the Actors forget their states as well! This will be applied to all child + * groups recursively. */ + public void unfocusAll () { + for (int i = 0; i < focusedActor.length; i++) { focusedActor[i] = null; } - - for(int i = 0; i < groups.size(); i++) { + + for (int i = 0; i < groups.size(); i++) { groups.get(i).unfocusAll(); } - + keyboardFocusedActor = null; scrollFocusedActor = null; } - - /** - * Unfocuses this {@link Actor} from the touch, keyboard and scroll focus from this group - * and all groups above it. - * @param actor the Actor - */ - public void unfocusAll(Actor actor) { - for(int i = 0; i < focusedActor.length; i++) { - if(focusedActor[i] == actor) { + + /** Unfocuses this {@link Actor} from the touch, keyboard and scroll focus from this group and all groups above it. + * @param actor the Actor */ + public void unfocusAll (Actor actor) { + for (int i = 0; i < focusedActor.length; i++) { + if (focusedActor[i] == actor) { focus(null, i); } } - - if(keyboardFocusedActor == actor) keyboardFocus(null); - if(scrollFocusedActor == actor) scrollFocus(null); + + if (keyboardFocusedActor == actor) keyboardFocus(null); + if (scrollFocusedActor == actor) scrollFocus(null); } -} \ No newline at end of file +} diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Interpolator.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Interpolator.java index db735444c5e..68c671023dc 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Interpolator.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Interpolator.java @@ -13,35 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; -/** - * An interpolator defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, +/** An interpolator defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, * rotate) to be accelerated, decelerated etc. * - * @author Moritz Post - */ + * @author Moritz Post */ public interface Interpolator { - /** - * Maps a point in the animation duration to a multiplier to be applied to the transformations of an animation. The Input is a + /** Maps a point in the animation duration to a multiplier to be applied to the transformations of an animation. The Input is a * percentage of the elapsed animation duration. * * @param input A value between 0 and 1.0 indicating our current point in the animation where 0 represents the start and 1.0 * represents the end * @return The interpolation value. This value can be more than 1.0 for {@link Interpolator}s which overshoot their targets, or - * less than 0 for {@link Interpolator}s that undershoot their targets. - */ + * less than 0 for {@link Interpolator}s that undershoot their targets. */ float getInterpolation (float input); - /** - * Called when the animation has finished and the {@link Interpolator} is no longer needed. - */ + /** Called when the animation has finished and the {@link Interpolator} is no longer needed. */ void finished (); - /** - * Creates a copy of this interpolator. - * @return the copy. - */ - Interpolator copy(); + /** Creates a copy of this interpolator. + * @return the copy. */ + Interpolator copy (); } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Layout.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Layout.java index 16bdeaf586e..d14a6f46cee 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Layout.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Layout.java @@ -13,11 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; public interface Layout { public void layout (); - + public void invalidate (); public float getPrefWidth (); diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/OnActionCompleted.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/OnActionCompleted.java index 8c606147cc0..3673e31e8cb 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/OnActionCompleted.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/OnActionCompleted.java @@ -13,24 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; import com.badlogic.gdx.scenes.scene2d.actions.Repeat; -/** - * Listener interface called by an {@link Action} when it was completed. Use this - * with {@link Action#setCompletionListener(OnActionCompleted)}; - * @author mzechner - * - */ +/** Listener interface called by an {@link Action} when it was completed. Use this with + * {@link Action#setCompletionListener(OnActionCompleted)}; + * @author mzechner */ public interface OnActionCompleted { - /** - * Called when the {@link Action} is completed. Note that this - * might get called multiple times in case the Action is part of - * a {@link Repeat} Action. If the Action is an {@link AnimationAction} - * then you can cast to this class and receive the targeted {link Actor} - * via {@link AnimationAction#getTarget()}. - * @param action the Action. - */ - public void completed(Action action); + /** Called when the {@link Action} is completed. Note that this might get called multiple times in case the Action is part of a + * {@link Repeat} Action. If the Action is an {@link AnimationAction} then you can cast to this class and receive the targeted + * {link Actor} via {@link AnimationAction#getTarget()}. + * @param action the Action. */ + public void completed (Action action); } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java index f51b2989bdf..b123ef4b441 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; import java.util.List; import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.Camera; @@ -28,16 +28,15 @@ import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Disposable; -/** - *

        +/**

        * A Stage is a container for {@link Actor}s and handles distributing touch events, animating Actors and asking them to render * themselves. A Stage is basically a 2D scenegraph with hierarchies of Actors. *

        * *

        * A Stage object fills the whole screen. It has a width and height given in device independent pixels. It will create a - * {@link Camera} 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 + * {@link Camera} 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. *

        * @@ -46,14 +45,13 @@ * top of Actors added earlier. Touch events that will get distributed to later Actors first. *

        * - *

        Actors can get focused. When your game pauses and resumes make sure to call the {@link Stage#unfocusAll()} method so - * that the focus states get reset for each pointer id. You also have to make sure that the Actors that were focused reset - * their state if the depend on being focused, e.g. wait for a touch up event. An easier way to tackle this is to recreate the - * Stage if possible.

        - * - * @author mzechner + *

        + * Actors can get focused. When your game pauses and resumes make sure to call the {@link Stage#unfocusAll()} method so that the + * focus states get reset for each pointer id. You also have to make sure that the Actors that were focused reset their state if + * the depend on being focused, e.g. wait for a touch up event. An easier way to tackle this is to recreate the Stage if possible. + *

        * - */ + * @author mzechner */ public class Stage extends InputAdapter implements Disposable { protected float width; protected float height; @@ -63,11 +61,10 @@ public class Stage extends InputAdapter implements Disposable { protected final Group root; - protected final SpriteBatch batch; + protected final SpriteBatch batch; protected Camera camera; - /** - *

        + /**

        * 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. @@ -75,30 +72,27 @@ public class Stage extends InputAdapter implements Disposable { * * @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 - */ + * @param stretch whether to stretch the viewport to the real device resolution */ 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.camera = new OrthographicCamera(); + this.camera = new OrthographicCamera(); 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 + /** 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 stretch whether to stretch the viewport or not - */ + * @param stretch whether to stretch the viewport or not */ public void setViewport (float width, float height, boolean stretch) { if (!stretch) { - if (width > height && width/(float)Gdx.graphics.getWidth() <= height/(float)Gdx.graphics.getHeight()) { + if (width > height && width / (float)Gdx.graphics.getWidth() <= height / (float)Gdx.graphics.getHeight()) { float toDeviceSpace = Gdx.graphics.getHeight() / height; float toViewportSpace = height / Gdx.graphics.getHeight(); @@ -127,88 +121,65 @@ public void setViewport (float width, float height, boolean stretch) { camera.viewportHeight = this.height; } - /**8 - * @return the width of the stage in dips - */ + /** 8 + * @return the width of the stage in dips */ public float width () { return width; } - /** - * @return the height of the stage in dips - */ + /** @return the height of the stage in dips */ public float height () { return height; } - /** - * @return the x-coordinate of the left edge of the stage in dips - */ + /** @return the x-coordinate of the left edge of the stage in dips */ public int left () { return 0; } - /** - * @return the x-coordinate of the right edge of the stage in dips - */ + /** @return the x-coordinate of the right edge of the stage in dips */ public float right () { return width - 1; } - /** - * @return the y-coordinate of the top edge of the stage in dips - */ + /** @return the y-coordinate of the top edge of the stage in dips */ public float top () { return height - 1; } - /** - * @return the y-coordinate of the bottom edge of the stage in dips - */ + /** @return the y-coordinate of the bottom edge of the stage in dips */ public float bottom () { return 0; } - /** - * @return the center x-coordinate of the stage in dips - */ + /** @return the center x-coordinate of the stage in dips */ public float centerX () { return centerX; } - /** - * @return the center y-coordinate of the stage in dips - */ + /** @return the center y-coordinate of the stage in dips */ public float centerY () { return centerY; } - /** - * @return whether the stage is stretched - */ + /** @return whether the stage is stretched */ public boolean isStretched () { return stretch; } - /** - * Finds the {@link Actor} with the given name in the stage hierarchy. + /** Finds the {@link Actor} with the given name in the stage hierarchy. * @param name - * @return the Actor or null if it couldn't be found. - */ + * @return the Actor or null if it couldn't be found. */ public Actor findActor (String name) { return root.findActor(name); } - /** - * @return all top level {@link Actor}s - */ + /** @return all top level {@link Actor}s */ public List getActors () { return root.getActors(); } - /** - * @return all top level {@link Group}s - */ + /** @return all top level {@link Group}s */ public List getGroups () { return root.getGroups(); } @@ -216,14 +187,12 @@ public List getGroups () { final Vector2 point = new Vector2(); final Vector2 coords = new Vector2(); - /** - * Call this to distribute a touch down event to the stage. + /** Call this to distribute a touch down event to the stage. * @param x the x coordinate of the touch in screen coordinates * @param y the y coordinate of the touch in screen coordinates * @param pointer the pointer index * @param button the button that's been pressed - * @return whether an {@link Actor} in the scene processed the event or not - */ + * @return whether an {@link Actor} in the scene processed the event or not */ @Override public boolean touchDown (int x, int y, int pointer, int button) { toStageCoordinates(x, y, coords); @@ -231,14 +200,12 @@ public boolean touchDown (int x, int y, int pointer, int button) { return root.touchDown(point.x, point.y, pointer); } - /** - * Call this to distribute a touch Up event to the stage. + /** Call this to distribute a touch Up event to the stage. * * @param x the x coordinate of the touch in screen coordinates * @param y the y coordinate of the touch in screen coordinates * @param pointer the pointer index - * @return whether an {@link Actor} in the scene processed the event or not - */ + * @return whether an {@link Actor} in the scene processed the event or not */ @Override public boolean touchUp (int x, int y, int pointer, int button) { toStageCoordinates(x, y, coords); @@ -246,116 +213,92 @@ public boolean touchUp (int x, int y, int pointer, int button) { return root.touchUp(point.x, point.y, pointer); } - /** - * Call this to distribute a touch dragged event to the stage. + /** Call this to distribute a touch dragged event to the stage. * @param x the x coordinate of the touch in screen coordinates * @param y the y coordinate of the touch in screen coordinates * @param pointer the pointer index - * @return whether an {@link Actor} in the scene processed the event or not - */ + * @return whether an {@link Actor} in the scene processed the event or not */ @Override 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); } - - /** - * Call this to distribute a touch moved event to the stage. This event will - * only ever appear on the desktop. + + /** Call this to distribute a touch moved event to the stage. This event will only ever appear on the desktop. * @param x the x coordinate of the touch in screen coordinates * @param y the y coordinate of the touch in screen coordinates - * @return whether an {@link Actor} in the scene processed the event or not - */ + * @return whether an {@link Actor} in the scene processed the event or not */ @Override - public boolean touchMoved(int x, int y) { + public boolean touchMoved (int x, int y) { toStageCoordinates(x, y, coords); Group.toChildCoordinates(root, coords.x, coords.y, point); return root.touchMoved(point.x, point.y); } - - /** - * Call this to distribute a mouse scroll event to the stage. This event will - * only ever appear on the desktop. + + /** Call this to distribute a mouse scroll event to the stage. This event will only ever appear on the desktop. * @param amount the scroll amount. - * @return whether an {@link Actor} in the scene processed the event or not. - */ + * @return whether an {@link Actor} in the scene processed the event or not. */ @Override - public boolean scrolled(int amount) { + public boolean scrolled (int amount) { return root.scrolled(amount); } - - /** - * Called when a key was pressed + + /** Called when a key was pressed * * @param keycode one of the constants in {@link Keys} - * @return whether the input was processed - */ + * @return whether the input was processed */ @Override public boolean keyDown (int keycode) { return root.keyDown(keycode); } - /** - * Called when a key was released + /** Called when a key was released * * @param keycode one of the constants in {@link Keys} - * @return whether the input was processed - */ + * @return whether the input was processed */ @Override public boolean keyUp (int keycode) { return root.keyUp(keycode); } - /** - * Called when a key was typed + /** Called when a key was typed * * @param character The character - * @return whether the input was processed - */ + * @return whether the input was processed */ @Override public boolean keyTyped (char character) { return root.keyTyped(character); } - /** - * Calls the {@link Actor#act(float)} method of all contained Actors. This will advance any {@link Action}s active for an + /** Calls the {@link Actor#act(float)} method of all contained Actors. This will advance any {@link Action}s active for an * Actor. - * @param delta the delta time in seconds since the last invocation - */ + * @param delta the delta time in seconds since the last invocation */ public void act (float delta) { root.act(delta); } - /** - * Renders the stage - */ + /** Renders the stage */ public void draw () { camera.update(); - batch.setProjectionMatrix(camera.combined); + batch.setProjectionMatrix(camera.combined); batch.begin(); root.draw(batch, 1); batch.end(); } - /** - * Disposes the stage - */ + /** Disposes the stage */ public void dispose () { batch.dispose(); } - /** - * Adds an {@link Actor} to this stage - * @param actor the Actor - */ + /** Adds an {@link Actor} to this stage + * @param actor the Actor */ public void addActor (Actor actor) { root.addActor(actor); } - /** - * @return the Stage graph as a silly string - */ + /** @return the Stage graph as a silly string */ public String graphToString () { StringBuilder buffer = new StringBuilder(); graphToString(buffer, root, 0); @@ -376,93 +319,71 @@ private void graphToString (StringBuilder buffer, Actor actor, int level) { } } - /** - * @return the root {@link Group} of this Stage. - */ + /** @return the root {@link Group} of this Stage. */ public Group getRoot () { return root; } - /** - * @return the {@link SpriteBatch} offers its {@link Actor}s for rendering. - */ + /** @return the {@link SpriteBatch} offers its {@link Actor}s for rendering. */ public SpriteBatch getSpriteBatch () { return batch; } - - /** - * @return the {@link Camera} of this stage. - */ - public Camera getCamera() { + + /** @return the {@link Camera} of this stage. */ + public Camera getCamera () { return camera; } - - /** - * Sets the {@link Camera} this stage uses. You are responsible for setting - * it up properly! The {@link Stage#draw()} will call the Camera's update() method - * and use it's combined matrix as the projection matrix for the SpriteBatch. - * @param camera the {@link Camera} - */ - public void setCamera(Camera camera) { + + /** Sets the {@link Camera} this stage uses. You are responsible for setting it up properly! The {@link Stage#draw()} will call + * the Camera's update() method and use it's combined matrix as the projection matrix for the SpriteBatch. + * @param camera the {@link Camera} */ + public void setCamera (Camera camera) { this.camera = camera; } - /** - * @return the {@link Actor} last hit by a touch event. - */ + /** @return the {@link Actor} last hit by a touch event. */ public Actor getLastTouchedChild () { return root.lastTouchedChild; } - /** - * Returns the {@link Actor} intersecting with the point (x,y) in stage coordinates. Hit testing is performed in the order the + /** Returns the {@link Actor} intersecting with the point (x,y) in stage coordinates. Hit testing is performed in the order the * Actors were inserted into the Stage, last inserted Actors being tested first. To get stage coordinates from screen * coordinates use {@link #toStageCoordinates(int, int, Vector2)}. * * @param x the x-coordinate in stage coordinates * @param y the y-coordinate in stage coordinates - * @return the hit Actor or null - */ + * @return the hit Actor or null */ public Actor hit (float x, float y) { Group.toChildCoordinates(root, x, y, point); return root.hit(point.x, point.y); } final Vector3 tmp = new Vector3(); - /** - * Transforms the given screen coordinates to stage coordinates + + /** Transforms the given screen coordinates to stage coordinates * @param x the x-coordinate in screen coordinates * @param y the y-coordinate in screen coordinates - * @param out the output {@link Vector2}. - */ + * @param out the output {@link Vector2}. */ public void toStageCoordinates (int x, int y, Vector2 out) { camera.unproject(tmp.set(x, y, 0)); out.x = tmp.x; out.y = tmp.y; } - - /** - * Clears this stage, removing all {@link Actor}s and {@link Group}s. - */ - public void clear() { + + /** Clears this stage, removing all {@link Actor}s and {@link Group}s. */ + public void clear () { root.clear(); } - - /** - * Removes the given {@link Actor} from the stage by trying to find it - * recursively in the scenegraph. - * @param actor the actor - */ - public void removeActor(Actor actor) { + + /** Removes the given {@link Actor} from the stage by trying to find it recursively in the scenegraph. + * @param actor the actor */ + public void removeActor (Actor actor) { root.removeActorRecursive(actor); } - - /** - * Unfocues all {@link Actor} instance currently focused. You should - * call this in case your app resumes to clear up any pressed states. - * Make sure the Actors forget their states as well! - */ - public void unfocusAll() { + + /** Unfocues all {@link Actor} instance currently focused. You should call this in case your app resumes to clear up any pressed + * states. Make sure the Actors forget their states as well! */ + public void unfocusAll () { root.unfocusAll(); - } + } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/TemporalAction.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/TemporalAction.java index faf2e2e68fb..a8e5fd665ab 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/TemporalAction.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/TemporalAction.java @@ -13,23 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d; -/** - * A {@link TemporalAction} controls an {@link Action} by repeating, delaying etc. the effect of an {@link Action}. +/** A {@link TemporalAction} controls an {@link Action} by repeating, delaying etc. the effect of an {@link Action}. * - * @author Moritz Post - */ + * @author Moritz Post */ public abstract class TemporalAction extends Action { protected Action action; protected Actor target; - /** - * Gets the {@link Action} that is controlled by this {@link TemporalAction}. + /** Gets the {@link Action} that is controlled by this {@link TemporalAction}. * - * @return the {@link Action} under control - */ + * @return the {@link Action} under control */ public Action getAction () { return action; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ActionResetingPool.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ActionResetingPool.java index d0d2942b013..9f42c44bca2 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ActionResetingPool.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ActionResetingPool.java @@ -13,24 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.utils.Pool; -/** - * A pool taking care of the {@link Action} life cycle and resets all its properties when obtained from this pool. +/** A pool taking care of the {@link Action} life cycle and resets all its properties when obtained from this pool. * * @author Moritz Post - * @param the type action to manage - */ + * @param the type action to manage */ public abstract class ActionResetingPool extends Pool { public ActionResetingPool (int initialCapacity, int max) { super(initialCapacity, max); } - @Override public T obtain () { + @Override + public T obtain () { T elem = super.obtain(); elem.reset(); return elem; 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 207b591bbb9..596269f7d39 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Delay.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Delay.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -20,14 +21,15 @@ public class Delay extends Action { static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected Delay newObject () { + @Override + protected Delay newObject () { return new Delay(); } }; protected float taken; protected float duration; - protected Action action; + protected Action action; public static Delay $ (Action action, float duration) { Delay delay = pool.obtain(); @@ -36,39 +38,46 @@ public class Delay extends Action { return delay; } - @Override public void reset () { + @Override + public void reset () { super.reset(); } - @Override public void setTarget (Actor 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) { callActionCompletedListener(); action.act(delta); - if(action.isDone()) action.callActionCompletedListener(); + if (action.isDone()) action.callActionCompletedListener(); } } - @Override public boolean isDone () { + @Override + public boolean isDone () { return taken > duration && action.isDone(); } - @Override public void finish () { + @Override + public void finish () { pool.free(this); action.finish(); super.finish(); } - @Override public Action copy () { + @Override + public Action copy () { return $(action.copy(), duration); } - @Override public Actor getTarget () { - return action.getTarget(); + @Override + public Actor getTarget () { + return action.getTarget(); } } 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 2b89e0b2e22..180d4f89d79 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeIn.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeIn.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class FadeIn extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected FadeIn newObject () { + @Override + protected FadeIn newObject () { return new FadeIn(); } }; @@ -37,7 +39,8 @@ public class FadeIn extends AnimationAction { 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 = 1 - this.target.color.a; @@ -46,7 +49,8 @@ public class FadeIn extends AnimationAction { } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.color.a = 1.0f; @@ -55,17 +59,18 @@ public class FadeIn extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { pool.free(this); if (listener != null) { listener.completed(this); } } - @Override public Action copy () { + @Override + public Action copy () { FadeIn fadeIn = $(duration); - if(interpolator != null) - fadeIn.setInterpolator(interpolator.copy()); + if (interpolator != null) fadeIn.setInterpolator(interpolator.copy()); return fadeIn; } } 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 b134e8d721d..4fb362a1bc9 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeOut.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeOut.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class FadeOut extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected FadeOut newObject () { + @Override + protected FadeOut newObject () { return new FadeOut(); } }; @@ -37,7 +39,8 @@ public class FadeOut extends AnimationAction { 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 = -this.target.color.a; @@ -45,7 +48,8 @@ public class FadeOut extends AnimationAction { this.done = false; } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.color.a = 0.0f; @@ -54,15 +58,16 @@ public class FadeOut extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { super.finish(); pool.free(this); } - @Override public Action copy () { + @Override + public Action copy () { FadeOut fadeOut = $(duration); - if(interpolator != null) - fadeOut.setInterpolator(interpolator.copy()); + if (interpolator != null) fadeOut.setInterpolator(interpolator.copy()); return fadeOut; } } 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 47a98d66123..ff6b2d1a245 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/FadeTo.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class FadeTo extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected FadeTo newObject () { + @Override + protected FadeTo newObject () { return new FadeTo(); } }; @@ -39,7 +41,8 @@ public class FadeTo extends AnimationAction { 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; @@ -47,7 +50,8 @@ public class FadeTo extends AnimationAction { this.done = false; } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.color.a = toAlpha; @@ -57,15 +61,16 @@ public class FadeTo extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { super.finish(); pool.free(this); } - @Override public Action copy () { + @Override + public Action copy () { FadeTo fadeTo = $(toAlpha, duration); - if(interpolator != null) - fadeTo.setInterpolator(interpolator.copy()); + if (interpolator != null) fadeTo.setInterpolator(interpolator.copy()); return fadeTo; } } 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 87edfa4b246..c504e0cd1bc 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Forever.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Forever.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -21,7 +22,8 @@ public class Forever extends TemporalAction { static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected Forever newObject () { + @Override + protected Forever newObject () { return new Forever(); } }; @@ -32,12 +34,14 @@ public class Forever extends TemporalAction { return forever; } - @Override public void setTarget (Actor actor) { + @Override + public void setTarget (Actor actor) { action.setTarget(actor); target = actor; } - @Override public void act (float delta) { + @Override + public void act (float delta) { action.act(delta); if (action.isDone()) { Action oldAction = action; @@ -47,21 +51,25 @@ public class Forever extends TemporalAction { } } - @Override public boolean isDone () { + @Override + public boolean isDone () { return false; } - @Override public void finish () { + @Override + public void finish () { pool.free(this); action.finish(); super.finish(); } - @Override public Action copy () { + @Override + public Action copy () { return $(action.copy()); } - @Override public Actor getTarget () { + @Override + public Actor getTarget () { return target; } } 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 c8d82815c58..734402ca4cc 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveBy.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveBy.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class MoveBy extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected MoveBy newObject () { + @Override + protected MoveBy newObject () { return new MoveBy(); } }; @@ -45,7 +47,8 @@ public class MoveBy extends AnimationAction { 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; @@ -57,7 +60,8 @@ public class MoveBy extends AnimationAction { this.done = false; } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.x = x; @@ -68,15 +72,16 @@ public class MoveBy extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { super.finish(); pool.free(this); } - @Override public Action copy () { + @Override + public Action copy () { MoveBy moveBy = $(initialX, initialY, duration); - if(interpolator != null) - moveBy.setInterpolator(interpolator.copy()); + if (interpolator != null) moveBy.setInterpolator(interpolator.copy()); return moveBy; } } 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 0ac62172a86..c347f80d1e9 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/MoveTo.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class MoveTo extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected MoveTo newObject () { + @Override + protected MoveTo newObject () { return new MoveTo(); } }; @@ -43,7 +45,8 @@ public class MoveTo extends AnimationAction { 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; @@ -53,7 +56,8 @@ public class MoveTo extends AnimationAction { this.done = false; } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.x = x; @@ -64,15 +68,16 @@ public class MoveTo extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { super.finish(); pool.free(this); } - @Override public Action copy () { + @Override + public Action copy () { MoveTo moveTo = $(x, y, duration); - if(interpolator != null) - moveTo.setInterpolator(interpolator.copy()); + if (interpolator != null) moveTo.setInterpolator(interpolator.copy()); return moveTo; } } 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 959004ca4d5..6ba57467627 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Parallel.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class Parallel extends CompositeAction { static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected Parallel newObject () { + @Override + protected Parallel newObject () { return new Parallel(); } }; @@ -33,7 +35,8 @@ public class Parallel extends CompositeAction { public static Parallel $ (Action... actions) { Parallel parallel = pool.obtain(); parallel.actions.clear(); - if (parallel.finished == null || parallel.finished.length < actions.length) parallel.finished = new boolean[actions.length]; + if (parallel.finished == null || parallel.finished.length < actions.length) + parallel.finished = new boolean[actions.length]; int len = actions.length; for (int i = 0; i < len; i++) parallel.finished[i] = false; @@ -43,14 +46,16 @@ public class Parallel extends CompositeAction { return parallel; } - @Override public void setTarget (Actor actor) { + @Override + public void setTarget (Actor actor) { this.target = actor; int len = actions.size(); 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(); boolean allDone = true; Action action; @@ -67,17 +72,19 @@ public class Parallel extends CompositeAction { } } } - if(allDone) callActionCompletedListener(); + if (allDone) callActionCompletedListener(); } - @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; return true; } - @Override public void finish () { + @Override + public void finish () { pool.free(this); int len = actions.size(); for (int i = 0; i < len; i++) { @@ -85,11 +92,13 @@ public class Parallel extends CompositeAction { } super.finish(); } - - @Override public Action copy () { + + @Override + public Action copy () { Parallel parallel = pool.obtain(); parallel.actions.clear(); - if (parallel.finished == null || parallel.finished.length < actions.size()) parallel.finished = new boolean[actions.size()]; + if (parallel.finished == null || parallel.finished.length < actions.size()) + parallel.finished = new boolean[actions.size()]; int len = actions.size(); for (int i = 0; i < len; i++) parallel.finished[i] = false; @@ -98,8 +107,9 @@ public class Parallel extends CompositeAction { parallel.actions.add(actions.get(i).copy()); return parallel; } - - @Override public Actor getTarget () { + + @Override + public Actor getTarget () { return target; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Remove.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Remove.java index 922422f101d..141eb01fd05 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Remove.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Remove.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -20,42 +21,48 @@ public class Remove extends Action { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected Remove newObject () { + @Override + protected Remove newObject () { return new Remove(); } }; - + protected Actor target; - protected boolean removed = false; - - static public Remove $() { + protected boolean removed = false; + + static public Remove $ () { Remove remove = pool.obtain(); remove.removed = false; remove.target = null; return remove; } - - @Override public void setTarget (Actor actor) { + + @Override + public void setTarget (Actor actor) { this.target = actor; } - @Override public void act (float delta) { - if(!removed) { + @Override + public void act (float delta) { + if (!removed) { target.markToRemove(true); removed = true; callActionCompletedListener(); } } - @Override public boolean isDone () { + @Override + public boolean isDone () { return removed; } - @Override public Action copy () { + @Override + public Action copy () { return $(); } - @Override public Actor getTarget () { + @Override + public Actor getTarget () { return target; } } 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 37e08e2c123..db330c395b6 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Repeat.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Repeat.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -21,7 +22,8 @@ public class Repeat extends TemporalAction { static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected Repeat newObject () { + @Override + protected Repeat newObject () { return new Repeat(); } }; @@ -36,18 +38,21 @@ public class Repeat extends TemporalAction { return repeat; } - @Override public void reset () { + @Override + public void reset () { super.reset(); finishedTimes = 0; listener = null; } - @Override public void setTarget (Actor actor) { + @Override + public void setTarget (Actor actor) { action.setTarget(actor); target = actor; } - @Override public void act (float delta) { + @Override + public void act (float delta) { action.act(delta); if (action.isDone()) { finishedTimes++; @@ -62,21 +67,25 @@ public class Repeat extends TemporalAction { } } - @Override public boolean isDone () { + @Override + public boolean isDone () { return finishedTimes >= times; } - @Override public void finish () { + @Override + public void finish () { pool.free(this); action.finish(); super.finish(); } - @Override public Action copy () { + @Override + public Action copy () { return $(action.copy(), times); } - @Override public Actor getTarget () { + @Override + public Actor getTarget () { return target; } } 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 99f32b32ab3..dbf5d0fbba0 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateBy.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateBy.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class RotateBy extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected RotateBy newObject () { + @Override + protected RotateBy newObject () { return new RotateBy(); } }; @@ -39,7 +41,8 @@ public class RotateBy extends AnimationAction { return action; } - @Override public void setTarget (Actor actor) { + @Override + public void setTarget (Actor actor) { this.target = actor; this.startRotation = target.rotation; this.deltaRotation = rotation; @@ -47,7 +50,8 @@ public class RotateBy extends AnimationAction { this.done = false; } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.rotation = startRotation + rotation; @@ -56,15 +60,16 @@ public class RotateBy extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { super.finish(); pool.free(this); } - @Override public Action copy () { + @Override + public Action copy () { RotateBy rotateBy = $(rotation, duration); - if(interpolator != null) - rotateBy.setInterpolator(interpolator.copy()); + if (interpolator != null) rotateBy.setInterpolator(interpolator.copy()); return rotateBy; } } 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 e81ff62317b..7ee465b7bea 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/RotateTo.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class RotateTo extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected RotateTo newObject () { + @Override + protected RotateTo newObject () { return new RotateTo(); } }; @@ -39,7 +41,8 @@ public class RotateTo extends AnimationAction { 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; @@ -47,7 +50,8 @@ public class RotateTo extends AnimationAction { this.done = false; } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.rotation = rotation; @@ -56,15 +60,16 @@ public class RotateTo extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { super.finish(); pool.free(this); } - @Override public Action copy () { + @Override + public Action copy () { RotateTo rotateTo = $(rotation, duration); - if(interpolator != null) - rotateTo.setInterpolator(interpolator.copy()); + if (interpolator != null) rotateTo.setInterpolator(interpolator.copy()); return rotateTo; } } 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 c5f073f04ae..ab5dee55c11 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ScaleTo.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/ScaleTo.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; @@ -22,7 +23,8 @@ public class ScaleTo extends AnimationAction { private static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected ScaleTo newObject () { + @Override + protected ScaleTo newObject () { return new ScaleTo(); } }; @@ -43,7 +45,8 @@ public class ScaleTo extends AnimationAction { 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; @@ -53,7 +56,8 @@ public class ScaleTo extends AnimationAction { this.done = false; } - @Override public void act (float delta) { + @Override + public void act (float delta) { float alpha = createInterpolatedAlpha(delta); if (done) { target.scaleX = scaleX; @@ -64,15 +68,16 @@ public class ScaleTo extends AnimationAction { } } - @Override public void finish () { + @Override + public void finish () { super.finish(); pool.free(this); } - @Override public Action copy () { + @Override + public Action copy () { ScaleTo scaleTo = $(scaleX, scaleY, duration); - if(interpolator != null) - scaleTo.setInterpolator(interpolator.copy()); + if (interpolator != null) scaleTo.setInterpolator(interpolator.copy()); return scaleTo; } } 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 16066be147d..95f33399c7a 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actions/Sequence.java @@ -13,23 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.actions; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.CompositeAction; -import com.badlogic.gdx.scenes.scene2d.OnActionCompleted; public class Sequence extends CompositeAction { static final ActionResetingPool pool = new ActionResetingPool(4, 100) { - @Override protected Sequence newObject () { + @Override + protected Sequence newObject () { return new Sequence(); } }; protected Actor target; - protected int currAction = 0; + protected int currAction = 0; public static Sequence $ (Action... actions) { Sequence sequence = pool.obtain(); @@ -40,51 +41,57 @@ public class Sequence extends CompositeAction { return sequence; } - @Override public void setTarget (Actor actor) { + @Override + public void setTarget (Actor actor) { this.target = actor; if (actions.size() > 0) actions.get(0).setTarget(target); this.currAction = 0; } - @Override public void act (float delta) { + @Override + public void act (float delta) { if (actions.size() == 0) { currAction = 1; return; - } - - if(currAction >= actions.size()) { - callActionCompletedListener(); - return; } - + + if (currAction >= actions.size()) { + callActionCompletedListener(); + return; + } + actions.get(currAction).act(delta); if (actions.get(currAction).isDone()) { - actions.get(currAction).callActionCompletedListener(); + actions.get(currAction).callActionCompletedListener(); 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 () { + @Override + public void finish () { pool.free(this); super.finish(); } - @Override public Action copy () { + @Override + public Action copy () { Sequence action = pool.obtain(); 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; } - - @Override public Actor getTarget () { + + @Override + public Actor getTarget () { return target; } } 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 6e8d8aae484..c92930c0810 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/BoundGroup.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/BoundGroup.java @@ -13,16 +13,14 @@ * 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.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; -/** - * This is a group that respects its width and height. Useful for implementing layouts. - * @author mzechner - * - */ +/** 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); 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 12ca8b9e6ed..57e712177ae 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Button.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Button.java @@ -13,21 +13,18 @@ * 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.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Layout; -/** - * A simple Button {@link Actor}, useful for simple UIs - * - * @author mzechner +/** A simple Button {@link Actor}, useful for simple UIs * - */ + * @author mzechner */ public class Button extends Actor implements Layout { public interface ClickListener { public void clicked (Button button); @@ -39,22 +36,18 @@ public interface ClickListener { public boolean pressed = false; protected int pointer = -1; - /** - * Creates a new Button instance with the given name. - * @param name the name - */ + /** Creates a new Button instance with the given name. + * @param name the name */ public Button (String name) { super(name); this.pressedRegion = new TextureRegion(); this.unpressedRegion = new TextureRegion(); } - /** - * Creates a new Button instance with the given name, using the complete supplied texture for displaying the pressed and + /** Creates a new Button instance with the given name, using the complete supplied texture for displaying the pressed and * unpressed state of the button. * @param name the name - * @param texture the {@link Texture} - */ + * @param texture the {@link Texture} */ public Button (String name, Texture texture) { super(name); originX = texture.getWidth() / 2.0f; @@ -79,7 +72,8 @@ public Button (String name, TextureRegion unpressedRegion, TextureRegion pressed this.pressedRegion = new TextureRegion(pressedRegion); } - @Override public void draw (SpriteBatch batch, float parentAlpha) { + @Override + public void draw (SpriteBatch batch, float parentAlpha) { TextureRegion region = pressed ? pressedRegion : unpressedRegion; batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); if (region.getTexture() != null) { @@ -90,12 +84,13 @@ public Button (String name, TextureRegion unpressedRegion, TextureRegion pressed } } - @Override public boolean touchDown (float x, float y, int pointer) { - if(pressed) return false; + @Override + public boolean touchDown (float x, float y, int pointer) { + if (pressed) return false; boolean result = x > 0 && y > 0 && x < width && y < height; pressed = result; - + if (pressed) { parent.focus(this, pointer); this.pointer = pointer; @@ -103,10 +98,11 @@ public Button (String name, TextureRegion unpressedRegion, TextureRegion pressed return result; } - @Override public boolean touchUp (float x, float y, int pointer) { + @Override + public boolean touchUp (float x, float y, int pointer) { if (!pressed) return false; - if(pointer == this.pointer) { + if (pointer == this.pointer) { parent.focus(null, pointer); } pressed = false; @@ -114,7 +110,8 @@ public Button (String name, TextureRegion unpressedRegion, TextureRegion pressed return true; } - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { return pressed; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/FastImage.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/FastImage.java index 89d7e56bd2a..b8c49963eda 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/FastImage.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/FastImage.java @@ -13,6 +13,7 @@ * 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.Texture; @@ -33,8 +34,8 @@ public class FastImage extends Actor { private float sScaleY; private float sWidth; private float sHeight; - private Sprite sprite = new Sprite(); - + private Sprite sprite = new Sprite(); + public FastImage (String name) { super(name); this.region = new TextureRegion(); @@ -46,7 +47,7 @@ public FastImage (String name, Texture texture) { this.originY = texture.getHeight() / 2.0f; this.width = texture.getWidth(); this.height = texture.getHeight(); - this.region = new TextureRegion(texture); + this.region = new TextureRegion(texture); } public FastImage (String name, TextureRegion region) { @@ -58,57 +59,61 @@ public FastImage (String name, TextureRegion region) { this.region = new TextureRegion(region); } - @Override public void draw (SpriteBatch batch, float parentAlpha) { + @Override + public void draw (SpriteBatch batch, float parentAlpha) { updateSprite(); - - if (region.getTexture() != null) { + + if (region.getTexture() != null) { sprite.draw(batch, parentAlpha); } } - - private void updateSprite() { - if(sX != x || sY != y) { + + private void updateSprite () { + if (sX != x || sY != y) { sprite.setPosition(x, y); sX = x; sY = y; } - - if(sOriginX != originX || sOriginY != originY) { + + if (sOriginX != originX || sOriginY != originY) { sprite.setOrigin(originX, originY); sOriginX = originX; sOriginY = originY; } - - if(sRotation != rotation) { + + if (sRotation != rotation) { sprite.setRotation(rotation); sRotation = rotation; } - - if(sScaleX != scaleX || sScaleY != scaleY) { + + if (sScaleX != scaleX || sScaleY != scaleY) { sprite.setScale(scaleX, scaleY); sScaleX = scaleX; sScaleY = scaleY; } - - if(sWidth != width || sHeight != height) { + + if (sWidth != width || sHeight != height) { sprite.setSize(width, height); sWidth = width; sHeight = height; } - + sprite.setColor(color); - sprite.setRegion(region); + sprite.setRegion(region); } - @Override public boolean touchDown (float x, float y, int pointer) { + @Override + public boolean touchDown (float x, float y, int pointer) { return x > 0 && y > 0 && x < width && y < height; } - @Override public boolean touchUp (float x, float y, int pointer) { + @Override + public boolean touchUp (float x, float y, int pointer) { return false; } - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { return false; } 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 f63016cb20f..44499919b1e 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Image.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Image.java @@ -13,6 +13,7 @@ * 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.Texture; @@ -45,7 +46,8 @@ public Image (String name, TextureRegion region) { this.region = new TextureRegion(region); } - @Override public void draw (SpriteBatch batch, float parentAlpha) { + @Override + public void draw (SpriteBatch batch, float parentAlpha) { if (region.getTexture() != null) { batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); if (scaleX == 1 && scaleY == 1 && rotation == 0) @@ -55,15 +57,18 @@ public Image (String name, TextureRegion region) { } } - @Override public boolean touchDown (float x, float y, int pointer) { + @Override + public boolean touchDown (float x, float y, int pointer) { return x > 0 && y > 0 && x < width && y < height; } - @Override public boolean touchUp (float x, float y, int pointer) { + @Override + public boolean touchUp (float x, float y, int pointer) { return false; } - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { return false; } 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 79633c8779b..687da6a2a1d 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Label.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/Label.java @@ -13,6 +13,7 @@ * 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.g2d.BitmapFont; @@ -83,7 +84,8 @@ public void setFont (BitmapFont font) { } } - @Override public void draw (SpriteBatch batch, float parentAlpha) { + @Override + public void draw (SpriteBatch batch, float parentAlpha) { cache.setColor(color.r, color.g, color.b, color.a * parentAlpha); switch (valign) { case TOP: @@ -105,22 +107,26 @@ public void setFont (BitmapFont font) { cache.draw(batch); } - @Override public boolean touchDown (float x, float y, int pointer) { + @Override + public boolean touchDown (float x, float y, int pointer) { if (!touchable) return false; return x > 0 && y > 0 && x < width && y < height; } - @Override public boolean touchUp (float x, float y, int pointer) { + @Override + public boolean touchUp (float x, float y, int pointer) { if (!touchable) return false; return x > 0 && y > 0 && x < width && y < height; } - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { if (!touchable) return false; return x > 0 && y > 0 && x < width && y < height; } - @Override public Actor hit (float x, float y) { + @Override + 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/LinearGroup.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/LinearGroup.java index 4619cfce3ff..632ceeab30b 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/LinearGroup.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/actors/LinearGroup.java @@ -13,6 +13,7 @@ * 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.scenes.scene2d.Actor; diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateDecelerateInterpolator.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateDecelerateInterpolator.java index 09b9388c309..015511e4dc8 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateDecelerateInterpolator.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateDecelerateInterpolator.java @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.interpolators; import com.badlogic.gdx.scenes.scene2d.Interpolator; import com.badlogic.gdx.utils.Pool; -/** - * An interpolator where the rate of change starts out slowly, grows over time and ends slowly. +/** An interpolator where the rate of change starts out slowly, grows over time and ends slowly. * - * @author Moritz Post - */ + * @author Moritz Post */ public class AccelerateDecelerateInterpolator implements Interpolator { private static final float DEFAULT_FACTOR = 1.0f; private static final Pool pool = new Pool(4, 100) { - @Override protected AccelerateDecelerateInterpolator newObject () { + @Override + protected AccelerateDecelerateInterpolator newObject () { return new AccelerateDecelerateInterpolator(); } }; @@ -41,12 +41,10 @@ public class AccelerateDecelerateInterpolator implements Interpolator { // hide constructor } - /** - * Gets a new {@link AccelerateDecelerateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link AccelerateDecelerateInterpolator} from a maintained pool of {@link Interpolator}s. * * @param factor the factor controlling the rate of speed change - * @return the obtained {@link AccelerateDecelerateInterpolator} - */ + * @return the obtained {@link AccelerateDecelerateInterpolator} */ public static AccelerateDecelerateInterpolator $ (float factor) { AccelerateDecelerateInterpolator inter = pool.obtain(); inter.factor = factor; @@ -54,18 +52,17 @@ public class AccelerateDecelerateInterpolator implements Interpolator { return inter; } - /** - * Gets a new {@link AccelerateDecelerateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link AccelerateDecelerateInterpolator} from a maintained pool of {@link Interpolator}s. *

        * The initial factor is set to {@value AccelerateDecelerateInterpolator#DEFAULT_FACTOR}. * - * @return the obtained {@link AccelerateDecelerateInterpolator} - */ + * @return the obtained {@link AccelerateDecelerateInterpolator} */ public static AccelerateDecelerateInterpolator $ () { return $(DEFAULT_FACTOR); } - @Override public void finished () { + @Override + public void finished () { pool.free(this); } @@ -73,7 +70,8 @@ public float getInterpolation (float input) { return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f; } - @Override public Interpolator copy () { + @Override + public Interpolator copy () { return $(factor); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateInterpolator.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateInterpolator.java index 88cfa02bd9b..46bacf693bb 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateInterpolator.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AccelerateInterpolator.java @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.interpolators; import com.badlogic.gdx.scenes.scene2d.Interpolator; import com.badlogic.gdx.utils.Pool; -/** - * An interpolator where the rate of change starts out slowly and then accelerates over time. +/** An interpolator where the rate of change starts out slowly and then accelerates over time. * - * @author Moritz Post - */ + * @author Moritz Post */ public class AccelerateInterpolator implements Interpolator { private static final float DEFAULT_FACTOR = 1.0f; private static final Pool pool = new Pool(4, 100) { - @Override protected AccelerateInterpolator newObject () { + @Override + protected AccelerateInterpolator newObject () { return new AccelerateInterpolator(); } }; @@ -41,12 +41,10 @@ public class AccelerateInterpolator implements Interpolator { // hide constructor } - /** - * Gets a new {@link AccelerateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link AccelerateInterpolator} from a maintained pool of {@link Interpolator}s. * * @param factor the factor controlling the rate of change - * @return the obtained {@link AccelerateInterpolator} - */ + * @return the obtained {@link AccelerateInterpolator} */ public static AccelerateInterpolator $ (float factor) { AccelerateInterpolator inter = pool.obtain(); inter.factor = factor; @@ -54,18 +52,17 @@ public class AccelerateInterpolator implements Interpolator { return inter; } - /** - * Gets a new {@link AccelerateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link AccelerateInterpolator} from a maintained pool of {@link Interpolator}s. *

        * The initial factor is set to {@value AccelerateInterpolator#DEFAULT_FACTOR}. * - * @return the obtained {@link AccelerateInterpolator} - */ + * @return the obtained {@link AccelerateInterpolator} */ public static AccelerateInterpolator $ () { return $(DEFAULT_FACTOR); } - @Override public void finished () { + @Override + public void finished () { pool.free(this); } @@ -77,7 +74,8 @@ public float getInterpolation (float input) { } } - @Override public Interpolator copy () { + @Override + public Interpolator copy () { return $(factor); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AnticipateInterpolator.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AnticipateInterpolator.java index 15cab344c6b..0a8e1694fe2 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AnticipateInterpolator.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/AnticipateInterpolator.java @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.interpolators; import com.badlogic.gdx.scenes.scene2d.Interpolator; import com.badlogic.gdx.utils.Pool; -/** - * An {@link Interpolator} where the changes start backwards and than spring forward as the time progresses. +/** An {@link Interpolator} where the changes start backwards and than spring forward as the time progresses. * - * @author Moritz Post - */ + * @author Moritz Post */ public class AnticipateInterpolator implements Interpolator { private static final float DEFAULT_TENSION = 2.0f; private static final Pool pool = new Pool(4, 100) { - @Override protected AnticipateInterpolator newObject () { + @Override + protected AnticipateInterpolator newObject () { return new AnticipateInterpolator(); } }; @@ -39,30 +39,27 @@ public class AnticipateInterpolator implements Interpolator { // hide from the world } - /** - * Gets a new {@link AnticipateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link AnticipateInterpolator} from a maintained pool of {@link Interpolator}s. * * @param tension the tension controlling the rate spring effect of the animation - * @return the obtained {@link AccelerateInterpolator} - */ + * @return the obtained {@link AccelerateInterpolator} */ public static AnticipateInterpolator $ (float tension) { AnticipateInterpolator inter = pool.obtain(); inter.tension = tension; return inter; } - /** - * Gets a new {@link AnticipateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link AnticipateInterpolator} from a maintained pool of {@link Interpolator}s. *

        * The initial tension is set to {@value AnticipateInterpolator#DEFAULT_TENSION}. * - * @return the obtained {@link AnticipateInterpolator} - */ + * @return the obtained {@link AnticipateInterpolator} */ public static AnticipateInterpolator $ () { return $(DEFAULT_TENSION); } - @Override public void finished () { + @Override + public void finished () { pool.free(this); } @@ -70,7 +67,8 @@ public float getInterpolation (float t) { return t * t * ((tension + 1) * t - tension); } - @Override public Interpolator copy () { + @Override + public Interpolator copy () { return $(tension); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/DecelerateInterpolator.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/DecelerateInterpolator.java index 525d2d86acd..ad1d4b3d2e0 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/DecelerateInterpolator.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/DecelerateInterpolator.java @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.interpolators; import com.badlogic.gdx.scenes.scene2d.Interpolator; import com.badlogic.gdx.utils.Pool; -/** - * An interpolator where the rate of change starts out fast and then decelerates over time. +/** An interpolator where the rate of change starts out fast and then decelerates over time. * - * @author Moritz Post - */ + * @author Moritz Post */ public class DecelerateInterpolator implements Interpolator { private static final float DEFAULT_FACTOR = 1.0f; private static final Pool pool = new Pool(4, 100) { - @Override protected DecelerateInterpolator newObject () { + @Override + protected DecelerateInterpolator newObject () { return new DecelerateInterpolator(); } }; @@ -41,12 +41,10 @@ public class DecelerateInterpolator implements Interpolator { // hide constructor } - /** - * Gets a new {@link DecelerateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link DecelerateInterpolator} from a maintained pool of {@link Interpolator}s. * * @param factor the factor controlling the rate of change - * @return the obtained {@link DecelerateInterpolator} - */ + * @return the obtained {@link DecelerateInterpolator} */ public static DecelerateInterpolator $ (float factor) { DecelerateInterpolator inter = pool.obtain(); inter.factor = factor; @@ -54,18 +52,17 @@ public class DecelerateInterpolator implements Interpolator { return inter; } - /** - * Gets a new {@link DecelerateInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link DecelerateInterpolator} from a maintained pool of {@link Interpolator}s. *

        * The initial factor is set to {@value DecelerateInterpolator#DEFAULT_FACTOR}. * - * @return the obtained {@link DecelerateInterpolator} - */ + * @return the obtained {@link DecelerateInterpolator} */ public static DecelerateInterpolator $ () { return $(DEFAULT_FACTOR); } - @Override public void finished () { + @Override + public void finished () { pool.free(this); } @@ -77,7 +74,8 @@ public float getInterpolation (float input) { } } - @Override public Interpolator copy () { + @Override + public Interpolator copy () { return $(factor); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/LinearInterpolator.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/LinearInterpolator.java index a3b97ae9f99..ad07f2b7d3f 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/LinearInterpolator.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/LinearInterpolator.java @@ -13,20 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.interpolators; import com.badlogic.gdx.scenes.scene2d.Interpolator; import com.badlogic.gdx.utils.Pool; -/** - * A very simple {@link Interpolator} which provides a linear progression by just returning the current input. +/** A very simple {@link Interpolator} which provides a linear progression by just returning the current input. * - * @author Moritz Post - */ + * @author Moritz Post */ public class LinearInterpolator implements Interpolator { private static final Pool pool = new Pool(4, 100) { - @Override protected LinearInterpolator newObject () { + @Override + protected LinearInterpolator newObject () { return new LinearInterpolator(); } }; @@ -35,24 +35,25 @@ public class LinearInterpolator implements Interpolator { // hide constructor } - /** - * Gets a new {@link LinearInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link LinearInterpolator} from a maintained pool of {@link Interpolator}s. * - * @return the obtained {@link LinearInterpolator} - */ + * @return the obtained {@link LinearInterpolator} */ public static LinearInterpolator $ () { return pool.obtain(); } - @Override public void finished () { + @Override + public void finished () { pool.free(this); } - @Override public float getInterpolation (float input) { + @Override + public float getInterpolation (float input) { return input; } - @Override public Interpolator copy () { + @Override + public Interpolator copy () { return $(); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/OvershootInterpolator.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/OvershootInterpolator.java index 921e7067298..d2f6c6f3bdb 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/OvershootInterpolator.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/interpolators/OvershootInterpolator.java @@ -13,24 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.interpolators; import com.badlogic.gdx.scenes.scene2d.Interpolator; import com.badlogic.gdx.utils.Pool; -/** - * An interpolator where the change overshoots the target and springs back to the target position. +/** An interpolator where the change overshoots the target and springs back to the target position. *

        * The factor defines the rate of overshoot. * - * @author Moritz Post - */ + * @author Moritz Post */ public class OvershootInterpolator implements Interpolator { private static final float DEFAULT_FACTOR = 1.0f; private static final Pool pool = new Pool(4, 100) { - @Override protected OvershootInterpolator newObject () { + @Override + protected OvershootInterpolator newObject () { return new OvershootInterpolator(); } }; @@ -43,12 +43,10 @@ public class OvershootInterpolator implements Interpolator { // hide constructor } - /** - * Gets a new {@link OvershootInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link OvershootInterpolator} from a maintained pool of {@link Interpolator}s. * * @param factor the factor controlling the rate of overshoot energy change - * @return the obtained {@link OvershootInterpolator} - */ + * @return the obtained {@link OvershootInterpolator} */ public static OvershootInterpolator $ (float factor) { OvershootInterpolator inter = pool.obtain(); inter.factor = factor; @@ -56,27 +54,27 @@ public class OvershootInterpolator implements Interpolator { return inter; } - /** - * Gets a new {@link OvershootInterpolator} from a maintained pool of {@link Interpolator}s. + /** Gets a new {@link OvershootInterpolator} from a maintained pool of {@link Interpolator}s. *

        * The initial factor is set to {@value OvershootInterpolator#DEFAULT_FACTOR}. * - * @return the obtained {@link OvershootInterpolator} - */ + * @return the obtained {@link OvershootInterpolator} */ public static OvershootInterpolator $ () { return $(DEFAULT_FACTOR); } - @Override public void finished () { + @Override + public void finished () { pool.free(this); } public float getInterpolation (float t) { - t -= 1.0f; - return t * t * ((factor + 1) * t + factor) + 1.0f; + t -= 1.0f; + return t * t * ((factor + 1) * t + factor) + 1.0f; } - @Override public Interpolator copy () { + @Override + public Interpolator copy () { return $(factor); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Button.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Button.java index a23a549525a..ca0624b8d40 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Button.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Button.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; @@ -22,24 +23,19 @@ import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; -/** - * A button with text on it. +/** A button with text on it. * - *

        Functionality

        - * A button can be either in a pressed or unpressed state. A {@link ClickListener} can - * be registered with the Button which will be called in case the button was clicked/touched. + *

        Functionality

        A button can be either in a pressed or unpressed state. A {@link ClickListener} can be registered with + * the Button which will be called in case the button was clicked/touched. * - *

        Layout

        - * The (preferred) width and height of a Button are derrived from the border patches in the - * background {@link NinePatch} as well as the bounding box around the multi-line text displayed - * on the Button. Use {@link Button#setPrefSize(int, int)} to programmatically change the size - * to your liking. In case the width and height you set are to small for the contained text you - * will see artifacts. + *

        Layout

        The (preferred) width and height of a Button are derrived from the border patches in the background + * {@link NinePatch} as well as the bounding box around the multi-line text displayed on the Button. Use + * {@link Button#setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set + * are to small for the contained text you will see artifacts. * - *

        Style

        - * A Button is a {@link Widget} displaying a background {@link NinePatch} as well as - * multi-line text with a specific font and color. The style is defined via an instance - * of {@link ButtonStyle}, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        A Button is a {@link Widget} displaying a background {@link NinePatch} as well as multi-line text with a + * specific font and color. The style is defined via an instance of {@link ButtonStyle}, which can be either done programmatically + * or via a {@link Skin}.

        * * A Button's style definition in a skin XML file should look like this: * @@ -54,41 +50,39 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newButton(String, String, String)}.
        • - *
        • The down attribute references a {@link NinePatch} by name, to be used as the button's background when it is pressed
        • - *
        • The up attribute references a {@link NinePatch} by name, to be used as the button's background when it is not pressed
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newButton(String, String, String)}.
        • + *
        • The down attribute references a {@link NinePatch} by name, to be used as the button's background when it is + * pressed
        • + *
        • The up attribute references a {@link NinePatch} by name, to be used as the button's background when it is not + * pressed
        • *
        • The font attribute references a {@link BitmapFont} by name, to be used to render the text on the button
        • *
        • The fontColor attribute references a {@link Color} by name, to be used to render the text on the button
        • - *
        + * * - * @author mzechner - * - */ + * @author mzechner */ public class Button extends Widget { final ButtonStyle style; - String text; - final TextBounds bounds = new TextBounds(); - boolean isPressed = false; + String text; + final TextBounds bounds = new TextBounds(); + boolean isPressed = false; ClickListener listener = null; - - /** - * Creates a new Button. The width and height of the Button are determined by its - * label test and style. + + /** Creates a new Button. The width and height of the Button are determined by its label test and style. * @param name the namen * @param label the label - * @param style the {@link ButtonStyle} - */ - public Button(String name, String label, ButtonStyle style) { - super(name, 0, 0); + * @param style the {@link ButtonStyle} */ + public Button (String name, String label, ButtonStyle style) { + super(name, 0, 0); this.style = style; this.text = label; layout(); this.width = prefWidth; this.height = prefHeight; - } - + } + @Override - public void layout() { + public void layout () { final BitmapFont font = style.font; final NinePatch downPatch = style.down; bounds.set(font.getMultiLineBounds(text)); @@ -97,107 +91,96 @@ public void layout() { prefWidth = downPatch.getLeftWidth() + downPatch.getRightWidth() + bounds.width; invalidated = false; } - + @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final BitmapFont font = style.font; final Color fontColor = style.fontColor; - final NinePatch downPatch = style.down; + final NinePatch downPatch = style.down; final NinePatch upPatch = style.up; - - if(invalidated) layout(); - + + if (invalidated) layout(); + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - if(isPressed) downPatch.draw(batch, x, y, width, height); - else upPatch.draw(batch, x, y, width, height); - + if (isPressed) + downPatch.draw(batch, x, y, width, height); + else + upPatch.draw(batch, x, y, width, height); + float textY = (int)(height * 0.5f) + (int)(bounds.height * 0.5f); font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); font.drawMultiLine(batch, text, x + (int)(width * 0.5f), y + textY, 0, HAlignment.CENTER); } @Override - public boolean touchDown(float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { isPressed = true; - parent.focus(this, pointer); + parent.focus(this, pointer); return true; } return false; } @Override - public boolean touchUp(float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { - if(listener != null) listener.click(this); + public boolean touchUp (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { + if (listener != null) listener.click(this); parent.focus(null, pointer); isPressed = false; return true; - } + } isPressed = false; parent.focus(null, pointer); return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { - if(pointer != 0) return false; + public boolean touchDragged (float x, float y, int pointer) { + if (pointer != 0) return false; return isPressed; - } - - /** - * Defines a button style, see {@link Button} - * @author mzechner - * - */ + } + + /** Defines a button style, see {@link Button} + * @author mzechner */ public static class ButtonStyle { public final NinePatch down; public final NinePatch up; public final BitmapFont font; - public final Color fontColor; - - public ButtonStyle(BitmapFont font, Color fontColor, NinePatch down, NinePatch up) { + public final Color fontColor; + + public ButtonStyle (BitmapFont font, Color fontColor, NinePatch down, NinePatch up) { this.font = font; this.fontColor = fontColor; this.down = down; this.up = up; } } - - /** - * Interface for listening to click events of a button. - * @author mzechner - * - */ + + /** Interface for listening to click events of a button. + * @author mzechner */ public interface ClickListener { - public void click(Button button); + public void click (Button button); } - - /** - * Sets the multi-line label text of this button. Causes invalidation - * of all parents. - * @param text - */ - public void setText(String text) { + + /** Sets the multi-line label text of this button. Causes invalidation of all parents. + * @param text */ + public void setText (String text) { this.text = text; invalidateHierarchy(); } - - /** - * @return the label text of this button - */ - public String getText() { + + /** @return the label text of this button */ + public String getText () { return text; } - - /** - * Sets the {@link ClickListener} of this button + + /** Sets the {@link ClickListener} of this button * @param listener the listener or null - * @return this Button for chaining - */ - public Button setClickListener(ClickListener listener) { + * @return this Button for chaining */ + public Button setClickListener (ClickListener listener) { this.listener = listener; return this; } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/CheckBox.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/CheckBox.java index 7df3eb1ae56..9f624daf3bd 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/CheckBox.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/CheckBox.java @@ -13,44 +13,39 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; -import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; -/** - * A checkbox with a label. +/** A checkbox with a label. * - *

        Functionality

        - * A CheckBox can be either checked or unchecked. The state of the CheckBox is displayed - * with images representing the checked and unchecked state as well as a label, displayed to the right of the - * image(s). Checking/unchecking a CheckBox works by clicking either the image or the label itself, the hit - * area of the CheckBox is the compositum of both elements.

        + *

        Functionality

        A CheckBox can be either checked or unchecked. The state of the CheckBox is displayed with images + * representing the checked and unchecked state as well as a label, displayed to the right of the image(s). Checking/unchecking a + * CheckBox works by clicking either the image or the label itself, the hit area of the CheckBox is the compositum of both + * elements.

        * - * To get notifications about a change in state of the CheckBox one can register a {@link CheckedListener} with - * the CheckBox.

        + * To get notifications about a change in state of the CheckBox one can register a {@link CheckedListener} with the CheckBox.

        * - *

        Layout

        - * A CheckBox's (preferred) width and height is determined by the size of the bigger of the two images representing - * the state plus the bounding box around the (single-line) label. Both the image and the label are centered vertically. - * Use {@link CheckBox#setPrefSize(int, int)} to programmatically change the size to your liking. Note that this - * will not have an affect on the actual rendering, but only manipulate the hit area of the CheckBox. + *

        Layout

        A CheckBox's (preferred) width and height is determined by the size of the bigger of the two images + * representing the state plus the bounding box around the (single-line) label. Both the image and the label are centered + * vertically. Use {@link CheckBox#setPrefSize(int, int)} to programmatically change the size to your liking. Note that this will + * not have an affect on the actual rendering, but only manipulate the hit area of the CheckBox. * - *

        Style

        - * A CheckBox is a {@link Widget} displaying one of two {@link TextureRegion} instances representing the checked and - * unchecked state, as well as a label via a {@link BitmapFont} and accompanying {@link Color}. The style is defined - * via an instance of {@link CheckBoxStyle}, which can either be done programmatically or via a {@link Skin}.

        + *

        Style

        A CheckBox is a {@link Widget} displaying one of two {@link TextureRegion} instances representing the checked + * and unchecked state, as well as a label via a {@link BitmapFont} and accompanying {@link Color}. The style is defined via an + * instance of {@link CheckBoxStyle}, which can either be done programmatically or via a {@link Skin}.

        * * A CheckBox's style definition in a skin XML file should look like this: * - *
        + * 
          *  {@code 
          *  
          *  }
        - *  
        - * + *
        + * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newCheckBox(String, String, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newCheckBox(String, String, String)}.
        • *
        • The checked attribute references a {@link TextureRegion} by name, to be used when the CheckBox is checked
        • *
        • The unchecked attribute references a {@link TextureRegion} by name, to be used when the CheckBox is unchecked
        • *
        • The font attribute references a {@link BitmapFont} by name, to be used to render the label
        • *
        • The fontColor attribute references a {@link Color} by name, to be used to render the label
        • - *
        - * - * @author mzechner - * - */ + * + * + * @author mzechner */ public class CheckBox extends Widget { final CheckBoxStyle style; - String label; + String label; boolean isChecked = false; CheckedListener listener = null; - + final Vector2 boxPos = new Vector2(); final Vector2 textPos = new Vector2(); final TextBounds textBounds = new TextBounds(); final Rectangle bounds = new Rectangle(); float checkWidth = 0; - float checkHeight = 0; - - /** - * Creates a new check box. The width and height of the check box are - * determined by its label text and style. - * @param name the name + float checkHeight = 0; + + /** Creates a new check box. The width and height of the check box are determined by its label text and style. + * @param name the name * @param label the label - * @param style the {@link CheckBoxStyle} - */ - public CheckBox(String name, String label, CheckBoxStyle style) { + * @param style the {@link CheckBoxStyle} */ + public CheckBox (String name, String label, CheckBoxStyle style) { super(name, 0, 0); this.style = style; - this.label = label; + this.label = label; layout(); this.width = prefWidth; this.height = prefHeight; - } + } @Override - public void layout() { + public void layout () { final BitmapFont font = style.font; final TextureRegion checkedRegion = style.checked; final TextureRegion uncheckedRegion = style.unchecked; - + textBounds.set(font.getBounds(label)); textBounds.height -= font.getDescent(); checkWidth = Math.max(checkedRegion.getRegionWidth(), uncheckedRegion.getRegionWidth()); - checkHeight = Math.max(checkedRegion.getRegionHeight(), uncheckedRegion.getRegionHeight()); - if(textBounds.height > checkHeight) { + checkHeight = Math.max(checkedRegion.getRegionHeight(), uncheckedRegion.getRegionHeight()); + if (textBounds.height > checkHeight) { prefHeight = textBounds.height; boxPos.y = (int)((textBounds.height - checkedRegion.getRegionHeight()) / 2); textPos.y = textBounds.height; } else { - prefHeight = checkHeight; + prefHeight = checkHeight; boxPos.y = 0; textPos.y = (int)((checkHeight - textBounds.height) / 2) + textBounds.height; } - + boxPos.x = 0; textPos.x = checkWidth + 5; prefWidth = checkWidth + 5 + textBounds.width; @@ -127,78 +118,71 @@ public void layout() { } @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final BitmapFont font = style.font; final TextureRegion checkedRegion = style.checked; final TextureRegion uncheckedRegion = style.unchecked; final Color fontColor = style.fontColor; - - if(invalidated) layout(); - + + if (invalidated) layout(); + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - if(isChecked) batch.draw(checkedRegion, x + boxPos.x, y + boxPos.y); - else batch.draw(uncheckedRegion, x + boxPos.x, y + boxPos.y); - + if (isChecked) + batch.draw(checkedRegion, x + boxPos.x, y + boxPos.y); + else + batch.draw(uncheckedRegion, x + boxPos.x, y + boxPos.y); + font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); font.draw(batch, label, x + textPos.x, y + textPos.y); } @Override - public boolean touchDown(float x, float y, int pointer) { + public boolean touchDown (float x, float y, int pointer) { return false; } @Override - public boolean touchUp(float x, float y, int pointer) { - if(x >= 0 && x < width && - y >= 0 && y < height) { + public boolean touchUp (float x, float y, int pointer) { + if (x >= 0 && x < width && y >= 0 && y < height) { isChecked = !isChecked; - if(listener != null) listener.checked(this, isChecked); + if (listener != null) listener.checked(this, isChecked); } return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { + public boolean touchDragged (float x, float y, int pointer) { return false; } @Override - public Actor hit(float x, float y) { - return x > 0 && x < width && y > 0 && y < height?this: null; - } - - /** - * Interface for listening to check events on this check box. - * @author mzechner - * - */ + public Actor hit (float x, float y) { + return x > 0 && x < width && y > 0 && y < height ? this : null; + } + + /** Interface for listening to check events on this check box. + * @author mzechner */ public interface CheckedListener { - public void checked(CheckBox checkBox, boolean isChecked); + public void checked (CheckBox checkBox, boolean isChecked); } - - /** - * Sets the {@link CheckedListener} + + /** Sets the {@link CheckedListener} * @param listener the listener or null - * @return this CheckBox for chaining - */ - public CheckBox setCheckedListener(CheckedListener listener) { + * @return this CheckBox for chaining */ + public CheckBox setCheckedListener (CheckedListener listener) { this.listener = listener; return this; } - - /** - * Defines a check box style, see {@link CheckBox} - * @author mzechner - * - */ + + /** Defines a check box style, see {@link CheckBox} + * @author mzechner */ public static class CheckBoxStyle { public final BitmapFont font; public final Color fontColor; public final TextureRegion checked; public final TextureRegion unchecked; - - public CheckBoxStyle(BitmapFont font, Color fontColor, TextureRegion checked, TextureRegion unchecked) { + + public CheckBoxStyle (BitmapFont font, Color fontColor, TextureRegion checked, TextureRegion unchecked) { this.font = font; this.fontColor = fontColor; this.checked = checked; @@ -206,20 +190,15 @@ public CheckBoxStyle(BitmapFont font, Color fontColor, TextureRegion checked, Te } } - /** - * Sets whether this check box is checked or not. Invalidates - * all parents. - * @param isChecked checked or not - */ - public void setChecked (boolean isChecked) { + /** Sets whether this check box is checked or not. Invalidates all parents. + * @param isChecked checked or not */ + public void setChecked (boolean isChecked) { this.isChecked = isChecked; invalidateHierarchy(); } - - /** - * @return whether this checkbox is checked or not - */ - public boolean isChecked() { + + /** @return whether this checkbox is checked or not */ + public boolean isChecked () { return isChecked; } -} \ No newline at end of file +} diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ComboBox.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ComboBox.java index c854a4bf21f..7f1dfe4796f 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ComboBox.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ComboBox.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; @@ -23,43 +24,34 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; -import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle; import com.badlogic.gdx.scenes.scene2d.ui.utils.ScissorStack; -/** - * A dropdown or combo box. +/** A dropdown or combo box. * - *

        Functionality

        - * A ComboBox contains a list of Strings, with one of the strings being selected and displayed - * in the main area of the ComboBox. Clicking the ComboBox brings up a popup list showing all - * the entries. This popup list will grab the touch focus while it is displayed. This is achieved - * by temporarily adding a new Actor to the root of the Stage the ComboBox is contained in. As soon - * as an item is selected or a mouse click outside the area of the popup list is registered, the - * popup will disappear again and the focus is given back.

        + *

        Functionality

        A ComboBox contains a list of Strings, with one of the strings being selected and displayed in the main + * area of the ComboBox. Clicking the ComboBox brings up a popup list showing all the entries. This popup list will grab the touch + * focus while it is displayed. This is achieved by temporarily adding a new Actor to the root of the Stage the ComboBox is + * contained in. As soon as an item is selected or a mouse click outside the area of the popup list is registered, the popup will + * disappear again and the focus is given back.

        * - * A {@link SelectionListener} can be registered with the ComboBox to receive notification of - * selection changes.

        + * A {@link SelectionListener} can be registered with the ComboBox to receive notification of selection changes.

        * - *

        Layout

        - * A ComboBox's (preferred) width and height are determined by the border patches in the background + *

        Layout

        A ComboBox's (preferred) width and height are determined by the border patches in the background * {@link NinePatch} as well as the bounding box of the widest entry in the list of strings. Use - * {@link ComboBox#setPrefSize(int, int)} to change this size programmatically. In case the set - * size is to small to contain the widest entry, artifacts may appear.

        + * {@link ComboBox#setPrefSize(int, int)} to change this size programmatically. In case the set size is to small to contain the + * widest entry, artifacts may appear.

        + * + * The additional popup list will be positioned at the bottom edge of the ComboBox, displaying all entries. The width and size is + * governed by the background {@link NinePatch} of the popup list as well as the bounding box around the list entries. * - * The additional popup list will be positioned at the bottom edge of the ComboBox, displaying - * all entries. The width and size is governed by the background {@link NinePatch} of the popup - * list as well as the bounding box around the list entries. + *

        Style

        A ComboBox is a {@link Widget} displaying a background {@link NinePatch} as well as the selected list entry as a + * label via a {@link BitmapFont} and a corresponding {@link Color}. Additionally a popup menu might be displayed, using a + * {@link NinePatch} for the background, another {@link NinePatch} for highlighting the current selection and the same + * {@link BitmapFont} and Color used to display the selected entry in the actual ComboBox.

        * - *

        Style

        - * A ComboBox is a {@link Widget} displaying a background {@link NinePatch} as well as the selected - * list entry as a label via a {@link BitmapFont} and a corresponding {@link Color}. Additionally - * a popup menu might be displayed, using a {@link NinePatch} for the background, another {@link NinePatch} for - * highlighting the current selection and the same {@link BitmapFont} and Color used to display the - * selected entry in the actual ComboBox.

        + * The style is defined via an instance of the {@link ComboBoxStyle} class, which can be either done programmatically or via a + * {@link Skin}.

        * - * The style is defined via an instance of the {@link ComboBoxStyle} class, which can be either done programmatically - * or via a {@link Skin}.

        - * * A ComboBox's style definition in a skin XML file should look like this: * *
        @@ -74,19 +66,20 @@
          * 
        * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newComboBox(String, String[], Stage, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newComboBox(String, String[], Stage, String)}.
        • *
        • The background attribute references a {@link NinePatch} by name, to be used as the ComboBox's background
        • - *
        • The listBackground attribute references a {@link NinePatch} by name, to be used as the background for the popup list
        • - *
        • The listSelection attribute references a {@link NinePatch} by name, to be used for highlighting a selection in the popup list
        • + *
        • The listBackground attribute references a {@link NinePatch} by name, to be used as the background for the + * popup list
        • + *
        • The listSelection attribute references a {@link NinePatch} by name, to be used for highlighting a selection in + * the popup list
        • *
        • The font attribute references a {@link BitmapFont} by name, to be used to render the list entries
        • *
        • The fontColor attribute references a {@link Color} by name, to be used to render the list entries
        • *
        * - * @author mzechner - * - */ -public class ComboBox extends Widget { - final Stage stage; + * @author mzechner */ +public class ComboBox extends Widget { + final Stage stage; final ComboBoxStyle style; String[] entries; int selection = 0; @@ -94,66 +87,67 @@ public class ComboBox extends Widget { final Vector2 screenCoords = new Vector2(); ComboList list = null; SelectionListener listener; - - /** - * Creates a new combo box. The width and height are determined by the widets entry and - * the style. + + /** Creates a new combo box. The width and height are determined by the widets entry and the style. * @param name the name * @param entries the single-line entries * @param stage the stage, used for the popup - * @param style the {@link ComboBoxStyle} - */ - public ComboBox(String name, String[] entries, Stage stage, ComboBoxStyle style) { + * @param style the {@link ComboBoxStyle} */ + public ComboBox (String name, String[] entries, Stage stage, ComboBoxStyle style) { super(name, 0, 0); this.entries = entries; this.style = style; - this.stage = stage; + this.stage = stage; layout(); this.width = prefWidth; this.height = prefHeight; - } + } - @Override public void layout () { + @Override + public void layout () { final NinePatch background = style.background; final BitmapFont font = style.font; - + prefHeight = background.getTotalHeight(); float max = 0; - for(int i = 0; i < entries.length; i++) { + for (int i = 0; i < entries.length; i++) { max = Math.max(font.getBounds(entries[i]).width, max); } prefWidth = background.getLeftWidth() + background.getRightWidth() + max; - invalidated = false; + invalidated = false; } - @Override public void draw (SpriteBatch batch, float parentAlpha) { + @Override + public void draw (SpriteBatch batch, float parentAlpha) { final NinePatch background = style.background; final BitmapFont font = style.font; final Color fontColor = style.fontColor; - - if(invalidated) layout(); - + + if (invalidated) layout(); + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); background.draw(batch, x, y, width, height); - if(entries.length > 0) { + if (entries.length > 0) { float availableWidth = width - background.getLeftWidth() - background.getRightWidth(); int numGlyphs = font.computeVisibleGlyphs(entries[selection], 0, entries[selection].length(), availableWidth); bounds.set(font.getBounds(entries[selection])); bounds.height -= font.getDescent(); float textY = (int)(height / 2) + (int)(bounds.height / 2); font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); - font.draw(batch, entries[selection], x + background.getLeftWidth(), y + textY, 0, numGlyphs); + font.draw(batch, entries[selection], x + background.getLeftWidth(), y + textY, 0, numGlyphs); } - + // calculate screen coords where list should be displayed ScissorStack.toWindowCoordinates(stage.getCamera(), batch.getTransformMatrix(), screenCoords.set(x, y)); } Vector2 stageCoords = new Vector2(); - @Override public boolean touchDown (float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { - if(list != null) stage.removeActor(list); + + @Override + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { + if (list != null) stage.removeActor(list); stage.toStageCoordinates((int)screenCoords.x, (int)screenCoords.y, stageCoords); list = new ComboList(this.name + "-list", stageCoords.x, stageCoords.y); stage.addActor(list); @@ -162,59 +156,54 @@ public ComboBox(String name, String[] entries, Stage stage, ComboBoxStyle style) return false; } - @Override public boolean touchUp (float x, float y, int pointer) { + @Override + public boolean touchUp (float x, float y, int pointer) { return false; } - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { return false; } - - /** - * Defines the style of a combo box. See {@link ComboBox} - * @author mzechner - * - */ + + /** Defines the style of a combo box. See {@link ComboBox} + * @author mzechner */ public static class ComboBoxStyle { public final NinePatch background; - public final NinePatch listBackground; + public final NinePatch listBackground; public final NinePatch listSelection; public final BitmapFont font; public final Color fontColor = new Color(1, 1, 1, 1); - - public ComboBoxStyle(BitmapFont font, Color fontColor, NinePatch background, NinePatch listBackground, NinePatch listSelection) { + + public ComboBoxStyle (BitmapFont font, Color fontColor, NinePatch background, NinePatch listBackground, + NinePatch listSelection) { this.background = background; this.listBackground = listBackground; this.listSelection = listSelection; this.font = font; - this.fontColor.set(fontColor); + this.fontColor.set(fontColor); } } - - /** - * Interface for listening to selection events. - * @author mzechner - * - */ + + /** Interface for listening to selection events. + * @author mzechner */ public interface SelectionListener { - public void selected(ComboBox comboBox, int selectionIndex, String selection); + public void selected (ComboBox comboBox, int selectionIndex, String selection); } - - /** - * Sets the {@link SelectionListener}. - * @param listener the listener or null - */ - public void setSelectionListener(SelectionListener listener) { + + /** Sets the {@link SelectionListener}. + * @param listener the listener or null */ + public void setSelectionListener (SelectionListener listener) { this.listener = listener; } - + protected class ComboList extends Actor { Vector2 oldScreenCoords = new Vector2(); float entryHeight = 0; float textOffsetX = 0; float textOffsetY = 0; int selected = ComboBox.this.selection; - + public ComboList (String name, float x, float y) { super(name); this.x = x; @@ -226,46 +215,47 @@ public ComboList (String name, float x, float y) { layout(); } - private void layout() { + private void layout () { final BitmapFont font = style.font; final NinePatch listSelection = style.listSelection; - + float prefWidth = 0; float prefHeight = 0; - - for(int i = 0; i < entries.length; i++) { + + for (int i = 0; i < entries.length; i++) { String entry = entries[i]; TextBounds bounds = font.getBounds(entry); - prefWidth = Math.max(bounds.width, prefWidth); - + prefWidth = Math.max(bounds.width, prefWidth); + } - + entryHeight = font.getLineHeight() - font.getDescent(); entryHeight += listSelection.getTopHeight() + listSelection.getBottomHeight(); entryHeight *= ComboBox.this.parent.scaleY; - prefWidth += listSelection.getLeftWidth() + listSelection.getRightWidth(); + prefWidth += listSelection.getLeftWidth() + listSelection.getRightWidth(); prefHeight = entries.length * entryHeight; textOffsetX = listSelection.getLeftWidth(); textOffsetY = listSelection.getTopHeight() - font.getDescent(); - + width = Math.max(prefWidth, ComboBox.this.width); width *= ComboBox.this.parent.scaleX; height = prefHeight; y -= height; } - - @Override public void draw (SpriteBatch batch, float parentAlpha) { + + @Override + public void draw (SpriteBatch batch, float parentAlpha) { final NinePatch listBackground = style.listBackground; final NinePatch listSelection = style.listSelection; final BitmapFont font = style.font; final Color fontColor = style.fontColor; - + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); listBackground.draw(batch, x, y, width, height); float posY = height; - for(int i = 0; i < entries.length; i++) { - if(selected == i) { - listSelection.draw(batch, x, y + posY - entryHeight, width, entryHeight); + for (int i = 0; i < entries.length; i++) { + if (selected == i) { + listSelection.draw(batch, x, y + posY - entryHeight, width, entryHeight); } font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); font.setScale(ComboBox.this.parent.scaleX, ComboBox.this.parent.scaleY); @@ -273,79 +263,76 @@ private void layout() { font.setScale(1, 1); posY -= entryHeight; } - - if(screenCoords.x != oldScreenCoords.x || screenCoords.y != oldScreenCoords.y) { + + if (screenCoords.x != oldScreenCoords.x || screenCoords.y != oldScreenCoords.y) { stage.removeActor(this); } } - @Override public boolean touchDown (float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { - selected = (int)((height-y) / entryHeight); + @Override + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { + selected = (int)((height - y) / entryHeight); selected = Math.max(0, selected); - selected = Math.min(entries.length -1, selected); + selected = Math.min(entries.length - 1, selected); selection = selected; - if(entries.length > 0 && listener != null) listener.selected(ComboBox.this, selected, entries[selected]); - } + if (entries.length > 0 && listener != null) listener.selected(ComboBox.this, selected, entries[selected]); + } return true; } boolean firstUp = false; - @Override public boolean touchUp (float x, float y, int pointer) { - if(firstUp) { + + @Override + public boolean touchUp (float x, float y, int pointer) { + if (firstUp) { stage.removeActor(this); - } else firstUp = true; + } else + firstUp = true; return true; } - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { return true; } - - @Override public boolean touchMoved(float x, float y) { - if(hit(x, y) != null) { - selected = (int)((height-y) / entryHeight); + + @Override + public boolean touchMoved (float x, float y) { + if (hit(x, y) != null) { + selected = (int)((height - y) / entryHeight); selected = Math.max(0, selected); - selected = Math.min(entries.length -1, selected); + selected = Math.min(entries.length - 1, selected); } return true; } @Override - public Actor hit(float x, float y) { - return x > 0 && x < width && y > 0 && y < height?this: null; - } + public Actor hit (float x, float y) { + return x > 0 && x < width && y > 0 && y < height ? this : null; + } } - /** - * Sets the selected item via it's index - * @param selection the selection index - */ + /** Sets the selected item via it's index + * @param selection the selection index */ public void setSelection (int selection) { this.selection = selection; } - - /** - * @return the index of the current selection. The top entry has an index of 0 - */ - public int getSelectionIndex() { + + /** @return the index of the current selection. The top entry has an index of 0 */ + public int getSelectionIndex () { return selection; } - - /** - * @return the string of the currently selected entry - */ - public String getSelection() { + + /** @return the string of the currently selected entry */ + public String getSelection () { return entries[selection]; } - - /** - * Sets the entries of this combo box. Invalidates - * all parents. - * @param entries the entries - */ - public void setEntries(String[] entries) { + + /** Sets the entries of this combo box. Invalidates all parents. + * @param entries the entries */ + public void setEntries (String[] entries) { this.entries = entries; invalidateHierarchy(); } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/FlickScrollPane.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/FlickScrollPane.java index 5e63511b7fc..6a92dc4341c 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/FlickScrollPane.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/FlickScrollPane.java @@ -30,34 +30,26 @@ import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; import com.badlogic.gdx.scenes.scene2d.ui.utils.ScissorStack; -/** - * A special container that allows scrolling over its children, supporting - * scrolling by click/dragging anywhere and flick gestures. +/** A special container that allows scrolling over its children, supporting scrolling by click/dragging anywhere and flick + * gestures. * - *

        Functionality

        A ScrollPane can embed any {@link Actor} (and - * {@link Widget} or {@link Table} for that matter) and provide scrolling - * functionality in case the embedded Actor is bigger than the scroll pane - * itself. The scroll pane will automatically decide whether it needs a vertical - * and/or horizontal scroll handle based on the contained Actor's size with + *

        Functionality

        A ScrollPane can embed any {@link Actor} (and {@link Widget} or {@link Table} for that matter) and + * provide scrolling functionality in case the embedded Actor is bigger than the scroll pane itself. The scroll pane will + * automatically decide whether it needs a vertical and/or horizontal scroll handle based on the contained Actor's size with * respect to the scroll pane's own size.

        * - * Note: do not use any of the {@link #addActor(Actor)} or - * {@link #removeActor(Actor)} methods with this class! The embedded widget is - * specified at construction time or via {@link #setWidget(Actor)}. + * Note: do not use any of the {@link #addActor(Actor)} or {@link #removeActor(Actor)} methods with this class! The embedded + * widget is specified at construction time or via {@link #setWidget(Actor)}. * - *

        Layout

        The (preferred) width and height of a scroll pane is - * determined by the size passed to its constructor. The contained Actor will be - * positioned in such a way that it's top left corner will coincide with the - * scroll pane's corner when the vertical and horizontal scroll handles are at - * their minimum position.

        + *

        Layout

        The (preferred) width and height of a scroll pane is determined by the size passed to its constructor. The + * contained Actor will be positioned in such a way that it's top left corner will coincide with the scroll pane's corner when the + * vertical and horizontal scroll handles are at their minimum position.

        * - *

        Style

        A ScrollPane is a {@link Group} (note the comment in the - * functionality section!) that displays the embedded Actor, clipped to the - * available area inside of the scroll pane.

        + *

        Style

        A ScrollPane is a {@link Group} (note the comment in the functionality section!) that displays the embedded + * Actor, clipped to the available area inside of the scroll pane.

        * * @author mzechner - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class FlickScrollPane extends Group implements Layout { Actor widget; Stage stage; @@ -76,12 +68,11 @@ public class FlickScrollPane extends Group implements Layout { Vector2 lastPoint = new Vector2(); private boolean scrolling = false; - private long scrollingStarted; + private long scrollingStarted; private Vector2 scrollStartPoint = new Vector2(); public boolean overscrolls = false; - - public FlickScrollPane(String name, Stage stage, Actor widget, - int prefWidth, int prefHeight) { + + public FlickScrollPane (String name, Stage stage, Actor widget, int prefWidth, int prefHeight) { super(name); this.prefWidth = this.width = prefWidth; this.prefHeight = this.height = prefHeight; @@ -94,45 +85,39 @@ public FlickScrollPane(String name, Stage stage, Actor widget, Vector3 tmp = new Vector3(); - private void calculateBoundsAndPositions(Matrix4 batchTransform) { + private void calculateBoundsAndPositions (Matrix4 batchTransform) { // get available space size by subtracting background's // padded area hasHScroll = false; hasVScroll = false; // Figure out if we need horizontal/vertical scrollbars, - if (widget.width > width) - hasHScroll = true; - if (widget.height > height) - hasVScroll = true; + if (widget.width > width) hasHScroll = true; + if (widget.height > height) hasVScroll = true; // Set the widget area bounds widgetAreaBounds.set(0, 0, width, height); // Calculate the widgets offset depending on the scroll state and // available widget area. - widget.y = -(!hasVScroll ? (int) (widget.height - height) : 0) - - (hasVScroll ? (int) ((widget.height - height) * (1 - vScrollAmount)) - : 0); - widget.x = -(hasHScroll ? (int) ((widget.width - width) * hScrollAmount) - : 0); + widget.y = -(!hasVScroll ? (int)(widget.height - height) : 0) + - (hasVScroll ? (int)((widget.height - height) * (1 - vScrollAmount)) : 0); + widget.x = -(hasHScroll ? (int)((widget.width - width) * hScrollAmount) : 0); // Caculate the scissor bounds based on the batch transform, // the available widget area and the camera transform. We // need to project those to screen coordinates for OpenGL ES // to consume. This is pretty freaking nasty... - ScissorStack.calculateScissors(stage.getCamera(), batchTransform, - widgetAreaBounds, scissorBounds); + ScissorStack.calculateScissors(stage.getCamera(), batchTransform, widgetAreaBounds, scissorBounds); } @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { // setup transform for this group setupTransform(batch); // if invalidated layout! - if (invalidated) - layout(); + if (invalidated) layout(); // calculate the bounds for the scrollbars, the widget // area and the scissor area. Nasty... @@ -148,9 +133,9 @@ public void draw(SpriteBatch batch, float parentAlpha) { } @Override - public void layout() { + public void layout () { if (widget instanceof Layout) { - Layout layout = (Layout) widget; + Layout layout = (Layout)widget; widget.width = Math.max(width, layout.getPrefWidth()); widget.height = Math.max(height, layout.getPrefHeight()); layout.invalidate(); @@ -160,25 +145,24 @@ public void layout() { } @Override - public void invalidate() { - if (widget instanceof Layout) - ((Layout) widget).invalidate(); + public void invalidate () { + if (widget instanceof Layout) ((Layout)widget).invalidate(); invalidated = true; } @Override - public float getPrefWidth() { + public float getPrefWidth () { return prefWidth; } @Override - public float getPrefHeight() { + public float getPrefHeight () { return prefHeight; } @Override - public boolean touchDown(float x, float y, int pointer) { - if (pointer != 0 || !touchable | hit(x,y) == null ){ + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0 || !touchable | hit(x, y) == null) { Gdx.app.log("", "HERE d"); return false; } @@ -191,13 +175,11 @@ public boolean touchDown(float x, float y, int pointer) { return true; } - - @Override - public boolean touchUp(float x, float y, int pointer) { - + public boolean touchUp (float x, float y, int pointer) { + focus(null, 0); - + if (pointer != 0) { return false; } @@ -205,14 +187,10 @@ public boolean touchUp(float x, float y, int pointer) { if (scrolling) { scrolling = false; long timetaken = System.currentTimeMillis() - scrollingStarted; - float diffx = Math.max(scrollStartPoint.x, x) - - Math.min(scrollStartPoint.x, x); - float diffy = Math.max(scrollStartPoint.y, y) - - Math.min(scrollStartPoint.y, y); + float diffx = Math.max(scrollStartPoint.x, x) - Math.min(scrollStartPoint.x, x); + float diffy = Math.max(scrollStartPoint.y, y) - Math.min(scrollStartPoint.y, y); - System.out.println(String.format( - "Scrolled for %dms, %f on x, %f on y ", timetaken, diffx, - diffy)); + System.out.println(String.format("Scrolled for %dms, %f on x, %f on y ", timetaken, diffx, diffy)); if (vScrollAmount > 1f) { smoothScrollTo(0, 1f); @@ -250,24 +228,17 @@ else if (vScrollAmount < 0f) { else { float yaccel = diffy / timetaken; float xaccel = diffx / timetaken; - System.out.println(String.format("y accel %f x accel %f", - yaccel, xaccel)); + System.out.println(String.format("y accel %f x accel %f", yaccel, xaccel)); if (yaccel > 1 || xaccel > 1) { System.out.println("fling"); if (scrollStartPoint.y > y) { - smoothScrollTo( - hScrollAmount, - (Math.max(vScrollAmount + (1 / widget.height) - * -(diffy * 4), 0f)), - (int) (timetaken * 1.5)); + smoothScrollTo(hScrollAmount, (Math.max(vScrollAmount + (1 / widget.height) * -(diffy * 4), 0f)), + (int)(timetaken * 1.5)); } else { - smoothScrollTo( - hScrollAmount, - Math.min(vScrollAmount + (1 / widget.height) - * (diffy * 4), 1f), - (int) (timetaken * 1.5)); + smoothScrollTo(hScrollAmount, Math.min(vScrollAmount + (1 / widget.height) * (diffy * 4), 1f), + (int)(timetaken * 1.5)); } if (listener != null) { @@ -285,19 +256,18 @@ else if (vScrollAmount < 0f) { // } else } - + return super.touchUp(x, y, pointer); - + } @Override - public boolean touchDragged(float x, float y, int pointer) { - if (pointer != 0 || !touchable) - return false; + public boolean touchDragged (float x, float y, int pointer) { + if (pointer != 0 || !touchable) return false; if (scrolling) { if (hasHScroll) { hScrollAmount -= (x - lastPoint.x) / (widget.width - width); - if(overscrolls){ + if (overscrolls) { hScrollAmount = Math.max(0, hScrollAmount); hScrollAmount = Math.min(1, hScrollAmount); } @@ -305,7 +275,7 @@ public boolean touchDragged(float x, float y, int pointer) { if (hasVScroll) { vScrollAmount += (y - lastPoint.y) / (widget.height - height); - if(overscrolls){ + if (overscrolls) { vScrollAmount = Math.max(0, vScrollAmount); vScrollAmount = Math.min(1, vScrollAmount); } @@ -315,117 +285,109 @@ public boolean touchDragged(float x, float y, int pointer) { } Gdx.app.log("", "HERE dr!"); - + return false; } @Override - public Actor hit(float x, float y) { + public Actor hit (float x, float y) { return x > 0 && x < width && y > 0 && y < height ? this : null; } - /** - * Sets the {@link Actor} embedded in this scroll pane. + /** Sets the {@link Actor} embedded in this scroll pane. * - * @param widget - * the Actor - */ - public void setWidget(Actor widget) { - if (widget == null) - throw new IllegalArgumentException("widget must not be null"); + * @param widget the Actor */ + public void setWidget (Actor widget) { + if (widget == null) throw new IllegalArgumentException("widget must not be null"); this.removeActor(this.widget); this.widget = widget; this.addActor(widget); invalidate(); } - - - public void scrollHorizontalTo(float scroll){ + + public void scrollHorizontalTo (float scroll) { Gdx.app.log("", "scrollHorizontalTo"); hScrollAmount = scroll; } - - public float getHorizontalScrollAmount(){ + + public float getHorizontalScrollAmount () { return hScrollAmount; } - - public void scrollVerticalTo(float scroll){ + + public void scrollVerticalTo (float scroll) { vScrollAmount = scroll; } - - public float getVerticalScrollAmount(){ + + public float getVerticalScrollAmount () { return vScrollAmount; } - + float scrolledtime = 0; private static final int SCROLLTIMEDEFAULT = 350; - int scrolltime = SCROLLTIMEDEFAULT; + int scrolltime = SCROLLTIMEDEFAULT; float scrollstarth; float scrollstartv; float smoothscrolldesty = -1; float smoothscrolldestx = -1; DecelerateInterpolator interpolator = DecelerateInterpolator.$(); - - public void smoothScrollTo(float horizontal, float vertical){ + + public void smoothScrollTo (float horizontal, float vertical) { smoothScrollTo(horizontal, vertical, SCROLLTIMEDEFAULT); } - - public void smoothScrollTo(float horizontal, float vertical, int duration){ - - //Gdx.app.log("", String.format("hScrollAmount %f", hScrollAmount)); - //Gdx.app.log("", String.format("hScrollAmount %f", horizontal)); - + + public void smoothScrollTo (float horizontal, float vertical, int duration) { + + // Gdx.app.log("", String.format("hScrollAmount %f", hScrollAmount)); + // Gdx.app.log("", String.format("hScrollAmount %f", horizontal)); + smoothscrolldestx = horizontal; smoothscrolldesty = vertical; scrollstarth = hScrollAmount; scrollstartv = vScrollAmount; scrolledtime = 0; scrolltime = duration; - + } - - public void cancelAnimation(){ + + public void cancelAnimation () { smoothscrolldestx = -1; smoothscrolldesty = -1; } @Override - public void act(float delta) { + public void act (float delta) { super.act(delta); - - if(smoothscrolldestx != -1 && smoothscrolldesty != -1){ - + + if (smoothscrolldestx != -1 && smoothscrolldesty != -1) { + touchable = false; - + scrolledtime += (delta * 1000); - - float relscrolltime = ((float) 1f/scrolltime) * scrolledtime; - - if(smoothscrolldestx > scrollstarth){ - //hScrollAmount += (((smoothscrolldestx - scrollstarth)) / scrolltime) * (delta * 1000); - + + float relscrolltime = ((float)1f / scrolltime) * scrolledtime; + + if (smoothscrolldestx > scrollstarth) { + // hScrollAmount += (((smoothscrolldestx - scrollstarth)) / scrolltime) * (delta * 1000); + hScrollAmount = scrollstarth + (smoothscrolldestx - scrollstarth) * interpolator.getInterpolation(relscrolltime); - } - else{ - //hScrollAmount -= (((scrollstarth - smoothscrolldestx)) / scrolltime) * (delta * 1000); - + } else { + // hScrollAmount -= (((scrollstarth - smoothscrolldestx)) / scrolltime) * (delta * 1000); + hScrollAmount = scrollstarth - (scrollstarth - smoothscrolldestx) * interpolator.getInterpolation(relscrolltime); - + } - - if(smoothscrolldesty > scrollstartv){ - //vScrollAmount += (((smoothscrolldesty - scrollstartv)) / scrolltime) * (delta * 1000); + + if (smoothscrolldesty > scrollstartv) { + // vScrollAmount += (((smoothscrolldesty - scrollstartv)) / scrolltime) * (delta * 1000); vScrollAmount = scrollstartv + (smoothscrolldesty - scrollstartv) * interpolator.getInterpolation(relscrolltime); - } - else{ - //vScrollAmount -= (((scrollstartv - smoothscrolldesty)) / scrolltime) * (delta * 1000); + } else { + // vScrollAmount -= (((scrollstartv - smoothscrolldesty)) / scrolltime) * (delta * 1000); vScrollAmount = scrollstartv - (scrollstartv - smoothscrolldesty) * interpolator.getInterpolation(relscrolltime); } - - - //Gdx.app.log("", String.format("t %f h %f v %f", relscrolltime, hScrollAmount, vScrollAmount)); - if(scrolledtime >= scrolltime){ + // Gdx.app.log("", String.format("t %f h %f v %f", relscrolltime, hScrollAmount, vScrollAmount)); + + if (scrolledtime >= scrolltime) { hScrollAmount = smoothscrolldestx; vScrollAmount = smoothscrolldesty; smoothscrolldestx = -1; @@ -433,25 +395,25 @@ public void act(float delta) { touchable = true; scrolledtime = 0; Gdx.app.log("", "SCROLL OVER"); - if(listener != null){ + if (listener != null) { listener.onSmoothScrollComplete(); } } - + } - + } - public Listener listener; - + public static interface Listener { - public void onFlinged(); - public void onSmoothScrollComplete(); + public void onFlinged (); + + public void onSmoothScrollComplete (); } - - public void setListener(Listener listener){ + + public void setListener (Listener listener) { this.listener = listener; } - + } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageButton.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageButton.java index 5e2cee64b3c..fa369fe740f 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageButton.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageButton.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.g2d.NinePatch; @@ -20,24 +21,19 @@ import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; -/** - * A button with an image on it. +/** A button with an image on it. * - *

        Functionality

        - * A button can be either in a pressed or unpressed state. A {@link ClickListener} can - * be registered with the ImageButton which will be called in case the button was clicked/touched. + *

        Functionality

        A button can be either in a pressed or unpressed state. A {@link ClickListener} can be registered with + * the ImageButton which will be called in case the button was clicked/touched. * - *

        Layout

        - * The (preferred) width and height of an ImageButton are derrived from the border patches in the - * background {@link NinePatch} as well as the width and height of the TextureRegion of the image - * displayed inside the Imagebutton. Use {@link Button#setPrefSize(int, int)} to programmatically change the size - * to your liking. In case the width and height you set are to small for the contained image you - * will see artifacts. + *

        Layout

        The (preferred) width and height of an ImageButton are derrived from the border patches in the background + * {@link NinePatch} as well as the width and height of the TextureRegion of the image displayed inside the Imagebutton. Use + * {@link Button#setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set + * are to small for the contained image you will see artifacts. * - *

        Style

        - * An ImageButton is a {@link Widget} displaying a background {@link NinePatch} as well as - * image in form of a {@link TextureRegion}. The style is defined via an instance - * of {@link ImageButtonStyle}, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        An ImageButton is a {@link Widget} displaying a background {@link NinePatch} as well as image in form of a + * {@link TextureRegion}. The style is defined via an instance of {@link ImageButtonStyle}, which can be either done + * programmatically or via a {@link Skin}.

        * * A Button's style definition in a skin XML file should look like this: * @@ -51,34 +47,32 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newImageButton(String, TextureRegion, String)}.
        • - *
        • The down attribute references a {@link NinePatch} by name, to be used as the button's background when it is pressed
        • - *
        • The up attribute references a {@link NinePatch} by name, to be used as the button's background when it is not pressed
        • - *
        + *
      • The name attribute defines the name of the style which you can later use with + * {@link Skin#newImageButton(String, TextureRegion, String)}.
      • + *
      • The down attribute references a {@link NinePatch} by name, to be used as the button's background when it is + * pressed
      • + *
      • The up attribute references a {@link NinePatch} by name, to be used as the button's background when it is not + * pressed
      • + * * * Note that the image's TextureRegion is defined at construction time or via {@link #setImageSize(float, float)} * - * @author mzechner - * - */ + * @author mzechner */ public class ImageButton extends Widget { final ImageButtonStyle style; TextureRegion image; float imageWidth = 0; float imageHeight = 0; - final Rectangle bounds = new Rectangle(); - boolean isPressed = false; + final Rectangle bounds = new Rectangle(); + boolean isPressed = false; ClickListener listener = null; - - /** - * Creates a new image button. The width and height will be determined by the size - * of the image and the style. + + /** Creates a new image button. The width and height will be determined by the size of the image and the style. * @param name the name * @param image the image's {@link TextureRegion} - * @param style the {@link ImageButtonStyle} - */ - public ImageButton(String name, TextureRegion image, ImageButtonStyle style) { - super(name, 0, 0); + * @param style the {@link ImageButtonStyle} */ + public ImageButton (String name, TextureRegion image, ImageButtonStyle style) { + super(name, 0, 0); this.style = style; this.image = image; this.imageWidth = image.getRegionWidth(); @@ -87,18 +81,15 @@ public ImageButton(String name, TextureRegion image, ImageButtonStyle style) { this.width = prefWidth; this.height = prefHeight; } - - /** - * Creates a new image button. The width and height will be determined by the size given - * for the image and the style + + /** Creates a new image button. The width and height will be determined by the size given for the image and the style * @param name the name * @param image the image's {@link TextureRegion} * @param imageWidth the image's width * @param imageHeight the image's height - * @param style the {@link ImageButtonStyle} - */ - public ImageButton(String name, TextureRegion image, float imageWidth, float imageHeight, ImageButtonStyle style) { - super(name, 0, 0); + * @param style the {@link ImageButtonStyle} */ + public ImageButton (String name, TextureRegion image, float imageWidth, float imageHeight, ImageButtonStyle style) { + super(name, 0, 0); this.style = style; this.image = image; this.imageWidth = imageWidth; @@ -107,29 +98,31 @@ public ImageButton(String name, TextureRegion image, float imageWidth, float ima this.width = prefWidth; this.height = prefHeight; } - + @Override - public void layout() { - final NinePatch downPatch = style.down; - + public void layout () { + final NinePatch downPatch = style.down; + bounds.set(0, 0, imageWidth, imageHeight); - + prefHeight = downPatch.getBottomHeight() + downPatch.getTopHeight() + bounds.height; prefWidth = downPatch.getLeftWidth() + downPatch.getRightWidth() + bounds.width; invalidated = false; } - + @Override - public void draw(SpriteBatch batch, float parentAlpha) { - final NinePatch downPatch = style.down; + public void draw (SpriteBatch batch, float parentAlpha) { + final NinePatch downPatch = style.down; final NinePatch upPatch = style.up; - - if(invalidated) layout(); - + + if (invalidated) layout(); + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - if(isPressed) downPatch.draw(batch, x, y, width, height); - else upPatch.draw(batch, x, y, width, height); - + if (isPressed) + downPatch.draw(batch, x, y, width, height); + else + upPatch.draw(batch, x, y, width, height); + float imageX = (width - bounds.width) * 0.5f; float imageY = (height - bounds.height) * 0.5f; @@ -137,96 +130,80 @@ public void draw(SpriteBatch batch, float parentAlpha) { } @Override - public boolean touchDown(float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { isPressed = true; - parent.focus(this, pointer); + parent.focus(this, pointer); return true; } return false; } @Override - public boolean touchUp(float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { - if(listener != null) listener.click(this); + public boolean touchUp (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { + if (listener != null) listener.click(this); parent.focus(null, pointer); isPressed = false; return true; - } + } isPressed = false; parent.focus(null, pointer); return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { - if(pointer != 0) return false; + public boolean touchDragged (float x, float y, int pointer) { + if (pointer != 0) return false; return isPressed; - } - - /** - * Defines an image button style, see {@link ImageButton} - * @author mzechner - * - */ + } + + /** Defines an image button style, see {@link ImageButton} + * @author mzechner */ public static class ImageButtonStyle { public final NinePatch down; public final NinePatch up; - - public ImageButtonStyle(NinePatch down, NinePatch up) { + + public ImageButtonStyle (NinePatch down, NinePatch up) { this.down = down; this.up = up; } } - - /** - * Interface for listening to clicked events. - * @author mzechner - * - */ + + /** Interface for listening to clicked events. + * @author mzechner */ public interface ClickListener { - public void click(ImageButton button); + public void click (ImageButton button); } - - /** - * @return the {@link TextureRegion} of the image used by this button - */ - public TextureRegion getImage() { + + /** @return the {@link TextureRegion} of the image used by this button */ + public TextureRegion getImage () { return image; } - - /** - * Sets the image's {@link TextureRegion} to be used by this button. Invalidates - * all parents. - * @param image the image's TextureRegion - */ - public void setImage(TextureRegion image) { + + /** Sets the image's {@link TextureRegion} to be used by this button. Invalidates all parents. + * @param image the image's TextureRegion */ + public void setImage (TextureRegion image) { this.image = image; invalidateHierarchy(); } - - /** - * Sets the image's size which is used irrespective of the image's - * TextureRegion's size. + + /** Sets the image's size which is used irrespective of the image's TextureRegion's size. * @param width the width - * @param height the height - */ - public void setImageSize(float width, float height) { + * @param height the height */ + public void setImageSize (float width, float height) { imageWidth = width; imageHeight = height; invalidateHierarchy(); } - - /** - * Sets the {@link ClickListener} for this button. + + /** Sets the {@link ClickListener} for this button. * @param listener the listener or null - * @return this ImageButton for chaining. - */ - public ImageButton setClickListener(ClickListener listener) { + * @return this ImageButton for chaining. */ + public ImageButton setClickListener (ClickListener listener) { this.listener = listener; return this; - } + } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageToggleButton.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageToggleButton.java index eb38afe8a7a..c889983417d 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageToggleButton.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ImageToggleButton.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.g2d.NinePatch; @@ -20,24 +21,19 @@ import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; -/** - * A toggle button with an image on it. +/** A toggle button with an image on it. * - *

        Functionality

        - * A toggle button can be either in a pressed or unpressed state. A {@link ClickListener} can - * be registered with the ImageToggleButton which will be called in case the button changed its state. + *

        Functionality

        A toggle button can be either in a pressed or unpressed state. A {@link ClickListener} can be registered + * with the ImageToggleButton which will be called in case the button changed its state. * - *

        Layout

        - * The (preferred) width and height of an ImageToggleButton are derrived from the border patches in the - * background {@link NinePatch} as well as the width and height of the TextureRegion of the image - * displayed inside the ImageToggleButton. Use {@link #setPrefSize(int, int)} to programmatically change the size - * to your liking. In case the width and height you set are to small for the contained image you - * will see artifacts. + *

        Layout

        The (preferred) width and height of an ImageToggleButton are derrived from the border patches in the background + * {@link NinePatch} as well as the width and height of the TextureRegion of the image displayed inside the ImageToggleButton. Use + * {@link #setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set are to + * small for the contained image you will see artifacts. * - *

        Style

        - * An ImageToggleButton is a {@link Widget} displaying a background {@link NinePatch} as well as - * image in form of a {@link TextureRegion}. The style is defined via an instance - * of {@link ImageToggleButtonStyle}, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        An ImageToggleButton is a {@link Widget} displaying a background {@link NinePatch} as well as image in form of a + * {@link TextureRegion}. The style is defined via an instance of {@link ImageToggleButtonStyle}, which can be either done + * programmatically or via a {@link Skin}.

        * * A Button's style definition in a skin XML file should look like this: * @@ -51,34 +47,32 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newImageToggleButton(String, TextureRegion, String)}.
        • - *
        • The down attribute references a {@link NinePatch} by name, to be used as the button's background when it is pressed
        • - *
        • The up attribute references a {@link NinePatch} by name, to be used as the button's background when it is not pressed
        • - *
        + *
      • The name attribute defines the name of the style which you can later use with + * {@link Skin#newImageToggleButton(String, TextureRegion, String)}.
      • + *
      • The down attribute references a {@link NinePatch} by name, to be used as the button's background when it is + * pressed
      • + *
      • The up attribute references a {@link NinePatch} by name, to be used as the button's background when it is not + * pressed
      • + * * * Note that the image's TextureRegion is defined at construction time or via {@link #setImageSize(float, float)} * - * @author mzechner - * - */ + * @author mzechner */ public class ImageToggleButton extends Widget { final ImageToggleButtonStyle style; TextureRegion image; float imageWidth; float imageHeight; - final Rectangle bounds = new Rectangle(); - boolean isPressed = false; + final Rectangle bounds = new Rectangle(); + boolean isPressed = false; ClickListener listener = null; - - /** - * Creates a new image toggle button. The size is determined by the image's size - * as well as the style. + + /** Creates a new image toggle button. The size is determined by the image's size as well as the style. * @param name the name * @param image the image' {@link TextureRegion} - * @param style the {@link ImageToggleButtonStyle} - */ - public ImageToggleButton(String name, TextureRegion image, ImageToggleButtonStyle style) { - super(name, 0, 0); + * @param style the {@link ImageToggleButtonStyle} */ + public ImageToggleButton (String name, TextureRegion image, ImageToggleButtonStyle style) { + super(name, 0, 0); this.style = style; this.image = image; this.imageWidth = image.getRegionWidth(); @@ -87,18 +81,15 @@ public ImageToggleButton(String name, TextureRegion image, ImageToggleButtonStyl this.width = prefWidth; this.height = prefHeight; } - - /** - * Creates a new image toggle button. The size is determined by the image's size - * as well as the style. + + /** Creates a new image toggle button. The size is determined by the image's size as well as the style. * @param name the name * @param image the image' {@link TextureRegion} * @param imageWidth the image's width * @param imageHeight the image's height - * @param style the {@link ImageToggleButtonStyle} - */ - public ImageToggleButton(String name, TextureRegion image, float imageWidth, float imageHeight, ImageToggleButtonStyle style) { - super(name, 0, 0); + * @param style the {@link ImageToggleButtonStyle} */ + public ImageToggleButton (String name, TextureRegion image, float imageWidth, float imageHeight, ImageToggleButtonStyle style) { + super(name, 0, 0); this.style = style; this.image = image; this.imageWidth = imageWidth; @@ -106,132 +97,114 @@ public ImageToggleButton(String name, TextureRegion image, float imageWidth, flo layout(); this.width = prefWidth; this.height = prefHeight; - } - + } + @Override - public void layout() { - final NinePatch downPatch = style.down; - + public void layout () { + final NinePatch downPatch = style.down; + bounds.set(0, 0, imageWidth, imageHeight); - + prefHeight = downPatch.getBottomHeight() + downPatch.getTopHeight() + bounds.height; prefWidth = downPatch.getLeftWidth() + downPatch.getRightWidth() + bounds.width; invalidated = false; } - + @Override - public void draw(SpriteBatch batch, float parentAlpha) { - final NinePatch downPatch = style.down; + public void draw (SpriteBatch batch, float parentAlpha) { + final NinePatch downPatch = style.down; final NinePatch upPatch = style.up; - - if(invalidated) layout(); - + + if (invalidated) layout(); + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - if(isPressed) downPatch.draw(batch, x, y, width, height); - else upPatch.draw(batch, x, y, width, height); - + if (isPressed) + downPatch.draw(batch, x, y, width, height); + else + upPatch.draw(batch, x, y, width, height); + float imageX = (width - bounds.width) * 0.5f; float imageY = (height - bounds.height) * 0.5f; - + batch.draw(image, x + imageX, y + imageY, imageWidth, imageHeight); } @Override - public boolean touchDown(float x, float y, int pointer) { - if (pointer != 0) - return false; + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; if (hit(x, y) != null) { - isPressed = !isPressed; - if(listener != null) listener.click(this, isPressed); + isPressed = !isPressed; + if (listener != null) listener.click(this, isPressed); return true; } return false; } @Override - public boolean touchUp(float x, float y, int pointer) { + public boolean touchUp (float x, float y, int pointer) { return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { + public boolean touchDragged (float x, float y, int pointer) { return false; - } - - /** - * Defines an image toggle button style, see {@link ImageToggleButton} - * @author mzechner - * - */ + } + + /** Defines an image toggle button style, see {@link ImageToggleButton} + * @author mzechner */ public static class ImageToggleButtonStyle { public final NinePatch down; public final NinePatch up; - - public ImageToggleButtonStyle(NinePatch down, NinePatch up) { + + public ImageToggleButtonStyle (NinePatch down, NinePatch up) { this.down = down; this.up = up; } } - - /** - * Interface for listening to click events. - * @author mzechner - * - */ + + /** Interface for listening to click events. + * @author mzechner */ public interface ClickListener { - public void click(ImageToggleButton button, boolean isPressed); + public void click (ImageToggleButton button, boolean isPressed); } - - /** - * @return the image's {@link TextureRegion} - */ - public TextureRegion getImage() { + + /** @return the image's {@link TextureRegion} */ + public TextureRegion getImage () { return image; } - - /** - * Sets the image's TextureRegion. Invalidates all parents. Keeps - * the previously set image size. - * @param image the image's {@link TextureRegion} - */ - public void setImage(TextureRegion image) { + + /** Sets the image's TextureRegion. Invalidates all parents. Keeps the previously set image size. + * @param image the image's {@link TextureRegion} */ + public void setImage (TextureRegion image) { this.image = image; invalidateHierarchy(); } - - /** - * Sets the image's size. Invalidates all parents + + /** Sets the image's size. Invalidates all parents * @param width the image's width - * @param height the image's height - */ - public void setImageSize(float width, float height) { + * @param height the image's height */ + public void setImageSize (float width, float height) { this.imageWidth = width; this.imageHeight = height; invalidateHierarchy(); } - - /** - * Sets the {@link ClickListener} + + /** Sets the {@link ClickListener} * @param listener the listener or null - * @return this {@link ImageToggleButton} for chaining - */ - public ImageToggleButton setClickListener(ClickListener listener) { + * @return this {@link ImageToggleButton} for chaining */ + public ImageToggleButton setClickListener (ClickListener listener) { this.listener = listener; return this; } - - /** - * @return whether this {@link ImageToggleButton} is down or not - */ - public boolean isPressed() { + + /** @return whether this {@link ImageToggleButton} is down or not */ + public boolean isPressed () { return isPressed; } - - /** - * Sets whether this {@link ImageToggleButton} is down. - * @param isPressed whether this button is down - */ - public void setPressed(boolean isPressed) { + + /** Sets whether this {@link ImageToggleButton} is down. + * @param isPressed whether this button is down */ + public void setPressed (boolean isPressed) { this.isPressed = isPressed; - } + } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Label.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Label.java index 1631defdafd..e7de58d69ae 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Label.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Label.java @@ -13,33 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; -import com.badlogic.gdx.graphics.g2d.NinePatch; -import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; -/** - * A label. +/** A label. * - *

        Functionality

        - * A Label displays multi-line text. + *

        Functionality

        A Label displays multi-line text. * - *

        Layout

        - * The (preferred) width and height of a Label are derrived from the bounding box of the text contained in it. Use - * {@link #setPrefSize(int, int)} to change this programmatically. If the text doesn't fit into the specified area - * artifacts will be visible. + *

        Layout

        The (preferred) width and height of a Label are derrived from the bounding box of the text contained in it. Use + * {@link #setPrefSize(int, int)} to change this programmatically. If the text doesn't fit into the specified area artifacts will + * be visible. * - *

        Style

        - * A label is a {@link Widget} displaying text via a {@link BitmapFont} and a {@link Color}. The style is defined - * via an instance of {@link LabelStyle}, which can be either done programmatically or via a {@link Skin}. A label's - * text will always be rendered starting from the top edge of it's bouding box, define by its width and height, not - * the text's bounding box. + *

        Style

        A label is a {@link Widget} displaying text via a {@link BitmapFont} and a {@link Color}. The style is defined + * via an instance of {@link LabelStyle}, which can be either done programmatically or via a {@link Skin}. A label's text will + * always be rendered starting from the top edge of it's bouding box, define by its width and height, not the text's bounding box. * * A Label's style definition in a skin XML file should look like this: * @@ -53,34 +47,33 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newLabel(String, String, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newLabel(String, String, String)}.
        • *
        • The font attribute references a {@link BitmapFont} by name, to be used to render the label's text.
        • *
        • The fontColor attribute references a {@link Color} by name, to be used to render the label's text.
        • - *
        + * * - * @author mzechner - * - */ -public class Label extends Widget { + * @author mzechner */ +public class Label extends Widget { final LabelStyle style; String label; final TextBounds bounds = new TextBounds(); final Vector2 textPos = new Vector2(); - - public Label(String name, String label, LabelStyle style) { + + public Label (String name, String label, LabelStyle style) { super(name, 0, 0); this.style = style; - this.label = label; + this.label = label; this.touchable = false; layout(); this.width = prefWidth; this.height = prefHeight; - } + } @Override - public void layout() { + public void layout () { final BitmapFont font = style.font; - + bounds.set(font.getMultiLineBounds(label)); bounds.height -= font.getDescent(); prefWidth = bounds.width; @@ -91,51 +84,48 @@ public void layout() { } @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final BitmapFont font = style.font; final Color fontColor = style.fontColor; - - if(invalidated) layout(); - font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); - font.drawMultiLine(batch, label, x + textPos.x, y + height); + + if (invalidated) layout(); + font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); + font.drawMultiLine(batch, label, x + textPos.x, y + height); } @Override - public boolean touchDown(float x, float y, int pointer) { + public boolean touchDown (float x, float y, int pointer) { return false; } @Override - public boolean touchUp(float x, float y, int pointer) { + public boolean touchUp (float x, float y, int pointer) { return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { + public boolean touchDragged (float x, float y, int pointer) { return false; } @Override - public Actor hit(float x, float y) { + public Actor hit (float x, float y) { return null; } - - /** - * Defines a label's style, see {@link Label} - * @author mzechner - * - */ + + /** Defines a label's style, see {@link Label} + * @author mzechner */ public static class LabelStyle { public BitmapFont font; public Color fontColor; - - public LabelStyle(BitmapFont font, Color fontColor) { + + public LabelStyle (BitmapFont font, Color fontColor) { this.font = font; this.fontColor = fontColor; } - } - - public void setText(String text) { + } + + public void setText (String text) { this.label = text; layout(); invalidateHierarchy(); diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/List.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/List.java index ec7c3df6bf6..8e2bc352f1e 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/List.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/List.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; @@ -22,26 +23,20 @@ import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Actor; -/** - * A list of string entries. +/** A list of string entries. * - *

        Functionality

        - * A list displays textual entries and highlights the current selection. A {@link SelectionListener} can - * be registered with the list to listen to selection changes. Entries have an index in the list, the - * top entry having the index 0. + *

        Functionality

        A list displays textual entries and highlights the current selection. A {@link SelectionListener} can be + * registered with the list to listen to selection changes. Entries have an index in the list, the top entry having the index 0. * - *

        Layout

        - * The (preferred) width and height of a List are derrived from the bounding box around all list entries. Use {@link #setPrefSize(int, int)} - * to programmatically change the size to your liking. In case the width and height you set are to small for the contained text you - * will see artifacts. The patch highlighting the current selection will have the width of the List, either determined as - * explained above or set programmatically. + *

        Layout

        The (preferred) width and height of a List are derrived from the bounding box around all list entries. Use + * {@link #setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set are to + * small for the contained text you will see artifacts. The patch highlighting the current selection will have the width of the + * List, either determined as explained above or set programmatically. * - *

        Style

        - * A List is a {@link Widget} a text rendered for each list entry via a - * {@link BitmapFont} and {@link Color} as well as a {@link NinePatch} highlighting the current selection and a second Color used - * for the text of the currently selected entry. The highlighting - * NinePatch is rendered beneath the selected entry. The style is defined via an - * instance of {@link ListStyle}, which can be done either programmatically or via a {@link Skin}.

        + *

        Style

        A List is a {@link Widget} a text rendered for each list entry via a {@link BitmapFont} and {@link Color} as + * well as a {@link NinePatch} highlighting the current selection and a second Color used for the text of the currently selected + * entry. The highlighting NinePatch is rendered beneath the selected entry. The style is defined via an instance of + * {@link ListStyle}, which can be done either programmatically or via a {@link Skin}.

        * * A List's style definition in an XML skin file should look like this: * @@ -56,59 +51,57 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newList(String, String[], String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newList(String, String[], String)}.
        • *
        • The fontName attribute references a {@link BitmapFont} by name, to be used for render the entries
        • - *
        • The fontColorUnselected attribute references a {@link Color} by name, to be used for render unselected entries
        • + *
        • The fontColorUnselected attribute references a {@link Color} by name, to be used for render unselected entries + *
        • *
        • The fontColorSelected attribute references a {@link Color} by name, to be used to render the selected entry
        • - *
        • The selected attribute references a {@link NinePatch} by name, to be used to render the highlight behind the selected entry
        • - *
        + *
      • The selected attribute references a {@link NinePatch} by name, to be used to render the highlight behind the + * selected entry
      • + * * - * @author mzechner - * - */ + * @author mzechner */ public class List extends Widget { final ListStyle style; - String[] entries; + String[] entries; boolean invalidated = false; float entryHeight = 0; float textOffsetX = 0; float textOffsetY = 0; int selected = 0; - SelectionListener listener; - - /** - * Creates a new List. The width and height is determined from the - * bounding box around all entries. + SelectionListener listener; + + /** Creates a new List. The width and height is determined from the bounding box around all entries. * @param name the name * @param entries the entries - * @param style the {@link ListStyle} - */ - public List(String name, String[] entries, ListStyle style) { + * @param style the {@link ListStyle} */ + public List (String name, String[] entries, ListStyle style) { super(name, 0, 0); this.style = style; - this.entries = entries; + this.entries = entries; layout(); this.width = prefWidth; this.height = prefHeight; - } + } @Override - public void layout() { - final BitmapFont font = style.font; + public void layout () { + final BitmapFont font = style.font; final NinePatch selectedPatch = style.selectedPatch; prefWidth = 0; prefHeight = 0; - - for(int i = 0; i < entries.length; i++) { + + for (int i = 0; i < entries.length; i++) { String entry = entries[i]; TextBounds bounds = font.getBounds(entry); - prefWidth = Math.max(bounds.width, prefWidth); - + prefWidth = Math.max(bounds.width, prefWidth); + } - + entryHeight = font.getLineHeight() - font.getDescent(); entryHeight += selectedPatch.getTopHeight() + selectedPatch.getBottomHeight(); - prefWidth += selectedPatch.getLeftWidth() + selectedPatch.getRightWidth(); + prefWidth += selectedPatch.getLeftWidth() + selectedPatch.getRightWidth(); prefHeight = entries.length * entryHeight; textOffsetX = selectedPatch.getLeftWidth(); textOffsetY = selectedPatch.getTopHeight() - font.getDescent(); @@ -116,22 +109,23 @@ public void layout() { } @Override - public void draw(SpriteBatch batch, float parentAlpha) { - final BitmapFont font = style.font; + public void draw (SpriteBatch batch, float parentAlpha) { + final BitmapFont font = style.font; final NinePatch selectedPatch = style.selectedPatch; final Color fontColorSelected = style.fontColorSelected; final Color fontColorUnselected = style.fontColorUnselected; - - if(invalidated) layout(); + + if (invalidated) layout(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - + float posY = height; - for(int i = 0; i < entries.length; i++) { - if(selected == i) { + for (int i = 0; i < entries.length; i++) { + if (selected == i) { selectedPatch.draw(batch, x, y + posY - entryHeight, Math.max(prefWidth, width), entryHeight); font.setColor(fontColorSelected.r, fontColorSelected.g, fontColorSelected.b, fontColorSelected.a * parentAlpha); } else { - font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a * parentAlpha); + font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a + * parentAlpha); } font.draw(batch, entries[i], x + textOffsetX, y + posY - textOffsetY); posY -= entryHeight; @@ -139,91 +133,77 @@ public void draw(SpriteBatch batch, float parentAlpha) { } @Override - public boolean touchDown(float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { - selected = (int)((height-y) / entryHeight); + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { + selected = (int)((height - y) / entryHeight); selected = Math.max(0, selected); - selected = Math.min(entries.length -1, selected); - if(listener != null) listener.selected(this, selected, entries[selected]); + selected = Math.min(entries.length - 1, selected); + if (listener != null) listener.selected(this, selected, entries[selected]); return true; } return false; } @Override - public boolean touchUp(float x, float y, int pointer) { + public boolean touchUp (float x, float y, int pointer) { return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { + public boolean touchDragged (float x, float y, int pointer) { return false; } @Override - public Actor hit(float x, float y) { - return x >= 0 && x < Math.max(prefWidth, width) && y >= 0 && y < prefHeight?this:null; + public Actor hit (float x, float y) { + return x >= 0 && x < Math.max(prefWidth, width) && y >= 0 && y < prefHeight ? this : null; } - /** - * Defines a list style, see {@link List} - * @author mzechner - * - */ + /** Defines a list style, see {@link List} + * @author mzechner */ public static class ListStyle { public final BitmapFont font; public final Color fontColorSelected = new Color(1, 1, 1, 1); public final Color fontColorUnselected = new Color(1, 1, 1, 1); public final NinePatch selectedPatch; - - public ListStyle(BitmapFont font, Color fontColorSelected, Color fontColorUnselected, NinePatch selectedPatch) { + + public ListStyle (BitmapFont font, Color fontColorSelected, Color fontColorUnselected, NinePatch selectedPatch) { this.font = font; this.fontColorSelected.set(fontColorSelected); this.fontColorUnselected.set(this.fontColorUnselected); this.selectedPatch = selectedPatch; } } - - /** - * Interface for listening to selection changes. - * @author mzechner - * - */ + + /** Interface for listening to selection changes. + * @author mzechner */ public interface SelectionListener { - public void selected(List list, int selectedIndex, String selection); + public void selected (List list, int selectedIndex, String selection); } - - /** - * @return the index of the currently selected entry. The top entry has an index of 0. - */ - public int getSelectedIndex() { + + /** @return the index of the currently selected entry. The top entry has an index of 0. */ + public int getSelectedIndex () { return selected; } - - /** - * @return the text of the curently selected entry - */ - public String getSelection() { + + /** @return the text of the curently selected entry */ + public String getSelection () { return entries[selected]; } - - /** - * Sets the entries of this list. Invalidates all parents. - * @param entries the entries. - */ - public void setEntries(String[] entries) { - if(entries == null) throw new IllegalArgumentException("entries must not be null"); + + /** Sets the entries of this list. Invalidates all parents. + * @param entries the entries. */ + public void setEntries (String[] entries) { + if (entries == null) throw new IllegalArgumentException("entries must not be null"); this.entries = entries; selected = 0; invalidateHierarchy(); } - - /** - * Sets the {@link SelectionListener} of this list. - * @param listener the listener or null - */ - public void setSelectionListener(SelectionListener listener) { + + /** Sets the {@link SelectionListener} of this list. + * @param listener the listener or null */ + public void setSelectionListener (SelectionListener listener) { this.listener = listener; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Pane.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Pane.java index c57d303c769..ab840541b77 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Pane.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Pane.java @@ -13,10 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; -import com.badlogic.gdx.graphics.Color; -import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Matrix4; @@ -27,29 +26,23 @@ import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.badlogic.gdx.scenes.scene2d.ui.utils.ScissorStack; -/** - * A Container with a background NinePatch. +/** A Container with a background NinePatch. * - *

        Functionality

        - * A Pane is a {@link Table} displaying a background {@link NinePatch}. It can house - * multiple {@link Actor} instances in a table-layout. The difference to a pure Container is - * that the Pane will automatically set the padding of the layout to respect the width and height - * of the border patches of its background NinePatch. See {@link Table} for more information on - * how Actor instances are laid out when using this class.

        + *

        Functionality

        A Pane is a {@link Table} displaying a background {@link NinePatch}. It can house multiple {@link Actor} + * instances in a table-layout. The difference to a pure Container is that the Pane will automatically set the padding of the + * layout to respect the width and height of the border patches of its background NinePatch. See {@link Table} for more + * information on how Actor instances are laid out when using this class.

        * - * In addition to the basic functionality provided by the Container super class, a Pane will also - * employ scissoring (clipping) to ensure that no contained Actor can render outside of its bounds. + * In addition to the basic functionality provided by the Container super class, a Pane will also employ scissoring (clipping) to + * ensure that no contained Actor can render outside of its bounds. * - *

        Layout

        - * The (preferred) width and height are determined by the values given in the constructor of this class. - * Please consult the {@link Table} documentation on how the width and height will be manipulated - * if the Pane is contained in another Container. Additionally you can set the (preferred) width and height - * via a call to {@link TableLayout#size(int, int)}. + *

        Layout

        The (preferred) width and height are determined by the values given in the constructor of this class. Please + * consult the {@link Table} documentation on how the width and height will be manipulated if the Pane is contained in another + * Container. Additionally you can set the (preferred) width and height via a call to {@link TableLayout#size(int, int)}. * - *

        Style

        - * A Pane is a {@link Table} displaying a background {@link NinePatch} and its child Actors, clipped to the - * Pane's area, taking into account the padding as described in the functionality section. The style is defined via - * an instance of {@link PaneStyle}, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        A Pane is a {@link Table} displaying a background {@link NinePatch} and its child Actors, clipped to the Pane's + * area, taking into account the padding as described in the functionality section. The style is defined via an instance of + * {@link PaneStyle}, which can be either done programmatically or via a {@link Skin}.

        * * A Pane's style definition in a skin XML file should look like this: * @@ -61,76 +54,70 @@ * * *
          - *
        • The styleName attribute defines the name of the style which you can later use with {@link Skin#newPane(String, Stage, int, int, String)}.
        • - *
        • The backgroundPatch attribute references a {@link NinePatch} by name, to be used as the Pane's background.
        • * - *
        - * @author mzechner - * - */ -public class Pane extends Table { + *
      • The styleName attribute defines the name of the style which you can later use with + * {@link Skin#newPane(String, Stage, int, int, String)}.
      • + *
      • The backgroundPatch attribute references a {@link NinePatch} by name, to be used as the Pane's background.
      • + * * + * + * @author mzechner */ +public class Pane extends Table { final PaneStyle style; final Stage stage; final Rectangle widgetBounds = new Rectangle(); final Rectangle scissors = new Rectangle(); - - /** - * Creates a new Pane. The width and height are determined by the - * arguments passed to the constructor. + + /** Creates a new Pane. The width and height are determined by the arguments passed to the constructor. * @param name the name * @param stage the stage used for clipping - * @param prefWidth the width + * @param prefWidth the width * @param prefHeight the height - * @param style the {@link PaneStyle} - */ - public Pane(String name, Stage stage, int prefWidth, int prefHeight, PaneStyle style) { + * @param style the {@link PaneStyle} */ + public Pane (String name, Stage stage, int prefWidth, int prefHeight, PaneStyle style) { super(name); this.stage = stage; width = prefWidth; height = prefHeight; this.style = style; - + final NinePatch background = style.background; TableLayout layout = getTableLayout(); layout.padBottom(Integer.toString((int)(background.getBottomHeight()) + 1)); layout.padTop(Integer.toString((int)(background.getTopHeight()) + 1)); layout.padLeft(Integer.toString((int)(background.getLeftWidth()) + 1)); layout.padRight(Integer.toString((int)(background.getRightWidth()) + 1)); - } - - private void calculateScissors(Matrix4 transform) { + } + + private void calculateScissors (Matrix4 transform) { final NinePatch background = style.background; - + widgetBounds.x = background.getLeftWidth(); widgetBounds.y = background.getBottomHeight(); widgetBounds.width = width - background.getLeftWidth() - background.getRightWidth(); widgetBounds.height = height - background.getTopHeight() - background.getBottomHeight(); ScissorStack.calculateScissors(stage.getCamera(), transform, widgetBounds, scissors); } - + @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final NinePatch background = style.background; - + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - background.draw(batch, x, y, width, height); + background.draw(batch, x, y, width, height); setupTransform(batch); layout(); calculateScissors(batch.getTransformMatrix()); ScissorStack.pushScissors(scissors); super.drawChildren(batch, parentAlpha); resetTransform(batch); - ScissorStack.popScissors(); + ScissorStack.popScissors(); } - - /** - * Defines the style of a pane, see {@link Pane} - * @author mzechner - * - */ + + /** Defines the style of a pane, see {@link Pane} + * @author mzechner */ public static class PaneStyle { public final NinePatch background; - - public PaneStyle(NinePatch backgroundPatch) { + + public PaneStyle (NinePatch backgroundPatch) { this.background = backgroundPatch; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java index 7afe3426772..4e38267c176 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ScrollPane.java @@ -13,10 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; -import com.badlogic.gdx.graphics.Color; -import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Matrix4; @@ -30,36 +29,31 @@ import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; import com.badlogic.gdx.scenes.scene2d.ui.utils.ScissorStack; -/** - * A special container that allows scrolling over its children. +/** A special container that allows scrolling over its children. * - *

        Functionality

        - * A ScrollPane can embed any {@link Actor} (and {@link Widget} or {@link Table} for that matter) and provide - * scrolling functionality in case the embedded Actor is bigger than the scroll pane itself. The scroll pane will - * automatically decide whether it needs a vertical and/or horizontal scroll handle based on the contained - * Actor's size with respect to the scroll pane's own size.

        + *

        Functionality

        A ScrollPane can embed any {@link Actor} (and {@link Widget} or {@link Table} for that matter) and + * provide scrolling functionality in case the embedded Actor is bigger than the scroll pane itself. The scroll pane will + * automatically decide whether it needs a vertical and/or horizontal scroll handle based on the contained Actor's size with + * respect to the scroll pane's own size.

        * * Note: do not use any of the {@link #addActor(Actor)} or {@link #removeActor(Actor)} methods with this class! The embedded - * widget is specified at construction time or via {@link #setWidget(Actor)}. - * * - *

        Layout

        - * The (preferred) width and height of a scroll pane is determined by the size passed to its constructor. The contained - * Actor will be positioned in such a way that it's top left corner will coincide with the scroll pane's corner when - * the vertical and horizontal scroll handles are at their minimum position.

        - * + * widget is specified at construction time or via {@link #setWidget(Actor)}. *

        Layout

        The (preferred) width and + * height of a scroll pane is determined by the size passed to its constructor. The contained Actor will be positioned in such a + * way that it's top left corner will coincide with the scroll pane's corner when the vertical and horizontal scroll handles are + * at their minimum position.

        + * * - *

        Style

        - * A ScrollPane is a {@link Group} (note the comment in the functionality section!) that conditionally displays horizontal - * and vertical scroll bars and handles as well as the embedded Actor, clipped to the available area inside of the - * scroll pane. The scroll bars are {@link NinePatch} instances, the scroll handles are {@link NinePatch} instances as well. - * In addition a background {@link NinePatch} is displayed behind the embedded Actor. The style is defined - * via a {@link ScrollPaneStyle} instance, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        A ScrollPane is a {@link Group} (note the comment in the functionality section!) that conditionally displays + * horizontal and vertical scroll bars and handles as well as the embedded Actor, clipped to the available area inside of the + * scroll pane. The scroll bars are {@link NinePatch} instances, the scroll handles are {@link NinePatch} instances as well. In + * addition a background {@link NinePatch} is displayed behind the embedded Actor. The style is defined via a + * {@link ScrollPaneStyle} instance, which can be either done programmatically or via a {@link Skin}.

        * - * The height of the horizontal scroll bar and handle is constant and takes on the maximum {@link NinePatch#getTotalHeight()} value of the involed NinePatch - * instances. The width is determined automatically based on the size of the scroll pane.

        + * The height of the horizontal scroll bar and handle is constant and takes on the maximum {@link NinePatch#getTotalHeight()} + * value of the involed NinePatch instances. The width is determined automatically based on the size of the scroll pane.

        * - * The width of the vertical scroll bar and handle is constant and takes on the maximum {@link NinePatch#getTotalWidth()} value of the involed NinePatch - * instances. The height is determined automatically based on the size of the scroll pane.

        + * The width of the vertical scroll bar and handle is constant and takes on the maximum {@link NinePatch#getTotalWidth()} value of + * the involed NinePatch instances. The height is determined automatically based on the size of the scroll pane.

        * * * A ScrollPane's style definition in a skin XML file should look like this: @@ -76,192 +70,187 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newScrollPane(String, Stage, Actor, int, int, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newScrollPane(String, Stage, Actor, int, int, String)}.
        • *
        • The background attribute references a {@link NinePatch} by name, to be used as the scroll pane's background
        • - *
        • The hScroll attribute references a {@link NinePatch} by name, to be used as the scroll pane's horizontal scroll bar.
        • - *
        • The hScrollKnow attribute references a {@link NinePatch} by name, to be used as the scroll pane's horizontal scroll handle.
        • - *
        • The vScroll attribute references a {@link NinePatch} by name, to be used as the scroll pane's vertical scroll bar.
        • - *
        • The vScrollKnow attribute references a {@link NinePatch} by name, to be used as the scroll pane's vertical scroll handle..
        • + *
        • The hScroll attribute references a {@link NinePatch} by name, to be used as the scroll pane's horizontal + * scroll bar.
        • + *
        • The hScrollKnow attribute references a {@link NinePatch} by name, to be used as the scroll pane's horizontal + * scroll handle.
        • + *
        • The vScroll attribute references a {@link NinePatch} by name, to be used as the scroll pane's vertical scroll + * bar.
        • + *
        • The vScrollKnow attribute references a {@link NinePatch} by name, to be used as the scroll pane's vertical + * scroll handle..
        • *
        * - * @author mzechner - * - */ + * @author mzechner */ public class ScrollPane extends Group implements Layout { final ScrollPaneStyle style; Actor widget; Stage stage; float prefWidth; float prefHeight; - - boolean invalidated = true; - + + boolean invalidated = true; + Rectangle hScrollBounds = new Rectangle(); Rectangle vScrollBounds = new Rectangle(); Rectangle hScrollKnobBounds = new Rectangle(); - Rectangle vScrollKnobBounds = new Rectangle(); + Rectangle vScrollKnobBounds = new Rectangle(); Rectangle widgetAreaBounds = new Rectangle(); Rectangle scissorBounds = new Rectangle(); - + float hScrollAmount = 0; - float vScrollAmount = 0; + float vScrollAmount = 0; boolean hasHScroll = false; boolean hasVScroll = false; boolean touchScrollH = false; boolean touchScrollV = false; Vector2 lastPoint = new Vector2(); - - public ScrollPane(String name, Stage stage, Actor widget, int prefWidth, int prefHeight, ScrollPaneStyle style) { + + public ScrollPane (String name, Stage stage, Actor widget, int prefWidth, int prefHeight, ScrollPaneStyle style) { super(name); this.style = style; this.prefWidth = this.width = prefWidth; - this.prefHeight = this.height = prefHeight; - + this.prefHeight = this.height = prefHeight; + this.stage = stage; this.widget = widget; this.addActor(widget); layout(); - } - - Vector3 tmp = new Vector3(); - private void calculateBoundsAndPositions(Matrix4 batchTransform) { + } + + Vector3 tmp = new Vector3(); + + private void calculateBoundsAndPositions (Matrix4 batchTransform) { final NinePatch background = style.background; final NinePatch hScrollKnob = style.hScrollKnob; final NinePatch vScrollKnob = style.vScrollKnob; - - // get available space size by subtracting background's + + // get available space size by subtracting background's // padded area float areaWidth = width - background.getLeftWidth() - background.getRightWidth(); float areaHeight = height - background.getTopHeight() - background.getBottomHeight(); hasHScroll = false; hasVScroll = false; - - // Figure out if we need horizontal/vertical scrollbars, - if(widget.width > areaWidth) hasHScroll = true; - if(widget.height > areaHeight) hasVScroll = true; - - // check again, now taking into account the area + + // Figure out if we need horizontal/vertical scrollbars, + if (widget.width > areaWidth) hasHScroll = true; + if (widget.height > areaHeight) hasVScroll = true; + + // check again, now taking into account the area // that's taken up by any enabled scrollbars - if(hasVScroll && (widget.width > areaWidth - vScrollKnob.getTotalWidth())) { + if (hasVScroll && (widget.width > areaWidth - vScrollKnob.getTotalWidth())) { hasHScroll = true; areaWidth -= vScrollKnob.getTotalWidth(); } - if(hasHScroll && (widget.height > areaHeight - hScrollKnob.getTotalHeight())) { + if (hasHScroll && (widget.height > areaHeight - hScrollKnob.getTotalHeight())) { hasVScroll = true; areaHeight -= hScrollKnob.getTotalHeight(); } - - // now we know what scrollbars we need, set the bounds and + + // now we know what scrollbars we need, set the bounds and // scroll knob sizes accordingly - if(hasHScroll) { - hScrollBounds.set(background.getLeftWidth(), - background.getBottomHeight(), - areaWidth, - hScrollKnob.getTotalHeight()); + if (hasHScroll) { + hScrollBounds.set(background.getLeftWidth(), background.getBottomHeight(), areaWidth, hScrollKnob.getTotalHeight()); hScrollKnobBounds.width = Math.max(hScrollKnob.getTotalWidth(), (int)(hScrollBounds.width * areaWidth / widget.width)); hScrollKnobBounds.height = hScrollKnob.getTotalHeight(); - + hScrollKnobBounds.x = hScrollBounds.x + (int)((hScrollBounds.width - hScrollKnobBounds.width) * hScrollAmount); - hScrollKnobBounds.y = hScrollBounds.y; + hScrollKnobBounds.y = hScrollBounds.y; } - - if(hasVScroll) { - vScrollBounds.set(width - background.getRightWidth() - vScrollKnob.getTotalWidth(), - height - background.getTopHeight() - areaHeight, - vScrollKnob.getTotalWidth(), - areaHeight); + + if (hasVScroll) { + vScrollBounds.set(width - background.getRightWidth() - vScrollKnob.getTotalWidth(), height - background.getTopHeight() + - areaHeight, vScrollKnob.getTotalWidth(), areaHeight); vScrollKnobBounds.width = vScrollKnob.getTotalWidth(); - vScrollKnobBounds.height = Math.max(vScrollKnob.getTotalHeight(), (int)(vScrollBounds.height * areaHeight / widget.height)); + vScrollKnobBounds.height = Math.max(vScrollKnob.getTotalHeight(), + (int)(vScrollBounds.height * areaHeight / widget.height)); vScrollKnobBounds.x = vScrollBounds.x; - vScrollKnobBounds.y = vScrollBounds.y + (int)((vScrollBounds.height - vScrollKnobBounds.height) * (1 - vScrollAmount)); + vScrollKnobBounds.y = vScrollBounds.y + (int)((vScrollBounds.height - vScrollKnobBounds.height) * (1 - vScrollAmount)); } - // Set the widget area bounds - widgetAreaBounds.set(background.getLeftWidth(), - background.getBottomHeight() + (hasHScroll?hScrollKnob.getTotalHeight():0), - areaWidth, - areaHeight); - + widgetAreaBounds.set(background.getLeftWidth(), background.getBottomHeight() + + (hasHScroll ? hScrollKnob.getTotalHeight() : 0), areaWidth, areaHeight); + // Calculate the widgets offset depending on the scroll state and // available widget area. - widget.y = widgetAreaBounds.y - (!hasVScroll?(int)(widget.height - areaHeight):0) - - (hasVScroll?(int)((widget.height - areaHeight) * (1-vScrollAmount)):0); - widget.x = widgetAreaBounds.x - (hasHScroll?(int)((widget.width - areaWidth) * hScrollAmount):0); - + widget.y = widgetAreaBounds.y - (!hasVScroll ? (int)(widget.height - areaHeight) : 0) + - (hasVScroll ? (int)((widget.height - areaHeight) * (1 - vScrollAmount)) : 0); + widget.x = widgetAreaBounds.x - (hasHScroll ? (int)((widget.width - areaWidth) * hScrollAmount) : 0); + // Caculate the scissor bounds based on the batch transform, // the available widget area and the camera transform. We // need to project those to screen coordinates for OpenGL ES // to consume. This is pretty freaking nasty... - ScissorStack.calculateScissors(stage.getCamera(), batchTransform, widgetAreaBounds, scissorBounds); + ScissorStack.calculateScissors(stage.getCamera(), batchTransform, widgetAreaBounds, scissorBounds); } - + @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final NinePatch background = style.background; final NinePatch hScrollKnob = style.hScrollKnob; final NinePatch hScroll = style.hScroll; final NinePatch vScrollKnob = style.vScrollKnob; final NinePatch vScroll = style.vScroll; - + // setup transform for this group - setupTransform(batch); - + setupTransform(batch); + // if invalidated layout! - if(invalidated) layout(); - + if (invalidated) layout(); + // calculate the bounds for the scrollbars, the widget // area and the scissor area. Nasty... - calculateBoundsAndPositions(batch.getTransformMatrix()); - + calculateBoundsAndPositions(batch.getTransformMatrix()); + // first draw the background ninepatch batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - background.draw(batch, 0, 0, width, height); - + background.draw(batch, 0, 0, width, height); + // enable scissors for widget area and draw that damn // widget. Nasty #2 - ScissorStack.pushScissors(scissorBounds); + ScissorStack.pushScissors(scissorBounds); drawChildren(batch, parentAlpha); ScissorStack.popScissors(); - + // render scrollbars and knobs on top. batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - if(hasHScroll) { + if (hasHScroll) { hScroll.draw(batch, hScrollBounds.x, hScrollBounds.y, hScrollBounds.width, hScrollBounds.height); hScrollKnob.draw(batch, hScrollKnobBounds.x, hScrollKnobBounds.y, hScrollKnobBounds.width, hScrollKnobBounds.height); } - if(hasVScroll) { + if (hasVScroll) { vScroll.draw(batch, vScrollBounds.x, vScrollBounds.y, vScrollBounds.width, vScrollBounds.height); vScrollKnob.draw(batch, vScrollKnobBounds.x, vScrollKnobBounds.y, vScrollKnobBounds.width, vScrollKnobBounds.height); } - + resetTransform(batch); } - - /** - * Defines a scroll pane' style, see {@link ScrollPane} - * @author mzechner - * - */ + + /** Defines a scroll pane' style, see {@link ScrollPane} + * @author mzechner */ public static class ScrollPaneStyle { public final NinePatch background; public final NinePatch hScroll; public final NinePatch hScrollKnob; public final NinePatch vScroll; public final NinePatch vScrollKnob; - - public ScrollPaneStyle( NinePatch backgroundPatch, NinePatch hScroll, NinePatch hScrollKnob, NinePatch vScroll, NinePatch vScrollKnob) { + + public ScrollPaneStyle (NinePatch backgroundPatch, NinePatch hScroll, NinePatch hScrollKnob, NinePatch vScroll, + NinePatch vScrollKnob) { this.background = backgroundPatch; this.hScroll = hScroll; this.hScrollKnob = hScrollKnob; this.vScroll = vScroll; - this.vScrollKnob = vScrollKnob; + this.vScrollKnob = vScrollKnob; } } @Override - public void layout() { - if(widget instanceof Layout) { + public void layout () { + if (widget instanceof Layout) { Layout layout = (Layout)widget; widget.width = Math.max(width, layout.getPrefWidth()); widget.height = Math.max(height, layout.getPrefHeight()); @@ -272,109 +261,110 @@ public void layout() { } @Override - public void invalidate() { - if(widget instanceof Layout) ((Layout)widget).invalidate(); + public void invalidate () { + if (widget instanceof Layout) ((Layout)widget).invalidate(); invalidated = true; - } + } @Override - public float getPrefWidth() { + public float getPrefWidth () { return prefWidth; } @Override - public float getPrefHeight() { + public float getPrefHeight () { return prefHeight; } - + float handlePos = 0; + @Override public boolean touchDown (float x, float y, int pointer) { - if(pointer != 0) return false; - - if(hasHScroll && hScrollBounds.contains(x, y)) { - if(hScrollKnobBounds.contains(x, y)) { - lastPoint.set(x,y); + if (pointer != 0) return false; + + if (hasHScroll && hScrollBounds.contains(x, y)) { + if (hScrollKnobBounds.contains(x, y)) { + lastPoint.set(x, y); handlePos = hScrollKnobBounds.x; touchScrollH = true; focus(this, 0); } else { - if(x < hScrollKnobBounds.x) { + if (x < hScrollKnobBounds.x) { hScrollAmount = Math.max(0, hScrollAmount - 0.1f); } else { hScrollAmount = Math.min(1, hScrollAmount + 0.1f); } - } + } return true; - } - else if(hasVScroll && vScrollBounds.contains(x, y)) { - if(vScrollKnobBounds.contains(x, y)) { - lastPoint.set(x,y); + } else if (hasVScroll && vScrollBounds.contains(x, y)) { + if (vScrollKnobBounds.contains(x, y)) { + lastPoint.set(x, y); handlePos = vScrollKnobBounds.y; touchScrollV = true; focus(this, 0); } else { - if(y < vScrollKnobBounds.y) { + if (y < vScrollKnobBounds.y) { vScrollAmount = Math.min(1, vScrollAmount + 0.1f); } else { vScrollAmount = Math.max(0, vScrollAmount - 0.1f); - } - } + } + } return true; - } else if(widgetAreaBounds.contains(x, y)) { + } else if (widgetAreaBounds.contains(x, y)) { return super.touchDown(x, y, pointer); - } else return false; + } else + return false; } @Override public boolean touchUp (float x, float y, int pointer) { - if(pointer != 0) return false; - if(touchScrollH || touchScrollV) { + if (pointer != 0) return false; + if (touchScrollH || touchScrollV) { focus(null, 0); touchScrollH = false; touchScrollV = false; - return true; - } else return super.touchUp(x, y, pointer); + return true; + } else + return super.touchUp(x, y, pointer); } @Override public boolean touchDragged (float x, float y, int pointer) { - if(pointer != 0) return false; - if(touchScrollH) { + if (pointer != 0) return false; + if (touchScrollH) { float delta = x - lastPoint.x; float scrollH = handlePos + delta; handlePos = scrollH; scrollH = Math.max(hScrollBounds.x, scrollH); - scrollH = Math.min(hScrollBounds.x + hScrollBounds.width - hScrollKnobBounds.width, scrollH); - hScrollAmount = (scrollH - hScrollBounds.x) / (hScrollBounds.width - hScrollKnobBounds.width); - lastPoint.set(x, y); + scrollH = Math.min(hScrollBounds.x + hScrollBounds.width - hScrollKnobBounds.width, scrollH); + hScrollAmount = (scrollH - hScrollBounds.x) / (hScrollBounds.width - hScrollKnobBounds.width); + lastPoint.set(x, y); return true; - } else if(touchScrollV) { + } else if (touchScrollV) { float delta = y - lastPoint.y; float scrollV = handlePos + delta; handlePos = scrollV; scrollV = Math.max(vScrollBounds.y, scrollV); - scrollV = Math.min(vScrollBounds.y + vScrollBounds.height - vScrollKnobBounds.height, scrollV); - vScrollAmount = 1 - ((scrollV - vScrollBounds.y) / (vScrollBounds.height - vScrollKnobBounds.height)); - lastPoint.set(x, y); + scrollV = Math.min(vScrollBounds.y + vScrollBounds.height - vScrollKnobBounds.height, scrollV); + vScrollAmount = 1 - ((scrollV - vScrollBounds.y) / (vScrollBounds.height - vScrollKnobBounds.height)); + lastPoint.set(x, y); return true; - } else return super.touchDragged(x, y, pointer); + } else + return super.touchDragged(x, y, pointer); } - + @Override - public Actor hit(float x, float y) { - return x > 0 && x < width && y > 0 && y < height?this: null; + public Actor hit (float x, float y) { + return x > 0 && x < width && y > 0 && y < height ? this : null; } - /** - * Sets the {@link Actor} embedded in this scroll pane. - * @param widget the Actor - */ - public void setWidget(Actor widget) { - if(widget == null) throw new IllegalArgumentException("widget must not be null"); + /** Sets the {@link Actor} embedded in this scroll pane. + * @param widget the Actor */ + public void setWidget (Actor widget) { + if (widget == null) throw new IllegalArgumentException("widget must not be null"); this.removeActor(this.widget); - this.widget = widget; + this.widget = widget; this.addActor(widget); invalidate(); } -} \ No newline at end of file +} diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java index 7abef65782a..c99e92a0083 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Skin.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; -import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -50,26 +50,35 @@ import com.badlogic.gdx.utils.Xml; import com.badlogic.gdx.utils.Xml.Element; -/** - *

        A skin defines graphical resources like {@link NinePatch}, {@link TextureRegion}, {@link Color} and {@link BitmapFont} - * instances as well as widget styles.

        +/**

        + * A skin defines graphical resources like {@link NinePatch}, {@link TextureRegion}, {@link Color} and {@link BitmapFont} + * instances as well as widget styles. + *

        * - *

        Every widget found in this UI API, like {@link Button} or {@link SplitPane} has - * an associated style, like {@link ButtonStyle} or {@link SplitPaneStyle}. These styles are defined in an XML - * file and reference (nine-patch)regions in a single texture, colors and fonts to be used for any widget - * instantiated with that style.

        + *

        + * Every widget found in this UI API, like {@link Button} or {@link SplitPane} has an associated style, like {@link ButtonStyle} + * or {@link SplitPaneStyle}. These styles are defined in an XML file and reference (nine-patch)regions in a single texture, + * colors and fonts to be used for any widget instantiated with that style. + *

        * - *

        This class loads a widget style XML file and exposes all parts defined in it via getter methods. Additionally - * it allows to instantiate the default widgets via convenience methods like {@link Skin#newButton(String, String)}.

        + *

        + * This class loads a widget style XML file and exposes all parts defined in it via getter methods. Additionally it allows to + * instantiate the default widgets via convenience methods like {@link Skin#newButton(String, String)}. + *

        * - *

        Additionally you can instantiate an empty Skin via {@link Skin#Skin(Texture)} and add graphical resources and styles - * programmatically.

        + *

        + * Additionally you can instantiate an empty Skin via {@link Skin#Skin(Texture)} and add graphical resources and styles + * programmatically. + *

        * - *

        The Skin has a couple of resources it manages, namely the {@link Texture} containing all (nine-patch)regions as - * well as all the {@link BitmapFont} instances defined in the XML file. To dispose all resouces use the {@link Skin#dispose()} - * method.

        + *

        + * The Skin has a couple of resources it manages, namely the {@link Texture} containing all (nine-patch)regions as well as all the + * {@link BitmapFont} instances defined in the XML file. To dispose all resouces use the {@link Skin#dispose()} method. + *

        * - *

        A skin XML file has a root element called <skin>. Within this tag there are two elements excepted:

        + *

        + * A skin XML file has a root element called <skin>. Within this tag there are two elements excepted: + *

        * *
          * {@code
        @@ -84,13 +93,16 @@
          * }
          * 
        * - *

        The {@code } element contains the definitions of nine-patches, regions, colors and fonts. - * Every one of these has to have a unique name. When defining a widget style in the {@code } section - * you will reference these.

        + *

        + * The {@code } element contains the definitions of nine-patches, regions, colors and fonts. Every one of these has to + * have a unique name. When defining a widget style in the {@code } section you will reference these. + *

        * - *

        Regions, which are loaded as {@link TextureRegion} instances, define an area in the skin's texture. They - * are specified in pixels, with the origin being in the top left corner of the texture image, with the y-axis - * pointing downwards. Coordinates and sizes are given as integers relative to that coordinate system.

        + *

        + * Regions, which are loaded as {@link TextureRegion} instances, define an area in the skin's texture. They are specified in + * pixels, with the origin being in the top left corner of the texture image, with the y-axis pointing downwards. Coordinates and + * sizes are given as integers relative to that coordinate system. + *

        * *
          * {@code 
        @@ -99,7 +111,9 @@
          * 
        * * - *

        Nine-patches are composed of 9 regions and are defined like this:

        + *

        + * Nine-patches are composed of 9 regions and are defined like this: + *

        * *
          * {@code
        @@ -122,44 +136,58 @@
          * }
          * 
        * - *

        Note that the regions in each column have to have the same width, and the regions in each - * row have to have the same width! + *

        + * Note that the regions in each column have to have the same width, and the regions in each row have to have the same + * width! + * + *

        + * Colors are defined as RGBA values in the range [0,1] like this: + *

        * - *

        Colors are defined as RGBA values in the range [0,1] like this:

        *
          * {@code 
          * 
          * }
          * 
        * - *

        Fonts are defined like this:

        + *

        + * Fonts are defined like this: + *

        + * *
          * {@code 
          * 
          * }
          * 
        * - *

        The font's files have to be internal files {@link Files#internal(String)}, the path given is relative to the - * internal files path (e.g. assets/ on Android, the apps root directory on the desktop).

        + *

        + * The font's files have to be internal files {@link Files#internal(String)}, the path given is relative to the internal files + * path (e.g. assets/ on Android, the apps root directory on the desktop). + *

        + * + *

        + * These four types of graphical resources can then be referenced in widget style definitions via their name. A button style for + * example needs a ninepatch for its background in the "down" (pressed) state, a ninepatch for its background in the "up" + * (unpressed) state and a font and font color to display its label text. A button style could be defined like this: + *

        * - *

        These four types of graphical resources can then be referenced in widget style definitions via their name. A - * button style for example needs a ninepatch for its background in the "down" (pressed) state, a ninepatch for its background - * in the "up" (unpressed) state and a font and font color to display its label text. A button style could be defined like this:

        *
          * {@code
          * 
          * }
        - * 
        + * * - *

        The {@code } would be a child of the {@code } element. Its attributes reference nine-patches, fonts - * and colors from the {@code } element via their names. The above example requires a nine-patch named "button-down-patch" to be - * defined for example.

        + *

        + * The {@code } would be a child of the {@code } element. Its attributes reference nine-patches, fonts + * and colors from the {@code } element via their names. The above example requires a nine-patch named "button-down-patch" + * to be defined for example. + *

        * - *

        Refer to the invidual widget classes like {@link Button}, {@link ComboBox}, {@link SplitPane} and so on to find out - * how to define a style for them in the XML file.

        - * @author mzechner - * - */ + *

        + * Refer to the invidual widget classes like {@link Button}, {@link ComboBox}, {@link SplitPane} and so on to find out how to + * define a style for them in the XML file. + *

        + * @author mzechner */ public class Skin implements Disposable { /** registered widget styles **/ Map ninePatches = new HashMap(); @@ -181,45 +209,38 @@ public class Skin implements Disposable { Map imageToggleButtonStyles = new HashMap(); Map windowStyles = new HashMap(); Texture texture; - - /** - * Creates a new Skin from the given XML skin file and {@link Texture} image. + + /** Creates a new Skin from the given XML skin file and {@link Texture} image. * @param skinFile the XML skin file - * @param textureFile the texture image - */ - public Skin(FileHandle skinFile, FileHandle textureFile) { + * @param textureFile the texture image */ + public Skin (FileHandle skinFile, FileHandle textureFile) { texture = new Texture(textureFile); - texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); + texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); parseSkin(skinFile); } - - /** - * Creates an empty skin, using the given {@link Texture} - * @param texture the Texture - */ - public Skin(Texture texture) { + + /** Creates an empty skin, using the given {@link Texture} + * @param texture the Texture */ + public Skin (Texture texture) { this.texture = texture; } - - /** - * Parses the given XML skin file and adds all assets (regions, patches, colors, fonts) - * and widget styles to this skin. If an asset or widget style with the same name was - * already in the skin it will be overwritten. Widgets already created via this skin - * won't change their style! - * @param skinFile the XML skin file - */ - public void parseSkin(FileHandle skinFile) { + + /** Parses the given XML skin file and adds all assets (regions, patches, colors, fonts) and widget styles to this skin. If an + * asset or widget style with the same name was already in the skin it will be overwritten. Widgets already created via this + * skin won't change their style! + * @param skinFile the XML skin file */ + public void parseSkin (FileHandle skinFile) { try { Xml xml = new Xml(); Element skin = xml.parse(skinFile); parseLibrary(skin); parseWidgetStyles(skin.getChildByName("widgetStyles")); - } catch(Exception e) { + } catch (Exception e) { throw new GdxRuntimeException("Couldn't parse skinFile", e); } } - - protected void parseWidgetStyles(Element styles) { + + protected void parseWidgetStyles (Element styles) { parseButtonStyles(styles); parseCheckBoxStyles(styles); parseLabelStyles(styles); @@ -234,882 +255,747 @@ protected void parseWidgetStyles(Element styles) { parseWindowStyles(styles); parseImageButtonStyles(styles); parseImageToggleButtonStyles(styles); - } + } - private void error(String msg, Element element) { + private void error (String msg, Element element) { throw new GdxRuntimeException(msg + ", element: " + element.toString()); } - + private void parseWindowStyles (Element styles) { - for(Element style: styles.getChildrenByName("window")) { + for (Element style : styles.getChildrenByName("window")) { String name = style.getAttribute("name"); - NinePatch background = getNinePatch(style.getAttribute("background")); + NinePatch background = getNinePatch(style.getAttribute("background")); BitmapFont font = getFont(style.getAttribute("titleFont")); - Color fontColor = getColor(style.getAttribute("titleFontColor")); - - if(name == null) error("No name given for window style", style); - if(background == null) error("No 'background' nine-patch given for window style", style); - if(font == null) error("No 'font' given for window style", style); - if(fontColor == null) error("No 'fontColor' given for window style", style); - + Color fontColor = getColor(style.getAttribute("titleFontColor")); + + if (name == null) error("No name given for window style", style); + if (background == null) error("No 'background' nine-patch given for window style", style); + if (font == null) error("No 'font' given for window style", style); + if (fontColor == null) error("No 'fontColor' given for window style", style); + windowStyles.put(name, new WindowStyle(font, fontColor, background)); } } - - private void parseComboBoxStyles (Element styles) { - for(Element style: styles.getChildrenByName("combobox")) { + + private void parseComboBoxStyles (Element styles) { + for (Element style : styles.getChildrenByName("combobox")) { String name = style.getAttribute("name"); NinePatch background = getNinePatch(style.getAttribute("background")); NinePatch listBackground = getNinePatch(style.getAttribute("listBackground")); NinePatch listSelection = getNinePatch(style.getAttribute("listSelection")); BitmapFont font = getFont(style.getAttribute("font")); - Color fontColor = getColor(style.getAttribute("fontColor")); - - if(name == null) error("No name given for combobox style", style); - if(background == null) error("No 'background' nine-patch given for combobox style", style); - if(listBackground == null) error("No 'listBackground' nine-patch given for combobox style", style); - if(listSelection == null) error("No 'listSelection' nine-patch given for combobox style", style); - if(font == null) error("No 'font' given for combobox style", style); - if(fontColor == null) error("No 'fontColor' given for combobox style", style); - + Color fontColor = getColor(style.getAttribute("fontColor")); + + if (name == null) error("No name given for combobox style", style); + if (background == null) error("No 'background' nine-patch given for combobox style", style); + if (listBackground == null) error("No 'listBackground' nine-patch given for combobox style", style); + if (listSelection == null) error("No 'listSelection' nine-patch given for combobox style", style); + if (font == null) error("No 'font' given for combobox style", style); + if (fontColor == null) error("No 'fontColor' given for combobox style", style); + comboBoxStyles.put(name, new ComboBoxStyle(font, fontColor, background, listBackground, listSelection)); } } - private void parseTextFieldStyles(Element styles) { - for(Element style: styles.getChildrenByName("textfield")) { + private void parseTextFieldStyles (Element styles) { + for (Element style : styles.getChildrenByName("textfield")) { String name = style.getAttribute("name"); NinePatch background = getNinePatch(style.getAttribute("background")); NinePatch cursor = getNinePatch(style.getAttribute("cursor")); BitmapFont font = getFont(style.getAttribute("font")); Color fontColor = getColor(style.getAttribute("fontColor")); TextureRegion selection = getRegion(style.getAttribute("selection")); - - if(name == null) error("No name given for textfield style", style); - if(background == null) error("No 'background' nine-patch given for textfield style", style); - if(cursor == null) error("No 'cursor' nine-patch given for textfield style", style); - if(font == null) error("No 'font' given for textfield style", style); - if(fontColor == null) error("No 'fontColor' given for textfield stye", style); - if(selection == null) error("No 'selection' region given for textfield style", style); - + + if (name == null) error("No name given for textfield style", style); + if (background == null) error("No 'background' nine-patch given for textfield style", style); + if (cursor == null) error("No 'cursor' nine-patch given for textfield style", style); + if (font == null) error("No 'font' given for textfield style", style); + if (fontColor == null) error("No 'fontColor' given for textfield stye", style); + if (selection == null) error("No 'selection' region given for textfield style", style); + textFieldStyles.put(name, new TextFieldStyle(font, fontColor, cursor, selection, background)); } } - private void parseSplitPaneStyles(Element styles) { - for(Element style: styles.getChildrenByName("splitpane")) { + private void parseSplitPaneStyles (Element styles) { + for (Element style : styles.getChildrenByName("splitpane")) { String name = style.getAttribute("name"); - NinePatch handle = getNinePatch(style.getAttribute("handle")); - - if(name == null) error("No name given for splitpane style", style); - if(handle == null) error("No 'handle' given for splitpane style", style); - + NinePatch handle = getNinePatch(style.getAttribute("handle")); + + if (name == null) error("No name given for splitpane style", style); + if (handle == null) error("No 'handle' given for splitpane style", style); + splitPaneStyles.put(name, new SplitPaneStyle(handle)); } } - private void parseScrollPaneStyles(Element styles) { - for(Element style: styles.getChildrenByName("scrollpane")) { + private void parseScrollPaneStyles (Element styles) { + for (Element style : styles.getChildrenByName("scrollpane")) { String name = style.getAttribute("name"); NinePatch background = getNinePatch(style.getAttribute("background")); NinePatch hScroll = getNinePatch(style.getAttribute("hScroll")); NinePatch hScrollKnob = getNinePatch(style.getAttribute("hScrollKnob")); NinePatch vScroll = getNinePatch(style.getAttribute("vScroll")); NinePatch vScrollKnob = getNinePatch(style.getAttribute("vScrollKnob")); - - if(name == null) error("No name given for scrollpane style", style); - if(background == null) error("No 'background' given for scrollpane style", style); - if(hScroll == null) error("No 'hScroll' given for scrollpane style", style); - if(hScrollKnob == null) error("No 'hScrollKnob' given for scrollpane style", style); - if(vScroll == null) error("No 'vScroll' given for scrollpane style", style); - if(vScrollKnob == null) error("No 'vScrollKnob' given for scrollpane style", style); - + + if (name == null) error("No name given for scrollpane style", style); + if (background == null) error("No 'background' given for scrollpane style", style); + if (hScroll == null) error("No 'hScroll' given for scrollpane style", style); + if (hScrollKnob == null) error("No 'hScrollKnob' given for scrollpane style", style); + if (vScroll == null) error("No 'vScroll' given for scrollpane style", style); + if (vScrollKnob == null) error("No 'vScrollKnob' given for scrollpane style", style); + scrollPaneStyles.put(name, new ScrollPaneStyle(background, hScroll, hScrollKnob, vScroll, vScrollKnob)); } } - private void parsePaneStyles(Element styles) { - for(Element style: styles.getChildrenByName("pane")) { + private void parsePaneStyles (Element styles) { + for (Element style : styles.getChildrenByName("pane")) { String name = style.getAttribute("name"); NinePatch patch = getNinePatch(style.getAttribute("background")); - - if(name == null) error("No name given for pane style", style); - if(patch == null) error("No 'background' given for pane style", style); - + + if (name == null) error("No name given for pane style", style); + if (patch == null) error("No 'background' given for pane style", style); + paneStyles.put(name, new PaneStyle(patch)); } } - private void parseListStyles(Element styles) { - for(Element style: styles.getChildrenByName("list")) { + private void parseListStyles (Element styles) { + for (Element style : styles.getChildrenByName("list")) { String name = style.getAttribute("name"); BitmapFont font = getFont(style.getAttribute("font")); Color fontColorUnselected = getColor(style.getAttribute("fontColorUnselected")); Color fontColorSelected = getColor(style.getAttribute("fontColorSelected")); NinePatch selectedPatch = getNinePatch(style.getAttribute("selected")); - - if(name == null) error("No name given for list style", style); - if(font == null) error("No font given for list style", style); - if(fontColorUnselected == null) error("No 'fontColorUnselected' given for list style", style); - if(fontColorSelected == null) error("No 'fontColorSelected' given for list style", style); - if(selectedPatch == null) error("No 'selected' nine-patch given for list style", style); - + + if (name == null) error("No name given for list style", style); + if (font == null) error("No font given for list style", style); + if (fontColorUnselected == null) error("No 'fontColorUnselected' given for list style", style); + if (fontColorSelected == null) error("No 'fontColorSelected' given for list style", style); + if (selectedPatch == null) error("No 'selected' nine-patch given for list style", style); + listStyles.put(name, new ListStyle(font, fontColorSelected, fontColorUnselected, selectedPatch)); } } private void parseImageToggleButtonStyles (Element styles) { - for(Element style: styles.getChildrenByName("imagetogglebutton")) { + for (Element style : styles.getChildrenByName("imagetogglebutton")) { String name = style.getAttribute("name"); NinePatch down = getNinePatch(style.getAttribute("down")); - NinePatch up = getNinePatch(style.getAttribute("up")); - - if(name == null) error("No name given for togglebutton style", style); - if(down == null) error("No 'down' nine-patch given for togglebutton style", style); - if(up == null) error("No 'up' nine-patch given for togglebutton style", style); - + NinePatch up = getNinePatch(style.getAttribute("up")); + + if (name == null) error("No name given for togglebutton style", style); + if (down == null) error("No 'down' nine-patch given for togglebutton style", style); + if (up == null) error("No 'up' nine-patch given for togglebutton style", style); + imageToggleButtonStyles.put(name, new ImageToggleButtonStyle(down, up)); - } + } } - - private void parseToggleButtonStyles(Element styles) { - for(Element style: styles.getChildrenByName("togglebutton")) { + + private void parseToggleButtonStyles (Element styles) { + for (Element style : styles.getChildrenByName("togglebutton")) { String name = style.getAttribute("name"); NinePatch down = getNinePatch(style.getAttribute("down")); NinePatch up = getNinePatch(style.getAttribute("up")); BitmapFont font = getFont(style.getAttribute("font")); Color fontColor = getColor(style.getAttribute("fontColor")); - - if(name == null) error("No name given for togglebutton style", style); - if(down == null) error("No 'down' nine-patch given for togglebutton style", style); - if(up == null) error("No 'up' nine-patch given for togglebutton style", style); - if(font == null) error("No 'font' given for togglebutton style", style); - if(fontColor == null) error("No 'fontColor' given for togglebutton style", style); - + + if (name == null) error("No name given for togglebutton style", style); + if (down == null) error("No 'down' nine-patch given for togglebutton style", style); + if (up == null) error("No 'up' nine-patch given for togglebutton style", style); + if (font == null) error("No 'font' given for togglebutton style", style); + if (fontColor == null) error("No 'fontColor' given for togglebutton style", style); + toggleButtonStyles.put(name, new ToggleButtonStyle(font, fontColor, down, up)); } } - private void parseSliderStyles(Element styles) { - for(Element style: styles.getChildrenByName("slider")) { + private void parseSliderStyles (Element styles) { + for (Element style : styles.getChildrenByName("slider")) { String name = style.getAttribute("name"); NinePatch sliderPatch = getNinePatch(style.getAttribute("slider")); TextureRegion knobPatch = getRegion(style.getAttribute("knob")); - - if(name == null) error("No name given for slider style", style); - if(sliderPatch == null) error("No 'slider' nine-patch given for slider style", style); - if(knobPatch == null) error("No 'knob' region given for slider style", style); + + if (name == null) error("No name given for slider style", style); + if (sliderPatch == null) error("No 'slider' nine-patch given for slider style", style); + if (knobPatch == null) error("No 'knob' region given for slider style", style); sliderStyles.put(name, new SliderStyle(sliderPatch, knobPatch)); } } - private void parseCheckBoxStyles(Element styles) { - for(Element style: styles.getChildrenByName("checkbox")) { + private void parseCheckBoxStyles (Element styles) { + for (Element style : styles.getChildrenByName("checkbox")) { String name = style.getAttribute("name"); BitmapFont font = getFont(style.getAttribute("font")); Color fontColor = getColor(style.getAttribute("fontColor")); TextureRegion checked = getRegion(style.getAttribute("checked")); TextureRegion unchecked = getRegion(style.getAttribute("unchecked")); - - if(name == null) error("No name given for checkbox style", style); - if(font == null) error("No 'font' given for checkbox style", style); - if(fontColor == null) error("No 'fontColor' given for checkbox style", style); - if(checked == null) error("No 'checked' region given for checkbox style", style); - if(unchecked == null) error("No 'unchecked' region given for checkbox style", style); - + + if (name == null) error("No name given for checkbox style", style); + if (font == null) error("No 'font' given for checkbox style", style); + if (fontColor == null) error("No 'fontColor' given for checkbox style", style); + if (checked == null) error("No 'checked' region given for checkbox style", style); + if (unchecked == null) error("No 'unchecked' region given for checkbox style", style); + checkBoxStyles.put(name, new CheckBoxStyle(font, fontColor, checked, unchecked)); } } - private void parseImageButtonStyles (Element styles) { - for(Element style: styles.getChildrenByName("imagebutton")) { + private void parseImageButtonStyles (Element styles) { + for (Element style : styles.getChildrenByName("imagebutton")) { String name = style.getAttribute("name"); NinePatch down = getNinePatch(style.getAttribute("down")); - NinePatch up = getNinePatch(style.getAttribute("up")); - - if(name == null) error("No name given for button style", style); - if(down == null) error("No 'down' nine-patch given for button style", style); - if(up == null) error("No 'up' nine-patch given for button style", style); - + NinePatch up = getNinePatch(style.getAttribute("up")); + + if (name == null) error("No name given for button style", style); + if (down == null) error("No 'down' nine-patch given for button style", style); + if (up == null) error("No 'up' nine-patch given for button style", style); + imageButtonStyles.put(name, new ImageButtonStyle(down, up)); - } + } } - - private void parseButtonStyles(Element styles) { - for(Element style: styles.getChildrenByName("button")) { + + private void parseButtonStyles (Element styles) { + for (Element style : styles.getChildrenByName("button")) { String name = style.getAttribute("name"); NinePatch down = getNinePatch(style.getAttribute("down")); NinePatch up = getNinePatch(style.getAttribute("up")); BitmapFont font = getFont(style.getAttribute("font")); Color fontColor = getColor(style.getAttribute("fontColor")); - - if(name == null) error("No name given for button style", style); - if(down == null) error("No 'down' nine-patch given for button style", style); - if(up == null) error("No 'up' nine-patch given for button style", style); - if(font == null) error("No 'font' nine-patch given for button style", style); - if(fontColor == null) error("No 'fontColor' given for button style", style); - + + if (name == null) error("No name given for button style", style); + if (down == null) error("No 'down' nine-patch given for button style", style); + if (up == null) error("No 'up' nine-patch given for button style", style); + if (font == null) error("No 'font' nine-patch given for button style", style); + if (fontColor == null) error("No 'fontColor' given for button style", style); + buttonStyles.put(name, new ButtonStyle(font, fontColor, down, up)); - } + } } - - private void parseLabelStyles(Element styles) { - for(Element style: styles.getChildrenByName("label")) { + + private void parseLabelStyles (Element styles) { + for (Element style : styles.getChildrenByName("label")) { String name = style.getAttribute("name"); BitmapFont font = getFont(style.getAttribute("font")); Color fontColor = getColor(style.getAttribute("fontColor")); - - if(name == null) error("No name given for label style", style); - if(font == null) error("No 'font' given for label style", style); - if(fontColor == null) error("No 'fontColor' given for label style", style); - + + if (name == null) error("No name given for label style", style); + if (font == null) error("No 'font' given for label style", style); + if (fontColor == null) error("No 'fontColor' given for label style", style); + labelStyles.put(style.getAttribute("name"), new LabelStyle(font, fontColor)); } } - private void parseLibrary(Element skin) { + private void parseLibrary (Element skin) { Element library = skin.getChildByName("library"); parseColors(library); parseNinePatches(library); parseRegions(library); - parseFonts(library); - } - - private void parseColors(Element library) { - for(Element color: library.getChildrenByName("color")) { - Color col = new Color(color.getFloatAttribute("r"), - color.getFloatAttribute("g"), - color.getFloatAttribute("b"), - color.getFloatAttribute("a")); + parseFonts(library); + } + + private void parseColors (Element library) { + for (Element color : library.getChildrenByName("color")) { + Color col = new Color(color.getFloatAttribute("r"), color.getFloatAttribute("g"), color.getFloatAttribute("b"), + color.getFloatAttribute("a")); colors.put(color.getAttribute("name"), col); } } - - private void parseFonts(Element library) { - for(Element font: library.getChildrenByName("font")) { - BitmapFont bitmapFont = new BitmapFont(Gdx.files.internal(font.getAttribute("file")), false); + + private void parseFonts (Element library) { + for (Element font : library.getChildrenByName("font")) { + BitmapFont bitmapFont = new BitmapFont(Gdx.files.internal(font.getAttribute("file")), false); fonts.put(font.getAttribute("name"), bitmapFont); } } - - private void parseRegions(Element library) { - for(Element region: library.getChildrenByName("region")) { + + private void parseRegions (Element library) { + for (Element region : library.getChildrenByName("region")) { regions.put(region.getAttribute("name"), parseRegion(region)); } } - - private void parseNinePatches(Element library) { - for(Element ninePatch: library.getChildrenByName("ninepatch")) { + + private void parseNinePatches (Element library) { + for (Element ninePatch : library.getChildrenByName("ninepatch")) { ninePatches.put(ninePatch.getAttribute("name"), parseNinePatch(ninePatch)); } } - - private NinePatch parseNinePatch(Element ninePatch) { + + private NinePatch parseNinePatch (Element ninePatch) { TextureRegion[] regions = new TextureRegion[9]; Array patches = ninePatch.getChildrenByName("region"); - if(regions.length != 9) error("Nine-patch definition has to have 9 regions", ninePatch); - for(int i = 0; i < regions.length; i++) { + if (regions.length != 9) error("Nine-patch definition has to have 9 regions", ninePatch); + for (int i = 0; i < regions.length; i++) { regions[i] = parseRegion(patches.get(i)); } return new NinePatch(regions); } - - private TextureRegion parseRegion(Element region) { - return new TextureRegion(texture, - region.getIntAttribute("x"), region.getIntAttribute("y"), - region.getIntAttribute("width"), region.getIntAttribute("height")); + + private TextureRegion parseRegion (Element region) { + return new TextureRegion(texture, region.getIntAttribute("x"), region.getIntAttribute("y"), + region.getIntAttribute("width"), region.getIntAttribute("height")); } - - /** - * Returns a {@link Color} with the given name. + + /** Returns a {@link Color} with the given name. * @param name the name - * @return the Color or null - */ - public Color getColor(String name) { + * @return the Color or null */ + public Color getColor (String name) { return colors.get(name); } - - /** - * Adds the {@link Color} with the given name. Overwrites - * and previously stored Color with that name. Will not - * have an effect on widget styles already added to this skin! + + /** Adds the {@link Color} with the given name. Overwrites and previously stored Color with that name. Will not have an effect + * on widget styles already added to this skin! * @param name the name - * @param color the Color - */ - public void addColor(String name, Color color) { + * @param color the Color */ + public void addColor (String name, Color color) { colors.put(name, color); } - - /** - * Returns a {@link NinePatch} with the given name. + + /** Returns a {@link NinePatch} with the given name. * @param name the name - * @return the NinePatch or null - */ - public NinePatch getNinePatch(String name) { + * @return the NinePatch or null */ + public NinePatch getNinePatch (String name) { return ninePatches.get(name); } - - /** - * Adds the {@link NinePatch} with the given name. Overwrites - * and previously stored NinePatch with that name. Will not - * have an effect on widget styles already added to this skin! + + /** Adds the {@link NinePatch} with the given name. Overwrites and previously stored NinePatch with that name. Will not have an + * effect on widget styles already added to this skin! * @param name the name - * @param ninePatch the Color - */ - public void addNinePatch(String name, NinePatch ninePatch) { - ninePatches.put(name, ninePatch); - } - - /** - * Returns a {@link TextureRegion} with the given name. + * @param ninePatch the Color */ + public void addNinePatch (String name, NinePatch ninePatch) { + ninePatches.put(name, ninePatch); + } + + /** Returns a {@link TextureRegion} with the given name. * @param name the name - * @return the TextureRegion or null. - */ - public TextureRegion getRegion(String name) { + * @return the TextureRegion or null. */ + public TextureRegion getRegion (String name) { return regions.get(name); } - - /** - * Adds the {@link TextureRegion} with the given name. Overwrites - * any previously stored TextureRegion with that name. Will not + + /** Adds the {@link TextureRegion} with the given name. Overwrites any previously stored TextureRegion with that name. Will not * have an effect on widget styles already added to this skin! * @param name the name - * @param region the TextureRegion - */ - public void addRegion(String name, TextureRegion region) { + * @param region the TextureRegion */ + public void addRegion (String name, TextureRegion region) { regions.put(name, region); } - - /** - * Returns a {@link BitmapFont} with the given name. + + /** Returns a {@link BitmapFont} with the given name. * @param name the name - * @return the BitmapFont or null. - */ - public BitmapFont getFont(String name) { + * @return the BitmapFont or null. */ + public BitmapFont getFont (String name) { return fonts.get(name); } - - /** - * Adds the {@link BitmapFont} with the given name. Overwrites - * any previously stored BitmapFont with that name. Will not - * have an effect on widget styles already added to this skin! + + /** Adds the {@link BitmapFont} with the given name. Overwrites any previously stored BitmapFont with that name. Will not have + * an effect on widget styles already added to this skin! * @param name the name - * @param font the BitmapFont - */ - public void addFont(String name, BitmapFont font) { - fonts.put(name, font); - } - - /** - * Returns the {@link ButtonStyle} with the given name. + * @param font the BitmapFont */ + public void addFont (String name, BitmapFont font) { + fonts.put(name, font); + } + + /** Returns the {@link ButtonStyle} with the given name. * @param name the name - * @return the ButtonStyle or null - */ - public ButtonStyle getButtonStyle(String name) { + * @return the ButtonStyle or null */ + public ButtonStyle getButtonStyle (String name) { return buttonStyles.get(name); } - - /** - * Adds the {@link ButtonStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link ButtonStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the ButtonStyle - */ - public void addButtonStyle(String name, ButtonStyle style) { + * @param style the ButtonStyle */ + public void addButtonStyle (String name, ButtonStyle style) { buttonStyles.put(name, style); } - - /** - * Returns the {@link ImageButtonStyle} with the given name. + + /** Returns the {@link ImageButtonStyle} with the given name. * @param name the name - * @return the ImageButtonStyle or null - */ - public ImageButtonStyle getImageButtonStyle(String name) { + * @return the ImageButtonStyle or null */ + public ImageButtonStyle getImageButtonStyle (String name) { return imageButtonStyles.get(name); } - - /** - * Adds the {@link ImageButtonStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have + + /** Adds the {@link ImageButtonStyle} with the given name. Overwrites any previously stored style with that name. Will not have * an effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addImageButtonStyle(String name, ImageButtonStyle style) { + * @param style the style */ + public void addImageButtonStyle (String name, ImageButtonStyle style) { imageButtonStyles.put(name, style); } - - /** - * Returns the {@link ImageToggleButtonStyle} with the given name. + + /** Returns the {@link ImageToggleButtonStyle} with the given name. * @param name the name - * @return the ImageToggleButtonStyle or null - */ - public ImageToggleButtonStyle getImageToggleButtonStyle(String name) { + * @return the ImageToggleButtonStyle or null */ + public ImageToggleButtonStyle getImageToggleButtonStyle (String name) { return imageToggleButtonStyles.get(name); } - - /** - * Adds the {@link ImageToggleButtonStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link ImageToggleButtonStyle} with the given name. Overwrites any previously stored style with that name. Will not + * have an effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addImageToggleButtonStyle(String name, ImageToggleButtonStyle style) { + * @param style the style */ + public void addImageToggleButtonStyle (String name, ImageToggleButtonStyle style) { imageToggleButtonStyles.put(name, style); } - - /** - * Returns the {@link CheckBoxStyle} with the given name. + + /** Returns the {@link CheckBoxStyle} with the given name. * @param name the name - * @return the CheckBoxStyle or null - */ - public CheckBoxStyle getCheckBoxStyle(String name) { + * @return the CheckBoxStyle or null */ + public CheckBoxStyle getCheckBoxStyle (String name) { return checkBoxStyles.get(name); } - - /** - * Adds the {@link CheckBoxStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link CheckBoxStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addCheckBoxStyle(String name, CheckBoxStyle style) { - checkBoxStyles.put(name, style); - } - - /** - * Returns the {@link ComboBoxStyle} with the given name. + * @param style the style */ + public void addCheckBoxStyle (String name, CheckBoxStyle style) { + checkBoxStyles.put(name, style); + } + + /** Returns the {@link ComboBoxStyle} with the given name. * @param name the name - * @return the ComboBoxStyle or null - */ - public ComboBoxStyle getComboBoxStyle(String name) { + * @return the ComboBoxStyle or null */ + public ComboBoxStyle getComboBoxStyle (String name) { return comboBoxStyles.get(name); - } - - /** - * Adds the {@link ComboBoxStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + } + + /** Adds the {@link ComboBoxStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addComboBoxStyle(String name, ComboBoxStyle style) { + * @param style the style */ + public void addComboBoxStyle (String name, ComboBoxStyle style) { comboBoxStyles.put(name, style); } - - /** - * Returns the {@link LabelStyle} with the given name. + + /** Returns the {@link LabelStyle} with the given name. * @param name the name - * @return the LabelStyle or null - */ - public LabelStyle getLabelStyle(String name) { + * @return the LabelStyle or null */ + public LabelStyle getLabelStyle (String name) { return labelStyles.get(name); } - - /** - * Adds the {@link LabelStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link LabelStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addLabelStyle(String name, LabelStyle style) { + * @param style the style */ + public void addLabelStyle (String name, LabelStyle style) { labelStyles.put(name, style); } - - /** - * Returns the {@link ListStyle} with the given name. + + /** Returns the {@link ListStyle} with the given name. * @param name the name - * @return the ListStyle or null - */ - public ListStyle getListStyle(String name) { + * @return the ListStyle or null */ + public ListStyle getListStyle (String name) { return listStyles.get(name); } - - /** - * Adds the {@link ListStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link ListStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addListStyle(String name, ListStyle style) { - listStyles.put(name, style); - } - - /** - * Returns the {@link PaneStyle} with the given name. + * @param style the style */ + public void addListStyle (String name, ListStyle style) { + listStyles.put(name, style); + } + + /** Returns the {@link PaneStyle} with the given name. * @param name the name - * @return the PaneStyle or null - */ - public PaneStyle getPaneStyle(String name) { + * @return the PaneStyle or null */ + public PaneStyle getPaneStyle (String name) { return paneStyles.get(name); } - - /** - * Adds the {@link PaneStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link PaneStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addPaneStyle(String name, PaneStyle style) { + * @param style the style */ + public void addPaneStyle (String name, PaneStyle style) { paneStyles.put(name, style); } - - /** - * Returns the {@link ScrollPaneStyle} with the given name. + + /** Returns the {@link ScrollPaneStyle} with the given name. * @param name the name - * @return the ScrollPaneStyle or null - */ - public ScrollPaneStyle getScrollPaneStyle(String name) { + * @return the ScrollPaneStyle or null */ + public ScrollPaneStyle getScrollPaneStyle (String name) { return scrollPaneStyles.get(name); } - - /** - * Adds the {@link ScrollPaneStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have + + /** Adds the {@link ScrollPaneStyle} with the given name. Overwrites any previously stored style with that name. Will not have * an effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addScrollPaneStyle(String name, ScrollPaneStyle style) { + * @param style the style */ + public void addScrollPaneStyle (String name, ScrollPaneStyle style) { scrollPaneStyles.put(name, style); } - - /** - * Returns the {@link SliderStyle} with the given name. + + /** Returns the {@link SliderStyle} with the given name. * @param name the name - * @return the SliderStyle or null - */ - public SliderStyle getSliderStyle(String name) { + * @return the SliderStyle or null */ + public SliderStyle getSliderStyle (String name) { return sliderStyles.get(name); - } - - /** - * Adds the {@link SliderStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + } + + /** Adds the {@link SliderStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addSliderStyle(String name, SliderStyle style) { + * @param style the style */ + public void addSliderStyle (String name, SliderStyle style) { sliderStyles.put(name, style); } - - /** - * Returns the {@link SplitPaneStyle} with the given name. + + /** Returns the {@link SplitPaneStyle} with the given name. * @param name the name - * @return the SplitPaneStyle or null - */ - public SplitPaneStyle getSplitPaneStyle(String name) { + * @return the SplitPaneStyle or null */ + public SplitPaneStyle getSplitPaneStyle (String name) { return splitPaneStyles.get(name); } - - /** - * Adds the {@link SplitPaneStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link SplitPaneStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addSplitPaneStyle(String name, SplitPaneStyle style) { + * @param style the style */ + public void addSplitPaneStyle (String name, SplitPaneStyle style) { splitPaneStyles.put(name, style); } - - /** - * Returns the {@link TextFieldStyle} with the given name. + + /** Returns the {@link TextFieldStyle} with the given name. * @param name the name - * @return the TextFieldStyle or null - */ - public TextFieldStyle getTextFieldStyle(String name) { + * @return the TextFieldStyle or null */ + public TextFieldStyle getTextFieldStyle (String name) { return textFieldStyles.get(name); } - - /** - * Adds the {@link TextFieldStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link TextFieldStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addTextFieldStyle(String name, TextFieldStyle style) { + * @param style the style */ + public void addTextFieldStyle (String name, TextFieldStyle style) { textFieldStyles.put(name, style); } - - /** - * Returns the {@link ToggleButtonStyle} with the given name. + + /** Returns the {@link ToggleButtonStyle} with the given name. * @param name the name - * @return the ToggleButtonStyle or null - */ - public ToggleButtonStyle getToggleButtonStyle(String name) { + * @return the ToggleButtonStyle or null */ + public ToggleButtonStyle getToggleButtonStyle (String name) { return toggleButtonStyles.get(name); - } - - /** - * Adds the {@link ToggleButtonStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have + } + + /** Adds the {@link ToggleButtonStyle} with the given name. Overwrites any previously stored style with that name. Will not have * an effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addToggleButtonStyle(String name, ToggleButtonStyle style) { + * @param style the style */ + public void addToggleButtonStyle (String name, ToggleButtonStyle style) { toggleButtonStyles.put(name, style); } - /** - * Returns the {@link WindowStyle} with the given name. + /** Returns the {@link WindowStyle} with the given name. * @param name the name - * @return the WindowStyle or null - */ - public WindowStyle getWindowStyle(String name) { + * @return the WindowStyle or null */ + public WindowStyle getWindowStyle (String name) { return windowStyles.get(name); } - - /** - * Adds the {@link WindowStyle} with the given name. Overwrites - * any previously stored style with that name. Will not have - * an effect on widgets already created! + + /** Adds the {@link WindowStyle} with the given name. Overwrites any previously stored style with that name. Will not have an + * effect on widgets already created! * @param name the name of the style - * @param style the style - */ - public void addWindowStyle(String name, WindowStyle style) { + * @param style the style */ + public void addWindowStyle (String name, WindowStyle style) { windowStyles.put(name, style); } - - /** - * Creates a new {@link ImageButton}, using the style with 'default'. + + /** Creates a new {@link ImageButton}, using the style with 'default'. * @param name the name of the button * @param image the image to be displayed on the button - * @return the ImageButton - */ - public ImageButton newImageButton(String name, TextureRegion image) { + * @return the ImageButton */ + public ImageButton newImageButton (String name, TextureRegion image) { return newImageButton(name, image, "default"); } - - /** - * Creates a new {@link ImageButton}, using the style with 'default'. + + /** Creates a new {@link ImageButton}, using the style with 'default'. * @param name the name of the button * @param image the image to be displayed on the button * @param style the name of the {@link ImageButtonStyle} - * @return the ImageButton - */ - public ImageButton newImageButton(String name, TextureRegion image, String style) { + * @return the ImageButton */ + public ImageButton newImageButton (String name, TextureRegion image, String style) { return new ImageButton(name, image, imageButtonStyles.get(style)); } - - /** - * Creates a new {@link ImageToggleButton}, using the style with 'default'. + + /** Creates a new {@link ImageToggleButton}, using the style with 'default'. * @param name the name of the button * @param image the image to be displayed on the button - * @return the ImageToggleButton - */ - public ImageToggleButton newImageToggleButton(String name, TextureRegion image) { + * @return the ImageToggleButton */ + public ImageToggleButton newImageToggleButton (String name, TextureRegion image) { return newImageToggleButton(name, image, "default"); } - - /** - * Creates a new {@link ImageToggleButton}, using the style with 'default'. + + /** Creates a new {@link ImageToggleButton}, using the style with 'default'. * @param name the name of the button * @param image the image to be displayed on the button * @param style the name of the {@link ImageToggleButtonStyle} - * @return the ImageButton - */ - public ImageToggleButton newImageToggleButton(String name, TextureRegion image, String style) { + * @return the ImageButton */ + public ImageToggleButton newImageToggleButton (String name, TextureRegion image, String style) { return new ImageToggleButton(name, image, imageToggleButtonStyles.get(style)); } - - /** - * Creates a new {@link Button}, using the style with 'default'. + + /** Creates a new {@link Button}, using the style with 'default'. * @param name the name of the button * @param label the label to be displayed on the button, can be multiline - * @return the Button - */ - public Button newButton(String name, String label) { + * @return the Button */ + public Button newButton (String name, String label) { return newButton(name, label, "default"); } - - /** - * Creates a new {@link Button}, using the given style. + + /** Creates a new {@link Button}, using the given style. * @param name the name of the Button * @param label the label to be displayed on the button, can be multiline * @param style the name of the {@link ButtonStyle} - * @return the Button - */ - public Button newButton(String name, String label, String style) { + * @return the Button */ + public Button newButton (String name, String label, String style) { return new Button(name, label, buttonStyles.get(style)); } - /** - * Creates a new {@link ToggleButton}, using the style named 'default'. + /** Creates a new {@link ToggleButton}, using the style named 'default'. * @param name the name of the toggle button * @param label the label to be displayed on the button, can be multline - * @return the ToggleButton - */ - public ToggleButton newToggleButton(String name, String label) { + * @return the ToggleButton */ + public ToggleButton newToggleButton (String name, String label) { return newToggleButton(name, label, "default"); } - - /** - * Creates a new {@link ToggleButton}, using the given style. + + /** Creates a new {@link ToggleButton}, using the given style. * @param name the name of the toggle button * @param label the label to be displayed on the button, can be multiline * @param style the name of the style - * @return the ToggleButton - */ - public ToggleButton newToggleButton(String name, String label, String style) { + * @return the ToggleButton */ + public ToggleButton newToggleButton (String name, String label, String style) { return new ToggleButton(name, label, toggleButtonStyles.get(style)); } - - /** - * Creates a new {@link CheckBox}, using the style named 'default'. + + /** Creates a new {@link CheckBox}, using the style named 'default'. * @param name the name of the check box * @param label the label to be displayed beside the checkbox, singleline - * @return the CheckBox - */ - public CheckBox newCheckBox(String name, String label) { + * @return the CheckBox */ + public CheckBox newCheckBox (String name, String label) { return new CheckBox(name, label, checkBoxStyles.get("default")); } - - /** - * Creates a new {@link CheckBox}, using the given style. + + /** Creates a new {@link CheckBox}, using the given style. * @param name the name of the check box * @param label the label to be displayed beside the checkbox, singleline * @param style the name of the style - * @return the CheckBox - */ - public CheckBox newCheckBox(String name, String label, String style) { + * @return the CheckBox */ + public CheckBox newCheckBox (String name, String label, String style) { return new CheckBox(name, label, checkBoxStyles.get(style)); } - - /** - * Creates a new {@link Label}, using the style named 'default' + + /** Creates a new {@link Label}, using the style named 'default' * @param name the name of the label * @param label the text to be displayed, can be multiline - * @return the Label - */ - public Label newLabel(String name, String label) { + * @return the Label */ + public Label newLabel (String name, String label) { return new Label(name, label, labelStyles.get("default")); } - - /** - * Creates a new {@link Label}, using the given style. + + /** Creates a new {@link Label}, using the given style. * @param name the name of the label * @param label the text to be displayed, can be multiline * @param style the name of the style - * @return the Label - */ - public Label newLabel(String name, String label, String style) { + * @return the Label */ + public Label newLabel (String name, String label, String style) { return new Label(name, label, labelStyles.get(style)); } - - /** - * Creates a new {@link Slider}, using the style named 'default' + + /** Creates a new {@link Slider}, using the style named 'default' * @param name the name of the slider * @param prefWidth the preferred width of the slider * @param min the mininum value the slider can take on * @param max the maximum value the slider can take on - * @param step the step size between individual slider values, e.g. 1 or 0.1 etc. - * @return the Slider - */ - public Slider newSlider(String name, float prefWidth, float min, float max, float step) { + * @param step the step size between individual slider values, e.g. 1 or 0.1 etc. + * @return the Slider */ + public Slider newSlider (String name, float prefWidth, float min, float max, float step) { return newSlider(name, prefWidth, min, max, step, "default"); } - - /** - * Creates a new {@link Slider}, using the given style. + + /** Creates a new {@link Slider}, using the given style. * @param name the name of the slider * @param prefWidth the preferred width of the slider * @param min the mininum value the slider can take on * @param max the maximum value the slider can take on * @param step the step size between individual slider values, e.g. 1 or 0.1 etc. - * @param style the name of the style. - * @return the Slider - */ - public Slider newSlider(String name, float prefWidth, float min, float max, float step, String style) { + * @param style the name of the style. + * @return the Slider */ + public Slider newSlider (String name, float prefWidth, float min, float max, float step, String style) { return new Slider(name, prefWidth, min, max, step, sliderStyles.get(style)); } - - /** - * Creates a new {@link List}, using the style named 'default' + + /** Creates a new {@link List}, using the style named 'default' * @param name the name of the list * @param entries the String entries to be displayed in the list, singleline - * @return the List - */ - public List newList(String name, String[] entries) { + * @return the List */ + public List newList (String name, String[] entries) { return newList(name, entries, "default"); } - - /** - * Creates a new {@link List}, using the given style. + + /** Creates a new {@link List}, using the given style. * @param name the name of the list * @param entries the String entries to be displayed in the list, singleline * @param style the name of the style - * @return the List - */ - public List newList(String name, String[] entries, String style) { + * @return the List */ + public List newList (String name, String[] entries, String style) { return new List(name, entries, listStyles.get(style)); } - - /** - * Creates a new {@link Pane}, using the style named 'default' + + /** Creates a new {@link Pane}, using the style named 'default' * @param name the name of the pane * @param stage the {@link Stage} this pane will be added to, needed for clipping * @param prefWidth the preferred width * @param prefHeight the preferred height - * @return the Pane - */ - public Pane newPane(String name, Stage stage, int prefWidth, int prefHeight) { + * @return the Pane */ + public Pane newPane (String name, Stage stage, int prefWidth, int prefHeight) { return newPane(name, stage, prefWidth, prefHeight, "default"); } - - /** - * Creates a new {@link Pane}, using the given style. + + /** Creates a new {@link Pane}, using the given style. * @param name the name of the pane * @param stage the {@link Stage} this pane will be added to, needed for clipping * @param prefWidth the preferred width * @param prefHeight the preferred height * @param style the name of the style - * @return the Pane - */ - public Pane newPane(String name, Stage stage, int prefWidth, int prefHeight, String style) { + * @return the Pane */ + public Pane newPane (String name, Stage stage, int prefWidth, int prefHeight, String style) { return new Pane(name, stage, prefWidth, prefHeight, paneStyles.get(style)); } - - /** - * Creates a new {@link ScrollPane}, using the style named 'default' + + /** Creates a new {@link ScrollPane}, using the style named 'default' * @param name the name of the scroll pane * @param stage the {@link Stage} this scroll pane will be added to, needed for clipping * @param widget the {@link Actor} this scroll pane should contain * @param prefWidth the preferred width * @param prefHeight the preferred height - * @return the ScrollPane - */ - public ScrollPane newScrollPane(String name, Stage stage, Actor widget, int prefWidth, int prefHeight) { + * @return the ScrollPane */ + public ScrollPane newScrollPane (String name, Stage stage, Actor widget, int prefWidth, int prefHeight) { return newScrollPane(name, stage, widget, prefWidth, prefHeight, "default"); } - - /** - * Creates a new {@link ScrollPane}, using the given style named. + + /** Creates a new {@link ScrollPane}, using the given style named. * @param name the name of the scroll pane * @param stage the {@link Stage} this scroll pane will be added to, needed for clipping * @param widget the {@link Actor} this scroll pane should contain * @param prefWidth the preferred width * @param prefHeight the preferred height * @param style the name of the style - * @return the ScrollPane - */ - public ScrollPane newScrollPane(String name, Stage stage, Actor widget, int prefWidth, int prefHeight, String style) { + * @return the ScrollPane */ + public ScrollPane newScrollPane (String name, Stage stage, Actor widget, int prefWidth, int prefHeight, String style) { return new ScrollPane(name, stage, widget, prefWidth, prefHeight, scrollPaneStyles.get(style)); - } - - /** - * Creates a new {@link SplitPane}, using the given style. There is no - * 'default' version of this method as a vertical split pane is likely to - * use a different style than a horizontal split pane. + } + + /** Creates a new {@link SplitPane}, using the given style. There is no 'default' version of this method as a vertical split + * pane is likely to use a different style than a horizontal split pane. * * @param name the name of the split pane * @param stage the {@link Stage} this split pane will be added to, needed for clipping @@ -1119,97 +1005,82 @@ public ScrollPane newScrollPane(String name, Stage stage, Actor widget, int pref * @param prefWidth the preferred width * @param prefHeight the preferred height * @param style the name of the style - * @return the SplitPane - */ - public SplitPane newSplitPane(String name, Stage stage, Actor firstWidget, Actor secondWidget, boolean vertical, int prefWidth, int prefHeight, String style) { + * @return the SplitPane */ + public SplitPane newSplitPane (String name, Stage stage, Actor firstWidget, Actor secondWidget, boolean vertical, + int prefWidth, int prefHeight, String style) { return new SplitPane(name, stage, firstWidget, secondWidget, vertical, prefWidth, prefHeight, splitPaneStyles.get(style)); } - - /** - * Creates a new {@link TextField}, using the style named 'default'. + + /** Creates a new {@link TextField}, using the style named 'default'. * @param name the name of the text field * @param prefWidth the preferred width - * @return the TextField - */ - public TextField newTextField(String name, float prefWidth) { + * @return the TextField */ + public TextField newTextField (String name, float prefWidth) { return newTextField(name, prefWidth, "default"); } - - /** - * Creates a new {@link TextField}, using the given style. + + /** Creates a new {@link TextField}, using the given style. * @param name the name of the text field * @param prefWidth the preferred width * @param style the name of the style - * @return the TextField - */ - public TextField newTextField(String name, float prefWidth, String style) { + * @return the TextField */ + public TextField newTextField (String name, float prefWidth, String style) { return new TextField(name, prefWidth, textFieldStyles.get(style)); } - - /** - * Creates a new {@link ComboBox}, using the style named 'default' + + /** Creates a new {@link ComboBox}, using the style named 'default' * @param name the name of the combo box * @param entries the String entries to be displayed in the combobox * @param stage the {@link Stage} this combobox will be added to, needed for clipping and displaying the selection list - * @return the ComboBox - */ - public ComboBox newComboBox(String name, String[] entries, Stage stage) { + * @return the ComboBox */ + public ComboBox newComboBox (String name, String[] entries, Stage stage) { return newComboBox(name, entries, stage, "default"); } - - /** - * Creates a new {@link ComboBox}, using the given style + + /** Creates a new {@link ComboBox}, using the given style * @param name the name of the combo box * @param entries the String entries to be displayed in the combobox * @param stage the {@link Stage} this combobox will be added to, needed for clipping and displaying the selection list * @param style the name of the style - * @return the ComboBox - */ - public ComboBox newComboBox(String name, String[] entries, Stage stage, String style) { + * @return the ComboBox */ + public ComboBox newComboBox (String name, String[] entries, Stage stage, String style) { return new ComboBox(name, entries, stage, comboBoxStyles.get(style)); } - - /** - * Creates a new {@link Window}, using the style named 'default' + + /** Creates a new {@link Window}, using the style named 'default' * @param name the name of the window * @param stage the {@link Stage} this window will be added to, needed for clipping * @param title the title of this window * @param width the width of this window * @param height the height of this window - * @return the Window - */ + * @return the Window */ public Window newWindow (String name, Stage stage, String title, int width, int height) { return newWindow(name, stage, title, width, height, "default"); } - - /** - * Creates a new {@link Window}, using the given style named. + + /** Creates a new {@link Window}, using the given style named. * @param name the name of the window * @param stage the {@link Stage} this window will be added to, needed for clipping * @param title the title of this window * @param width the width of this window * @param height the height of this window * @param style the name of the style - * @return the Window - */ + * @return the Window */ public Window newWindow (String name, Stage stage, String title, int width, int height, String style) { return new Window(name, stage, title, width, height, windowStyles.get(style)); } - - /** - * Disposes the {@link Texture} and all {@link BitmapFont} instances of this Skin. - */ - @Override public void dispose() { + + /** Disposes the {@link Texture} and all {@link BitmapFont} instances of this Skin. */ + @Override + public void dispose () { texture.dispose(); - for(BitmapFont font: fonts.values()) { + for (BitmapFont font : fonts.values()) { font.dispose(); } } - /** - * @return the {@link Texture} containing all {@link NinePatch} and {@link TextureRegion} pixels of this Skin. - */ - public Texture getTexture() { + /** @return the {@link Texture} containing all {@link NinePatch} and {@link TextureRegion} pixels of this Skin. */ + public Texture getTexture () { return texture; } -} \ No newline at end of file +} diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Slider.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Slider.java index bbc31916c48..1c07147d29e 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Slider.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Slider.java @@ -13,34 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; -import com.badlogic.gdx.graphics.Color; -import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor; -import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle; -/** - * A value slider. +/** A value slider. * - *

        Functionality

        - * A slider lets you select a value within a range (min, max), with stepping between each value the slider represents. - * To listen for changes of the slider value one can register a {@link ValueChangedListener} with the slider. + *

        Functionality

        A slider lets you select a value within a range (min, max), with stepping between each value the slider + * represents. To listen for changes of the slider value one can register a {@link ValueChangedListener} with the slider. * - *

        Layout

        - * A slider's (preferred) width and height are determined by the parameter past to its constructor as well as the maximum - * height of the {@link NinePatch} and {@link TextureRegion} involved in the display of the slider. Use {@link #setPrefSize(int, int)} to programmatically change the size - * to your liking. In case the width and height you set are to small you will see artifacts.

        + *

        Layout

        A slider's (preferred) width and height are determined by the parameter past to its constructor as well as the + * maximum height of the {@link NinePatch} and {@link TextureRegion} involved in the display of the slider. Use + * {@link #setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set are to + * small you will see artifacts.

        * * The slider background will only be stretched in the x-axis. The slider handle will be centered on the background vertically. * - *

        Style

        - * A slider is a {@link Widget} displaying a horizontal background {@link NinePatch}, stretched on the x-axis and using the total - * height of the NinePatch on the y-axis, as well as a TextureRegion for the slider handle. The style is defined via an instance - * of {@link SliderStyle}, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        A slider is a {@link Widget} displaying a horizontal background {@link NinePatch}, stretched on the x-axis and + * using the total height of the NinePatch on the y-axis, as well as a TextureRegion for the slider handle. The style is defined + * via an instance of {@link SliderStyle}, which can be either done programmatically or via a {@link Skin}.

        * * A Slider's style definition in a skin XML file should look like this: * @@ -53,78 +48,73 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newSlider(String, float, float, float, float, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newSlider(String, float, float, float, float, String)}.
        • *
        • The slider attribute references a {@link NinePatch} by name, to be used as the slider's background
        • - *
        • The knob attribute references a {@link TextureRegion} by name, to be used as the slider's handle
        • * - *
        + *
      • The knob attribute references a {@link TextureRegion} by name, to be used as the slider's handle
      • * + * * - * @author mzechner - * - */ + * @author mzechner */ public class Slider extends Widget { final SliderStyle style; float min; float max; float steps; - float value; + float value; float sliderPos; ValueChangedListener listener = null; - - /** - * Creates a new slider. It's width is determined by the given prefWidth parameter, - * its height is determined by the maximum of the height of either the slider {@link NinePatch} - * or slider handle {@link TextureRegion}. The min and max values determine the range the values - * of this slider can take on, the steps parameter specifies the distance between individual values. - * E.g. min could be 4, max could be 10 and steps could be 0.2, giving you a total of 30 values, 4.0 - * 4.2, 4.4 and so on. + + /** Creates a new slider. It's width is determined by the given prefWidth parameter, its height is determined by the maximum of + * the height of either the slider {@link NinePatch} or slider handle {@link TextureRegion}. The min and max values determine + * the range the values of this slider can take on, the steps parameter specifies the distance between individual values. E.g. + * min could be 4, max could be 10 and steps could be 0.2, giving you a total of 30 values, 4.0 4.2, 4.4 and so on. * @param name the name * @param prefWidth the (preferred) width * @param min the minimum value * @param max the maximum value * @param steps the step size between values - * @param style the {@link SliderStyle} - */ - public Slider(String name, float prefWidth, float min, float max, float steps, SliderStyle style) { + * @param style the {@link SliderStyle} */ + public Slider (String name, float prefWidth, float min, float max, float steps, SliderStyle style) { super(name, prefWidth, 0); this.style = style; - if(min > max) throw new IllegalArgumentException("min must be > max"); - if(steps < 0) throw new IllegalArgumentException("unit must be > 0"); + if (min > max) throw new IllegalArgumentException("min must be > max"); + if (steps < 0) throw new IllegalArgumentException("unit must be > 0"); this.min = min; this.max = max; this.steps = steps; - this.value = min; + this.value = min; layout(); this.width = prefWidth; this.height = prefHeight; - } + } @Override - public void layout() { + public void layout () { prefHeight = Math.max(style.knob.getRegionHeight(), style.slider.getTotalHeight()); invalidated = false; } @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final TextureRegion knob = style.knob; final NinePatch slider = style.slider; - - if(invalidated) layout(); - + + if (invalidated) layout(); + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); - sliderPos = (value-min) / (max-min) * (width - knob.getRegionWidth()); + sliderPos = (value - min) / (max - min) * (width - knob.getRegionWidth()); sliderPos = Math.max(0, sliderPos); sliderPos = Math.min(width - knob.getRegionWidth(), sliderPos); - + float maxHeight = Math.max(knob.getRegionHeight(), slider.getTotalHeight()); slider.draw(batch, x, y + (int)((maxHeight - slider.getTotalHeight()) * 0.5f), width, slider.getTotalHeight()); batch.draw(knob, x + sliderPos, y + (int)((maxHeight - knob.getRegionHeight()) * 0.5f)); } @Override - public boolean touchDown(float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { calculateSliderPosAndValue(x); parent.focus(this, pointer); return true; @@ -133,102 +123,88 @@ public boolean touchDown(float x, float y, int pointer) { } @Override - public boolean touchUp(float x, float y, int pointer) { - if(pointer != 0) return false; - if(parent.focusedActor[0] == this) { + public boolean touchUp (float x, float y, int pointer) { + if (pointer != 0) return false; + if (parent.focusedActor[0] == this) { calculateSliderPosAndValue(x); parent.focus(null, pointer); return true; } - return false; + return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { - if(pointer != 0) return false; - if(parent.focusedActor[0] == this) { + public boolean touchDragged (float x, float y, int pointer) { + if (pointer != 0) return false; + if (parent.focusedActor[0] == this) { calculateSliderPosAndValue(x); return true; } return false; } - private void calculateSliderPosAndValue(float x) { + private void calculateSliderPosAndValue (float x) { final TextureRegion knob = style.knob; - + sliderPos = x - knob.getRegionWidth() / 2; sliderPos = Math.max(0, sliderPos); sliderPos = Math.min(width - knob.getRegionWidth(), sliderPos); value = min + (max - min) * (sliderPos / (width - knob.getRegionWidth())); - if(listener != null) listener.changed(this, getValue()); + if (listener != null) listener.changed(this, getValue()); } - + @Override - public Actor hit(float x, float y) { - return x > 0 && x < width && y > 0 && y < height?this: null; + public Actor hit (float x, float y) { + return x > 0 && x < width && y > 0 && y < height ? this : null; } - /** - * Defines the style of a slider, see {@link Slider}. - * @author mzechner - * - */ + + /** Defines the style of a slider, see {@link Slider}. + * @author mzechner */ public static class SliderStyle { NinePatch slider; TextureRegion knob; - - public SliderStyle(NinePatch sliderPatch, TextureRegion knobRegion) { + + public SliderStyle (NinePatch sliderPatch, TextureRegion knobRegion) { this.slider = sliderPatch; this.knob = knobRegion; } } - - /** - * Interface to listen for changes of the value of the slider. - * @author mzechner - * - */ + + /** Interface to listen for changes of the value of the slider. + * @author mzechner */ public interface ValueChangedListener { - public void changed(Slider slider, float value); + public void changed (Slider slider, float value); } - - /** - * Sets the {@link ValueChangedListener} of this slider. + + /** Sets the {@link ValueChangedListener} of this slider. * @param listener the listener or null - * @return this Slider for chaining - */ - public Slider setValueChangedListener(ValueChangedListener listener) { + * @return this Slider for chaining */ + public Slider setValueChangedListener (ValueChangedListener listener) { this.listener = listener; return this; } - - /** - * @return the current value of the slider - */ - public float getValue() { - return (float)Math.floor(value / steps) * steps; - } - - /** - * Sets the value of this slider - * @param value the value - */ - public void setValue(float value) { - if(value < min || value > max) throw new IllegalArgumentException("value must be >= min && <= max"); - this.value = value; - if(listener != null) listener.changed(this, getValue()); + + /** @return the current value of the slider */ + public float getValue () { + return (float)Math.floor(value / steps) * steps; } - - /** - * Sets the range of this slider. The slider's current value is - * reset to min. + + /** Sets the value of this slider + * @param value the value */ + public void setValue (float value) { + if (value < min || value > max) throw new IllegalArgumentException("value must be >= min && <= max"); + this.value = value; + if (listener != null) listener.changed(this, getValue()); + } + + /** Sets the range of this slider. The slider's current value is reset to min. * @param min the minimum value - * @param max the maximum value - */ - public void setRange(float min, float max) { - if(min >= max) throw new IllegalArgumentException("min must be < max"); + * @param max the maximum value */ + public void setRange (float min, float max) { + if (min >= max) throw new IllegalArgumentException("min must be < max"); this.min = min; this.max = max; this.value = min; - if(listener != null) listener.changed(this, getValue()); + if (listener != null) listener.changed(this, getValue()); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SplitPane.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SplitPane.java index 98bb7e689a0..9240c378343 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SplitPane.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SplitPane.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.g2d.NinePatch; @@ -28,20 +29,19 @@ import com.badlogic.gdx.scenes.scene2d.ui.utils.ScissorStack; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * A special container holding two children and allowing to define the space used by each. +/** A special container holding two children and allowing to define the space used by each. * - *

        Functionality

        - * A SplitPane can embedd to {@link Actor} instances (or {@link Widget} or {@link Table} instances for that matter), separated - * by a split handle, either vertically or horizontally. Both widgets will be sized so that they take up their respective space - * within the SplitPane. The handle can be moved via dragging to vary the size available to each widget.

        + *

        Functionality

        A SplitPane can embedd to {@link Actor} instances (or {@link Widget} or {@link Table} instances for that + * matter), separated by a split handle, either vertically or horizontally. Both widgets will be sized so that they take up their + * respective space within the SplitPane. The handle can be moved via dragging to vary the size available to each widget.

        * - * The amount of available space for the first Actor is given between 0 and 1, 0 meaning no space, 1 meaning all the space. The amount - * of space available for the second Actor is computed as 1 minus the amount available to the second Actor. One can set - * the value for the first widget via {@link #setSplitAmount(float)} manually, the amount for the second Actor is derrived - * automatically. The range of the split amount can be defined via {@link #setMinSplitAmount(float)} and {@link #setMaxSplitAmount(float)}. + * The amount of available space for the first Actor is given between 0 and 1, 0 meaning no space, 1 meaning all the space. The + * amount of space available for the second Actor is computed as 1 minus the amount available to the second Actor. One can set the + * value for the first widget via {@link #setSplitAmount(float)} manually, the amount for the second Actor is derrived + * automatically. The range of the split amount can be defined via {@link #setMinSplitAmount(float)} and + * {@link #setMaxSplitAmount(float)}. * - * The SplitPane will employ scissoring (clipping) to make sure none of the two Actors can render outside of their allocated + * The SplitPane will employ scissoring (clipping) to make sure none of the two Actors can render outside of their allocated * space.

        * * Note: do not use any of the {@link #addActor(Actor)} or {@link #removeActor(Actor)} methods with this class! The embedded @@ -49,16 +49,14 @@ * * The embedded Actors will always be resized to fill their entire space within the SplitPane

        * - *

        Layout

        - * The (preferred) width and height of a split pane is determined by the size passed to its constructor. The contained - * Actor instances size will be set to their respective available area within the split pane.

        + *

        Layout

        The (preferred) width and height of a split pane is determined by the size passed to its constructor. The + * contained Actor instances size will be set to their respective available area within the split pane.

        * - *

        Style

        - * A SplitPane is a {@link Group} displaying two Actor instances either left and right or top and bottom, depending on - * whether the SplitPane is a horizontal split pane or a vertical split pane. Additionally a {@link NinePatch} is used - * to render the SplitPane handle, either a horizontal or vertical strip. In case the SplitPane is a horizontal one the - * NinePatch will be stretched vertically, and its width will be the value returned by {@link NinePatch#getTotalWidth()}. - * In case the SplitPane is a vertical one it will be stretched horizontally and its height will be the value returned by + *

        Style

        A SplitPane is a {@link Group} displaying two Actor instances either left and right or top and bottom, depending + * on whether the SplitPane is a horizontal split pane or a vertical split pane. Additionally a {@link NinePatch} is used to + * render the SplitPane handle, either a horizontal or vertical strip. In case the SplitPane is a horizontal one the NinePatch + * will be stretched vertically, and its width will be the value returned by {@link NinePatch#getTotalWidth()}. In case the + * SplitPane is a vertical one it will be stretched horizontally and its height will be the value returned by * {@link NinePatch#getTotalHeight()}.

        * * A SplitPane's style definition in a skin XML file should look like this: @@ -71,19 +69,18 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newSplitPane(String, Stage, Actor, Actor, boolean, int, int, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newSplitPane(String, Stage, Actor, Actor, boolean, int, int, String)}.
        • *
        • The handle attribute references a {@link NinePatch} by name, to be used as the split pane's handle
        • *
        - * @author mzechner - * - */ + * @author mzechner */ public class SplitPane extends Group implements Layout { final SplitPaneStyle style; float prefWidth; float prefHeight; - + boolean invalidated = false; - + boolean vertical; float splitAmount = 0.5f; float minAmount = 0; @@ -95,12 +92,10 @@ public class SplitPane extends Group implements Layout { Rectangle firstWidgetBounds = new Rectangle(); Rectangle secondWidgetBounds = new Rectangle(); Rectangle handleBounds = new Rectangle(); - Rectangle[] scissors = new Rectangle[] { new Rectangle(), new Rectangle() }; + Rectangle[] scissors = new Rectangle[] {new Rectangle(), new Rectangle()}; boolean touchDrag = false; - /** - * Creates a new SplitPane. It's width and height is determined by the prefWidth and prefHeight - * parameters. + /** Creates a new SplitPane. It's width and height is determined by the prefWidth and prefHeight parameters. * @param name the name * @param stage the stage, used for clipping * @param firstWidget the first {@link Actor} @@ -108,9 +103,9 @@ public class SplitPane extends Group implements Layout { * @param vertical whether this is a vertical SplitPane or not (horizontal) * @param prefWidth the (preferred) width * @param prefHeight the (preferred) height - * @param style the {@link SplitPaneStyle} - */ - public SplitPane(String name, Stage stage, Actor firstWidget, Actor secondWidget, boolean vertical, int prefWidth, int prefHeight, SplitPaneStyle style) { + * @param style the {@link SplitPaneStyle} */ + public SplitPane (String name, Stage stage, Actor firstWidget, Actor secondWidget, boolean vertical, int prefWidth, + int prefHeight, SplitPaneStyle style) { super(name); this.stage = stage; this.style = style; @@ -118,150 +113,153 @@ public SplitPane(String name, Stage stage, Actor firstWidget, Actor secondWidget this.secondWidget = secondWidget; this.prefWidth = this.width = prefWidth; this.prefHeight = this.height = prefHeight; - this.vertical = vertical; - + this.vertical = vertical; + this.addActor(firstWidget); - this.addActor(secondWidget); + this.addActor(secondWidget); layout(); - } + } - @Override - public void layout() { - if(firstWidget instanceof Layout) { + @Override + public void layout () { + if (firstWidget instanceof Layout) { Layout layout = (Layout)firstWidget; layout.layout(); firstWidget.width = layout.getPrefWidth(); - firstWidget.height = layout.getPrefHeight(); + firstWidget.height = layout.getPrefHeight(); } - - if(secondWidget instanceof Layout) { + + if (secondWidget instanceof Layout) { Layout layout = (Layout)secondWidget; - layout.layout(); + layout.layout(); secondWidget.width = layout.getPrefWidth(); - secondWidget.height = layout.getPrefHeight(); + secondWidget.height = layout.getPrefHeight(); } - + invalidated = false; - } + } @Override - public void invalidate() { - if(firstWidget instanceof Layout) ((Layout)firstWidget).invalidate(); - if(secondWidget instanceof Layout) ((Layout)secondWidget).invalidate(); + public void invalidate () { + if (firstWidget instanceof Layout) ((Layout)firstWidget).invalidate(); + if (secondWidget instanceof Layout) ((Layout)secondWidget).invalidate(); invalidated = true; } @Override - public float getPrefWidth() { + public float getPrefWidth () { return prefHeight; } @Override - public float getPrefHeight() { + public float getPrefHeight () { return prefWidth; } - - private void calculateBoundsAndPositions(Matrix4 transform) { - if(oldSplitAmount != splitAmount) { + + private void calculateBoundsAndPositions (Matrix4 transform) { + if (oldSplitAmount != splitAmount) { oldSplitAmount = splitAmount; - invalidate(); + invalidate(); } - - if(!vertical) calculateHorizBoundsAndPositions(); - else calculateVertBoundsAndPositions(); - + + if (!vertical) + calculateHorizBoundsAndPositions(); + else + calculateVertBoundsAndPositions(); + boolean layoutFirst = false; - boolean layoutSecond = false; - if(firstWidget.width != firstWidgetBounds.width || firstWidget.height != firstWidgetBounds.height) { + boolean layoutSecond = false; + if (firstWidget.width != firstWidgetBounds.width || firstWidget.height != firstWidgetBounds.height) { layoutFirst = true; - } - if(secondWidget.width != secondWidgetBounds.width || secondWidget.height != secondWidgetBounds.height) { + } + if (secondWidget.width != secondWidgetBounds.width || secondWidget.height != secondWidgetBounds.height) { layoutSecond = true; } - + firstWidget.x = firstWidgetBounds.x; firstWidget.y = firstWidgetBounds.y; firstWidget.width = firstWidgetBounds.width; firstWidget.height = firstWidgetBounds.height; - + secondWidget.x = secondWidgetBounds.x; secondWidget.y = secondWidgetBounds.y; secondWidget.width = secondWidgetBounds.width; - secondWidget.height = secondWidgetBounds.height; - - if(layoutFirst && firstWidget instanceof Layout) { - ((Layout)firstWidget).invalidate(); + secondWidget.height = secondWidgetBounds.height; + + if (layoutFirst && firstWidget instanceof Layout) { + ((Layout)firstWidget).invalidate(); } - - if(layoutSecond && secondWidget instanceof Layout) { - ((Layout)secondWidget).invalidate(); + + if (layoutSecond && secondWidget instanceof Layout) { + ((Layout)secondWidget).invalidate(); } ScissorStack.calculateScissors(stage.getCamera(), transform, firstWidgetBounds, scissors[0]); ScissorStack.calculateScissors(stage.getCamera(), transform, secondWidgetBounds, scissors[1]); } - - private void calculateHorizBoundsAndPositions() { + + private void calculateHorizBoundsAndPositions () { NinePatch handle = style.handle; - + float availWidth = width - handle.getTotalWidth(); float leftAreaWidth = (int)(availWidth * splitAmount); float rightAreaWidth = (availWidth - leftAreaWidth); float handleWidth = (handle.getTotalWidth()); - + firstWidgetBounds.set(0, 0, leftAreaWidth, height); secondWidgetBounds.set(leftAreaWidth + handleWidth, 0, rightAreaWidth, height); - handleBounds.set(leftAreaWidth, 0, handleWidth, height); + handleBounds.set(leftAreaWidth, 0, handleWidth, height); } - - private void calculateVertBoundsAndPositions() { + + private void calculateVertBoundsAndPositions () { NinePatch handle = style.handle; - + float availHeight = height - handle.getTotalHeight(); float topAreaHeight = (int)(availHeight * splitAmount); float bottomAreaHeight = (availHeight - topAreaHeight); float handleHeight = handle.getTotalHeight(); - + firstWidgetBounds.set(0, height - topAreaHeight, width, topAreaHeight); secondWidgetBounds.set(0, 0, width, bottomAreaHeight); - handleBounds.set(0, bottomAreaHeight, width, handleHeight); + handleBounds.set(0, bottomAreaHeight, width, handleHeight); } - + @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { NinePatch handle = style.handle; - - setupTransform(batch); - calculateBoundsAndPositions(batch.getTransformMatrix()); - for(int i = 0; i < children.size(); i++) { - ScissorStack.pushScissors(scissors[i]); + + setupTransform(batch); + calculateBoundsAndPositions(batch.getTransformMatrix()); + for (int i = 0; i < children.size(); i++) { + ScissorStack.pushScissors(scissors[i]); drawChild(children.get(i), batch, parentAlpha); ScissorStack.popScissors(); } batch.setColor(color.r, color.g, color.b, color.a); handle.draw(batch, handleBounds.x, handleBounds.y, handleBounds.width, handleBounds.height); - if(invalidated) layout(); + if (invalidated) layout(); resetTransform(batch); } - + Vector2 lastPoint = new Vector2(); Vector2 handlePos = new Vector2(); + @Override public boolean touchDown (float x, float y, int pointer) { - if(pointer != 0) return false; - if(handleBounds.contains(x, y)) { + if (pointer != 0) return false; + if (handleBounds.contains(x, y)) { touchDrag = true; lastPoint.set(x, y); handlePos.set(handleBounds.x, handleBounds.y); focus(this, 0); return true; } - return super.touchDown(x, y, pointer); + return super.touchDown(x, y, pointer); } @Override public boolean touchUp (float x, float y, int pointer) { - if(pointer != 0) return false; - if(touchDrag) { + if (pointer != 0) return false; + if (touchDrag) { focus(null, 0); touchDrag = false; return true; @@ -272,101 +270,89 @@ public boolean touchUp (float x, float y, int pointer) { @Override public boolean touchDragged (float x, float y, int pointer) { NinePatch handle = style.handle; - - if(pointer != 0) return false; - if(touchDrag) { - if(!vertical) { - float delta = x - lastPoint.x; + + if (pointer != 0) return false; + if (touchDrag) { + if (!vertical) { + float delta = x - lastPoint.x; float availWidth = width - handle.getTotalWidth(); float dragX = handlePos.x + delta; handlePos.x = dragX; dragX = Math.max(0, dragX); - dragX = Math.min(availWidth, dragX); + dragX = Math.min(availWidth, dragX); splitAmount = dragX / availWidth; - if(splitAmount < minAmount) splitAmount = minAmount; - if(splitAmount > maxAmount) splitAmount = maxAmount; + if (splitAmount < minAmount) splitAmount = minAmount; + if (splitAmount > maxAmount) splitAmount = maxAmount; invalidate(); - lastPoint.set(x, y); + lastPoint.set(x, y); } else { float delta = y - lastPoint.y; float availHeight = height - handle.getTotalHeight(); float dragY = handlePos.y + delta; handlePos.y = dragY; dragY = Math.max(0, dragY); - dragY = Math.min(availHeight, dragY); - splitAmount = 1 - (dragY / availHeight); - if(splitAmount < minAmount) splitAmount = minAmount; - if(splitAmount > maxAmount) splitAmount = maxAmount; + dragY = Math.min(availHeight, dragY); + splitAmount = 1 - (dragY / availHeight); + if (splitAmount < minAmount) splitAmount = minAmount; + if (splitAmount > maxAmount) splitAmount = maxAmount; invalidate(); lastPoint.set(x, y); } return true; - } else return super.touchDragged(x, y, pointer); + } else + return super.touchDragged(x, y, pointer); } - + @Override - public Actor hit(float x, float y) { - return x > 0 && x < width && y > 0 && y < height?this: null; + public Actor hit (float x, float y) { + return x > 0 && x < width && y > 0 && y < height ? this : null; } - - /** - * Defines the style of a split pane, see {@link SplitPane} - * @author mzechner - * - */ + + /** Defines the style of a split pane, see {@link SplitPane} + * @author mzechner */ public static class SplitPaneStyle { public final NinePatch handle; - - public SplitPaneStyle(NinePatch handle) { + + public SplitPaneStyle (NinePatch handle) { this.handle = handle; } } - - /** - * Sets the split amount - * @param split the split amount between 0 and 1 - */ - public void setSplitAmount(float split) { + + /** Sets the split amount + * @param split the split amount between 0 and 1 */ + public void setSplitAmount (float split) { this.splitAmount = Math.max(Math.min(maxAmount, split), minAmount); invalidate(); } - - /** - * @return the split amount - */ - public float getSplit() { + + /** @return the split amount */ + public float getSplit () { return splitAmount; } - - /** - * Sets the minimum split amount - * @param minAmount the minimum split amount - */ - public void setMinSplitAmount(float minAmount) { - if(minAmount < 0) throw new GdxRuntimeException("minAmount has to be >= 0"); - if(minAmount >= maxAmount) throw new GdxRuntimeException("minAmount has to be < maxAmount"); - this.minAmount = minAmount; + + /** Sets the minimum split amount + * @param minAmount the minimum split amount */ + public void setMinSplitAmount (float minAmount) { + if (minAmount < 0) throw new GdxRuntimeException("minAmount has to be >= 0"); + if (minAmount >= maxAmount) throw new GdxRuntimeException("minAmount has to be < maxAmount"); + this.minAmount = minAmount; } - - /** - * Sets the maximum split amount - * @param maxAmount the maximum split amount - */ - public void setMaxSplitAmount(float maxAmount) { - if(maxAmount > 1) throw new GdxRuntimeException("maxAmount has to be >= 0"); - if(maxAmount <= minAmount) throw new GdxRuntimeException("maxAmount has to be > minAmount"); + + /** Sets the maximum split amount + * @param maxAmount the maximum split amount */ + public void setMaxSplitAmount (float maxAmount) { + if (maxAmount > 1) throw new GdxRuntimeException("maxAmount has to be >= 0"); + if (maxAmount <= minAmount) throw new GdxRuntimeException("maxAmount has to be > minAmount"); this.maxAmount = maxAmount; } - - /** - * Sets the {@link Actor} instances embedded in this scroll pane. Invalidates - * the new Actor instances if they derrive from {@link Widget} + + /** Sets the {@link Actor} instances embedded in this scroll pane. Invalidates the new Actor instances if they derrive from + * {@link Widget} * @param firstWidget the first Actor - * @params secondtWidget the second Actor - */ - public void setWidgets(Actor firstWidget, Actor secondWidget) { - if(firstWidget == null) throw new IllegalArgumentException("firstWidget must not be null"); - if(secondWidget == null) throw new IllegalArgumentException("secondWidget must not be null"); + * @params secondtWidget the second Actor */ + public void setWidgets (Actor firstWidget, Actor secondWidget) { + if (firstWidget == null) throw new IllegalArgumentException("firstWidget must not be null"); + if (secondWidget == null) throw new IllegalArgumentException("secondWidget must not be null"); this.removeActor(this.firstWidget); this.removeActor(this.secondWidget); this.firstWidget = firstWidget; diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java index 4e4978b66a5..54ca61fe519 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; -import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; @@ -27,53 +27,42 @@ import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.Actor; -import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle; -import com.badlogic.gdx.scenes.scene2d.ui.utils.AndroidClipboard; import com.badlogic.gdx.scenes.scene2d.ui.utils.Clipboard; -import com.badlogic.gdx.scenes.scene2d.ui.utils.DesktopClipboard; import com.badlogic.gdx.utils.FloatArray; -/** - * A single-line text field. +/** A single-line text field. * - *

        Functionality

        - * A TextField provides a way to get single-line text input from a user. It supports - * scrolling based on the cursor position, selection via holding down the shift-key (desktop-only), - * and copy & paste (desktop only). + *

        Functionality

        A TextField provides a way to get single-line text input from a user. It supports scrolling based on the + * cursor position, selection via holding down the shift-key (desktop-only), and copy & paste (desktop only). * - *

        Copy & Paste

        - * The TextField will copy the currently selected text when ctrl + c is pressed, and paste any - * text in the clipboard when ctrl + v is pressed. Clipboard functionality is provided via the {@link Clipboard} - * interface. Currently there are two standard implementations, one for the desktop and one for Android. The later - * is a stub, as copy & pasting on Android is not supported yet. To set your own Clipboard implementation use the - * {@link #setClipboard(Clipboard)} method. + *

        Copy & Paste

        The TextField will copy the currently selected text when ctrl + c is pressed, and paste any text in the + * clipboard when ctrl + v is pressed. Clipboard functionality is provided via the {@link Clipboard} interface. Currently there + * are two standard implementations, one for the desktop and one for Android. The later is a stub, as copy & pasting on Android is + * not supported yet. To set your own Clipboard implementation use the {@link #setClipboard(Clipboard)} method. * - *

        On-Screen Keyboard

        - * The TextField allows you to specify an {@link OnscreenKeyboard} implementation responsible for displaying a - * softkeyboard and piping all key events generated by the keyboard to the TextField. There are two standard - * implementations, one for the desktop and one for Android. The former is a stub, as a softkeyboard is not needed - * on the desktop. The Android {@link OnscreenKeyboard} implementation will bring up the default IME. If you want - * to set your own {@link OnscreenKeyboard} for a TextField use the {@link #setOnscreenKeyboard(OnscreenKeyboard)} - * method. The OnscreenKeyboard allows you to dynamically show and hide it, e.g. based on a key event for the return - * key. + *

        On-Screen Keyboard

        The TextField allows you to specify an {@link OnscreenKeyboard} implementation responsible for + * displaying a softkeyboard and piping all key events generated by the keyboard to the TextField. There are two standard + * implementations, one for the desktop and one for Android. The former is a stub, as a softkeyboard is not needed on the desktop. + * The Android {@link OnscreenKeyboard} implementation will bring up the default IME. If you want to set your own + * {@link OnscreenKeyboard} for a TextField use the {@link #setOnscreenKeyboard(OnscreenKeyboard)} method. The OnscreenKeyboard + * allows you to dynamically show and hide it, e.g. based on a key event for the return key. * *

        Listening to Key Events

        - * To listen to TextField events one can register a {@link TextFieldListener}. This listener will be invoked after - * a new character was added or removed to and from the TextField. This allows you to perform input checks or dynamically - * hide the OnscreenKeyboard. + * To listen to TextField events one can register a {@link TextFieldListener}. This listener will be invoked after a new character + * was added or removed to and from the TextField. This allows you to perform input checks or dynamically hide the + * OnscreenKeyboard. * *

        Layout

        - * The (preferred) width and height of a TextField are derrived from the width given at construction - * time as well as the combination of the used font's height and the top and bottom border patches. Use - * {@link Button#setPrefSize(int, int)} to programmatically change the size to your liking. In case the - * width and height you set are to small for the contained text, the TextField will clip the characters - * based on the current cursor position. + * The (preferred) width and height of a TextField are derrived from the width given at construction time as well as the + * combination of the used font's height and the top and bottom border patches. Use {@link Button#setPrefSize(int, int)} to + * programmatically change the size to your liking. In case the width and height you set are to small for the contained text, the + * TextField will clip the characters based on the current cursor position. * *

        Style

        - * A TextField is a {@link Widget} displaying a background {@link NinePatch}, the current text via a - * {@link BitmapFont} and {@link Color}, a cursor via a {@link NinePatch} as well as the current selection - * via a {@link TextureRegion} that is stretched over the entire selection. The style is defined via an instance - * of {@link TextFieldStyle}, which can be either done programmatically or via a {@link Skin}.

        + * A TextField is a {@link Widget} displaying a background {@link NinePatch}, the current text via a {@link BitmapFont} and + * {@link Color}, a cursor via a {@link NinePatch} as well as the current selection via a {@link TextureRegion} that is stretched + * over the entire selection. The style is defined via an instance of {@link TextFieldStyle}, which can be either done + * programmatically or via a {@link Skin}.

        * * A TextField's style definition in a skin XML file should look like this: * @@ -89,25 +78,27 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newTextField(String, float, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newTextField(String, float, String)}.
        • *
        • The font attribute references a {@link BitmapFont} by name, to be used to render the text in the text field
        • *
        • The fontColor attribute references a {@link Color} by name, to be used to render the text on the text field
        • - *
        • The cursorPatch attribute references a {@link NinePatch} by name, to be used to render the text field's cursor
        • - *
        • The selectionRegion attribute references a {@link TextureRegion} by name, to be used to highlight the text field's selection
        • - *
        • The backgroundPatch attribute references a {@link NinePatch} by name, to be used as the text field's background
        • - *
        + *
      • The cursorPatch attribute references a {@link NinePatch} by name, to be used to render the text field's cursor + *
      • + *
      • The selectionRegion attribute references a {@link TextureRegion} by name, to be used to highlight the text + * field's selection
      • + *
      • The backgroundPatch attribute references a {@link NinePatch} by name, to be used as the text field's + * background
      • + * * - * @author mzechner - * - */ + * @author mzechner */ public class TextField extends Widget { final TextFieldStyle style; - - Clipboard clipboard; + + Clipboard clipboard; final Rectangle fieldBounds = new Rectangle(); final TextBounds textBounds = new TextBounds(); final Rectangle scissor = new Rectangle(); - + TextFieldListener listener; String text = ""; int cursor = 0; @@ -128,14 +119,11 @@ public class TextField extends Widget { float selectionWidth = 0; OnscreenKeyboard keyboard = new DefaultOnscreenKeyboard(); - /** - * Creates a new Textfield. The width is determined by the prefWidth - * parameter, the height is determined by the font's height as well - * as the top and bottom border patches of the text fields background. + /** Creates a new Textfield. The width is determined by the prefWidth parameter, the height is determined by the font's height + * as well as the top and bottom border patches of the text fields background. * @param name the name * @param prefWidth the (preferred) width - * @param style the {@link TextFieldStyle} - */ + * @param style the {@link TextFieldStyle} */ public TextField (String name, float prefWidth, TextFieldStyle style) { super(name, prefWidth, 0); this.style = style; @@ -146,10 +134,11 @@ public TextField (String name, float prefWidth, TextFieldStyle style) { this.height = this.prefHeight; } - @Override public void layout () { + @Override + public void layout () { final BitmapFont font = style.font; final NinePatch background = style.background; - + textBounds.set(font.getBounds(text)); textBounds.height -= font.getDescent() * 2; font.computeGlyphAdvancesAndPositions(text, glyphAdvances, glyphPositions); @@ -167,9 +156,9 @@ private void blink () { } } - private void calculateOffsets () { + private void calculateOffsets () { final NinePatch background = style.background; - + float position = glyphPositions.get(cursor); float distance = position - Math.abs(renderOffset); float visibleWidth = width - background.getLeftWidth() - background.getRightWidth(); @@ -202,15 +191,15 @@ private void calculateOffsets () { } } - // calculate last visible char based on visible width and render offset + // calculate last visible char based on visible width and render offset visibleTextEnd = Math.min(text.length(), cursor + 1); for (; visibleTextEnd <= text.length(); visibleTextEnd++) { if (glyphPositions.items[visibleTextEnd] - startPos > visibleWidth) break; } - visibleTextEnd = Math.max(0, visibleTextEnd -1); - + visibleTextEnd = Math.max(0, visibleTextEnd - 1); + // calculate selection x position and width - if(hasSelection) { + if (hasSelection) { int minIndex = Math.min(cursor, selectionStart); int maxIndex = Math.max(cursor, selectionStart); float minX = Math.max(glyphPositions.get(minIndex), glyphPositions.get(visibleTextStart)); @@ -220,13 +209,14 @@ private void calculateOffsets () { } } - @Override public void draw (SpriteBatch batch, float parentAlpha) { + @Override + public void draw (SpriteBatch batch, float parentAlpha) { final BitmapFont font = style.font; final Color fontColor = style.fontColor; final NinePatch background = style.background; final TextureRegion selection = style.selection; final NinePatch cursorPatch = style.cursor; - + if (invalidated) layout(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); @@ -250,16 +240,17 @@ private void calculateOffsets () { } } - @Override public boolean touchDown (float x, float y, int pointer) { + @Override + public boolean touchDown (float x, float y, int pointer) { if (pointer != 0) return false; if (hit(x, y) != null) { parent.keyboardFocus(this); keyboard.show(true); x = x - renderOffset; - for(int i = 0; i < glyphPositions.size; i++) { + for (int i = 0; i < glyphPositions.size; i++) { float pos = glyphPositions.items[i]; - if(pos > x) { - cursor = Math.max(0,i-1); + if (pos > x) { + cursor = Math.max(0, i - 1); break; } } @@ -268,18 +259,20 @@ private void calculateOffsets () { return false; } - @Override public boolean touchUp (float x, float y, int pointer) { + @Override + public boolean touchUp (float x, float y, int pointer) { return false; } - @Override public boolean touchDragged (float x, float y, int pointer) { + @Override + public boolean touchDragged (float x, float y, int pointer) { return false; } public boolean keyDown (int keycode) { final BitmapFont font = style.font; - - if (parent.keyboardFocusedActor == this) { + + if (parent.keyboardFocusedActor == this) { // clipboard if (Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT)) { if (keycode == Keys.V) { @@ -309,28 +302,28 @@ public boolean keyDown (int keycode) { // selection else if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) { if (keycode == Keys.LEFT) { - if(!hasSelection) { + if (!hasSelection) { selectionStart = cursor; hasSelection = true; } cursor--; } if (keycode == Keys.RIGHT) { - if(!hasSelection) { + if (!hasSelection) { selectionStart = cursor; hasSelection = true; } cursor++; } if (keycode == Keys.HOME) { - if(!hasSelection) { + if (!hasSelection) { selectionStart = cursor; hasSelection = true; } cursor = 0; } if (keycode == Keys.END) { - if(!hasSelection) { + if (!hasSelection) { selectionStart = cursor; hasSelection = true; } @@ -371,47 +364,50 @@ else if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys. public boolean keyTyped (char character) { final BitmapFont font = style.font; - - if (parent.keyboardFocusedActor == this) { - if(character == 8 && (cursor > 0 || hasSelection)) { - if(!hasSelection) { + + if (parent.keyboardFocusedActor == this) { + if (character == 8 && (cursor > 0 || hasSelection)) { + if (!hasSelection) { text = text.substring(0, cursor - 1) + text.substring(cursor); cursor--; font.computeGlyphAdvancesAndPositions(text, glyphAdvances, glyphPositions); } else { int minIndex = Math.min(cursor, selectionStart); int maxIndex = Math.max(cursor, selectionStart); - - text = (minIndex>0?text.substring(0, minIndex):"") + (maxIndex < text.length()?text.substring(maxIndex, text.length()):""); + + text = (minIndex > 0 ? text.substring(0, minIndex) : "") + + (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : ""); cursor = minIndex; font.computeGlyphAdvancesAndPositions(text, glyphAdvances, glyphPositions); hasSelection = false; } } - if(character == 127 && (cursor < text.length() || hasSelection)) { - if(!hasSelection) { - text = text.substring(0, cursor) + text.substring(cursor + 1); + if (character == 127 && (cursor < text.length() || hasSelection)) { + if (!hasSelection) { + text = text.substring(0, cursor) + text.substring(cursor + 1); font.computeGlyphAdvancesAndPositions(text, glyphAdvances, glyphPositions); } else { int minIndex = Math.min(cursor, selectionStart); int maxIndex = Math.max(cursor, selectionStart); - - text = (minIndex>0?text.substring(0, minIndex):"") + (maxIndex < text.length()?text.substring(maxIndex, text.length()):""); + + text = (minIndex > 0 ? text.substring(0, minIndex) : "") + + (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : ""); cursor = minIndex; font.computeGlyphAdvancesAndPositions(text, glyphAdvances, glyphPositions); hasSelection = false; } - } + } if (font.containsCharacter(character)) { - if(!hasSelection) { + if (!hasSelection) { text = text.substring(0, cursor) + character + text.substring(cursor, text.length()); cursor++; font.computeGlyphAdvancesAndPositions(text, glyphAdvances, glyphPositions); } else { int minIndex = Math.min(cursor, selectionStart); int maxIndex = Math.max(cursor, selectionStart); - - text = (minIndex>0?text.substring(0, minIndex):"") + (maxIndex < text.length()?text.substring(maxIndex, text.length()):""); + + text = (minIndex > 0 ? text.substring(0, minIndex) : "") + + (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : ""); cursor = minIndex; text = text.substring(0, cursor) + character + text.substring(cursor, text.length()); cursor++; @@ -419,25 +415,23 @@ public boolean keyTyped (char character) { hasSelection = false; } } - if(listener != null) listener.keyTyped(this, character); + if (listener != null) listener.keyTyped(this, character); return true; } else return false; } - @Override public Actor hit (float x, float y) { + @Override + public Actor hit (float x, float y) { return x > 0 && x < width && y > 0 && y < height ? this : null; } - /** - * Defines a text field's style, see {@link TextField} - * @author mzechner - * - */ + /** Defines a text field's style, see {@link TextField} + * @author mzechner */ public static class TextFieldStyle { public final NinePatch background; public final BitmapFont font; - public final Color fontColor; + public final Color fontColor; public final NinePatch cursor; public final TextureRegion selection; @@ -449,91 +443,69 @@ public TextFieldStyle (BitmapFont font, Color fontColor, NinePatch cursor, Textu this.selection = selection; } } - - /** - * Interface for listening to typed characters. - * @author mzechner - * - */ + + /** Interface for listening to typed characters. + * @author mzechner */ public interface TextFieldListener { - public void keyTyped(TextField textField, char key); + public void keyTyped (TextField textField, char key); } - - /** - * Sets the {@link TextFieldListener} - * @param listener the listener or null - */ - public void setTextFieldListener(TextFieldListener listener) { + + /** Sets the {@link TextFieldListener} + * @param listener the listener or null */ + public void setTextFieldListener (TextFieldListener listener) { this.listener = listener; } - /** - * Sets the text of this text field. - * @param text the text - */ + /** Sets the text of this text field. + * @param text the text */ public void setText (String text) { final BitmapFont font = style.font; - + if (text == null) throw new IllegalArgumentException("text must not be null"); this.text = text; this.cursor = 0; - this.hasSelection = false; + this.hasSelection = false; font.computeGlyphAdvancesAndPositions(text, this.glyphAdvances, this.glyphPositions); invalidateHierarchy(); } - /** - * @return the text of this text field. Never null, might be an empty string. - */ + /** @return the text of this text field. Never null, might be an empty string. */ public String getText () { return text; } - - /** - * Returns the currently used {@link OnscreenKeyboard}. {@link TextField} instances - * use the {@link DefaultOnscreenKeyboard} by default. - * @return the OnscreenKeyboard. - */ - public OnscreenKeyboard getOnscreenKeyboard() { + + /** Returns the currently used {@link OnscreenKeyboard}. {@link TextField} instances use the {@link DefaultOnscreenKeyboard} by + * default. + * @return the OnscreenKeyboard. */ + public OnscreenKeyboard getOnscreenKeyboard () { return keyboard; } - - /** - * Sets the {@link OnscreenKeyboard} to be used by this textfield - * @param keyboard the OnscreenKeyboard - */ - public void setOnscreenKeyboard(OnscreenKeyboard keyboard) { + + /** Sets the {@link OnscreenKeyboard} to be used by this textfield + * @param keyboard the OnscreenKeyboard */ + public void setOnscreenKeyboard (OnscreenKeyboard keyboard) { this.keyboard = keyboard; } - - /** - * An interface for onscreen keyboards. Can invoke the - * default keyboard or render your own keyboard! - * @author mzechner - * - */ + + /** An interface for onscreen keyboards. Can invoke the default keyboard or render your own keyboard! + * @author mzechner */ public interface OnscreenKeyboard { - public void show(boolean visible); + public void show (boolean visible); } - - /** - * The default {@link OnscreenKeyboard} used by all {@link TextField} instances. - * Just uses {@link Input#setOnscreenKeyboardVisible(boolean)} as appropriate. Might - * overlap your actual rendering, so use with care! - * @author mzechner - * - */ + + /** The default {@link OnscreenKeyboard} used by all {@link TextField} instances. Just uses + * {@link Input#setOnscreenKeyboardVisible(boolean)} as appropriate. Might overlap your actual rendering, so use with care! + * @author mzechner */ public static class DefaultOnscreenKeyboard implements OnscreenKeyboard { - @Override public void show (boolean visible) { + @Override + public void show (boolean visible) { Gdx.input.setOnscreenKeyboardVisible(visible); - } + } } - - /** - * Sets the {@link Clipboard} implementation this TextField uses. - * @param clipboard the Clipboard - */ - public void setClipboard(Clipboard clipboard) { + + /** Sets the {@link Clipboard} implementation this TextField uses. + * @param clipboard the Clipboard */ + public void setClipboard (Clipboard clipboard) { this.clipboard = clipboard; } -} \ No newline at end of file +} diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ToggleButton.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ToggleButton.java index a10d68e5833..196ba102679 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ToggleButton.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/ToggleButton.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; @@ -23,24 +24,19 @@ import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Actor; -/** - * A toggle button. +/** A toggle button. * - *

        Functionality

        - * A toggle button can be either in a pressed or unpressed state. A {@link ClickListener} can - * be registered with the ToggleButton which will be called in case the button changed its state. + *

        Functionality

        A toggle button can be either in a pressed or unpressed state. A {@link ClickListener} can be registered + * with the ToggleButton which will be called in case the button changed its state. * - *

        Layout

        - * The (preferred) width and height of an ImageToggleButton are derived from the border patches in the - * background {@link NinePatch} as well as the bounding box of the multi-line label displayed inside the - * ToggleButton. Use {@link #setPrefSize(int, int)} to programmatically change the size - * to your liking. In case the width and height you set are to small for the contained label you - * will see artifacts. + *

        Layout

        The (preferred) width and height of an ImageToggleButton are derived from the border patches in the background + * {@link NinePatch} as well as the bounding box of the multi-line label displayed inside the ToggleButton. Use + * {@link #setPrefSize(int, int)} to programmatically change the size to your liking. In case the width and height you set are to + * small for the contained label you will see artifacts. * - *

        Style

        - * A ToggleButton is a {@link Widget} displaying a background {@link NinePatch} as well as - * multi-line text with a specific font and color. The style is defined via an instance - * of {@link ToggleButtonStyle}, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        A ToggleButton is a {@link Widget} displaying a background {@link NinePatch} as well as multi-line text with a + * specific font and color. The style is defined via an instance of {@link ToggleButtonStyle}, which can be either done + * programmatically or via a {@link Skin}.

        * * A Button's style definition in a skin XML file should look like this: * @@ -55,31 +51,32 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newToggleButton(String, String, String)}.
        • - *
        • The down attribute references a {@link NinePatch} by name, to be used as the toggle button's background when it is pressed
        • - *
        • The up attribute references a {@link NinePatch} by name, to be used as the toggle button's background when it is not pressed
        • - *
        • The font attribute references a {@link BitmapFont} by name, to be used to render the text on the toggle button
        • - *
        • The fontColor attribute references a {@link Color} by name, to be used to render the text on the toggle button
        • - *
        + *
      • The name attribute defines the name of the style which you can later use with + * {@link Skin#newToggleButton(String, String, String)}.
      • + *
      • The down attribute references a {@link NinePatch} by name, to be used as the toggle button's background when + * it is pressed
      • + *
      • The up attribute references a {@link NinePatch} by name, to be used as the toggle button's background when it + * is not pressed
      • + *
      • The font attribute references a {@link BitmapFont} by name, to be used to render the text on the toggle button + *
      • + *
      • The fontColor attribute references a {@link Color} by name, to be used to render the text on the toggle button + *
      • + * * - * @author mzechner - * - */ + * @author mzechner */ public class ToggleButton extends Widget { final ToggleButtonStyle style; - String text; + String text; final TextBounds bounds = new TextBounds(); boolean isPressed = false; ClickListener listener = null; - /** - * Creates a new ToggleButton. The width and height are determined by the background {@link NinePatch} - * border patches as well as the bounding box around the contained text label. + /** Creates a new ToggleButton. The width and height are determined by the background {@link NinePatch} border patches as well + * as the bounding box around the contained text label. * @param name the name * @param label the multi-line label - * @param style the {@link ToggleButtonStyle} - */ - public ToggleButton(String name, String label, ToggleButtonStyle style) { + * @param style the {@link ToggleButtonStyle} */ + public ToggleButton (String name, String label, ToggleButtonStyle style) { super(name, 0, 0); this.style = style; this.text = label; @@ -89,81 +86,73 @@ public ToggleButton(String name, String label, ToggleButtonStyle style) { } @Override - public void layout() { + public void layout () { final BitmapFont font = style.font; - final NinePatch downPatch = style.down; - + final NinePatch downPatch = style.down; + bounds.set(font.getMultiLineBounds(text)); bounds.height -= font.getDescent(); - prefHeight = downPatch.getBottomHeight() + downPatch.getTopHeight() - + bounds.height; - prefWidth = downPatch.getLeftWidth() + downPatch.getRightWidth() - + bounds.width; + prefHeight = downPatch.getBottomHeight() + downPatch.getTopHeight() + bounds.height; + prefWidth = downPatch.getLeftWidth() + downPatch.getRightWidth() + bounds.width; invalidated = false; } @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final BitmapFont font = style.font; final Color fontColor = style.fontColor; final NinePatch downPatch = style.down; final NinePatch upPatch = style.up; - - if(invalidated) layout(); - + + if (invalidated) layout(); + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); if (isPressed) downPatch.draw(batch, x, y, width, height); else upPatch.draw(batch, x, y, width, height); - float textY = (int) (height / 2) + (int) (bounds.height / 2); + float textY = (int)(height / 2) + (int)(bounds.height / 2); font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); - font.drawMultiLine(batch, text, x + (int) (width / 2), y + textY, 0, - HAlignment.CENTER); + font.drawMultiLine(batch, text, x + (int)(width / 2), y + textY, 0, HAlignment.CENTER); } @Override - public boolean touchDown(float x, float y, int pointer) { - if (pointer != 0) - return false; + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; if (hit(x, y) != null) { - isPressed = !isPressed; - if(listener != null) listener.click(this, isPressed); + isPressed = !isPressed; + if (listener != null) listener.click(this, isPressed); return true; } return false; } @Override - public boolean touchUp(float x, float y, int pointer) { + public boolean touchUp (float x, float y, int pointer) { return false; } @Override - public boolean touchDragged(float x, float y, int pointer) { + public boolean touchDragged (float x, float y, int pointer) { return false; } @Override - public Actor hit(float x, float y) { + public Actor hit (float x, float y) { return x > 0 && x < width && y > 0 && y < height ? this : null; } - /** - * Defines the style of a toggle button, see {@link ToggleButton} - * @author mzechner - * - */ + /** Defines the style of a toggle button, see {@link ToggleButton} + * @author mzechner */ public static class ToggleButtonStyle { public final NinePatch down; public final NinePatch up; public final BitmapFont font; public final Color fontColor; - public ToggleButtonStyle(BitmapFont font, Color fontColor, NinePatch down, - NinePatch up) { + public ToggleButtonStyle (BitmapFont font, Color fontColor, NinePatch down, NinePatch up) { this.font = font; this.fontColor = fontColor; this.down = down; @@ -171,53 +160,40 @@ public ToggleButtonStyle(BitmapFont font, Color fontColor, NinePatch down, } } - /** - * Interface to listen for button state changes. - * @author mzechner - * - */ - public interface ClickListener { - public void click(ToggleButton button, boolean isPressed); + /** Interface to listen for button state changes. + * @author mzechner */ + public interface ClickListener { + public void click (ToggleButton button, boolean isPressed); } - /** - * Sets the text label of this button. Invalidates all parents. - * @param text the text - */ - public void setText(String text) { + /** Sets the text label of this button. Invalidates all parents. + * @param text the text */ + public void setText (String text) { this.text = text; invalidateHierarchy(); } - - /** - * @return the text label of this button - */ - public String getText () { + + /** @return the text label of this button */ + public String getText () { return text; } - /** - * Sets the {@link ClickListener} of this button. + /** Sets the {@link ClickListener} of this button. * @param listener the listener or null - * @return this {@link ToggleButton} for chaining - */ - public ToggleButton setClickListener(ClickListener listener) { + * @return this {@link ToggleButton} for chaining */ + public ToggleButton setClickListener (ClickListener listener) { this.listener = listener; return this; } - - /** - * @return whether this button is pressed or not. - */ - public boolean isPressed() { + + /** @return whether this button is pressed or not. */ + public boolean isPressed () { return isPressed; } - - /** - * Sets whether this button is pressed or not. - * @param isPressed whether the button is pressed or not - */ - public void setPressed(boolean isPressed) { + + /** Sets whether this button is pressed or not. + * @param isPressed whether the button is pressed or not */ + public void setPressed (boolean isPressed) { this.isPressed = isPressed; - } + } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Widget.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Widget.java index 17886da921c..9c621ed6771 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Widget.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Widget.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.scenes.scene2d.Actor; @@ -20,83 +21,71 @@ import com.badlogic.gdx.scenes.scene2d.Layout; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; -/** - * Base class for all UI widgets. A widget implements the {@link Layout} interface which - * has a couple of features.

        +/** Base class for all UI widgets. A widget implements the {@link Layout} interface which has a couple of features.

        * - * A widget has a preferred width and height which it will use if possible, e.g. if it is not in a {@link Table} ({@link Pane}, {@link Window}) or a {@link SplitPane} or - * a {@link ScrollPane}. In case it is contained in one of the aforementioned containers, the - * preferred width and height will be used to guide the layouting mechanism employed by those containers.

        + * A widget has a preferred width and height which it will use if possible, e.g. if it is not in a {@link Table} ({@link Pane}, + * {@link Window}) or a {@link SplitPane} or a {@link ScrollPane}. In case it is contained in one of the aforementioned + * containers, the preferred width and height will be used to guide the layouting mechanism employed by those containers.

        * - * A widget can be invalidated, e.g. by a Container changing its available space in the layout, in which case it will layout itself at the next oportunity to do so.

        + * A widget can be invalidated, e.g. by a Container changing its available space in the layout, in which case it will layout + * itself at the next oportunity to do so.

        * * Invalidation can also be triggered manually via a call to {@link #invalidate()} or {@link #invalidateHierarchy()}. The former - * will tell the Widget to only invalidate itself. The later will also invalidate all the widget's parents. The later mechanism is - * used in case the widget was modified and the container it is contained in must relayout itself due to this modification as well. - * @author mzechner - * - */ + * will tell the Widget to only invalidate itself. The later will also invalidate all the widget's parents. The later mechanism is + * used in case the widget was modified and the container it is contained in must relayout itself due to this modification as + * well. + * @author mzechner */ public abstract class Widget extends Actor implements Layout { public float prefWidth; public float prefHeight; protected boolean invalidated = false; - /** - * Creates a new widget with the preferred width and height + /** Creates a new widget with the preferred width and height * @param name the name * @param prefWidth the preferred width - * @param prefHeight the preferred height - */ - public Widget(String name, float prefWidth, float prefHeight) { + * @param prefHeight the preferred height */ + public Widget (String name, float prefWidth, float prefHeight) { super(name); this.prefWidth = prefWidth; this.prefHeight = prefHeight; - } - + } + @Override - public float getPrefWidth() { + public float getPrefWidth () { return prefWidth; } @Override - public float getPrefHeight() { + public float getPrefHeight () { return prefHeight; } - /** - * Invalidates this widget, causing it to relayout itself - * at the next oportunity. - */ - public void invalidate() { + + /** Invalidates this widget, causing it to relayout itself at the next oportunity. */ + public void invalidate () { this.invalidated = true; - } - - /** - * Invalidates this widget and all its parents, causing all involved - * widgets to relayout themselves at the next oportunity. - */ - public void invalidateHierarchy() { - invalidate(); + } + + /** Invalidates this widget and all its parents, causing all involved widgets to relayout themselves at the next oportunity. */ + public void invalidateHierarchy () { + invalidate(); Group parent = this.parent; - while(parent != null) { - if(parent instanceof Layout) ((Layout) parent).invalidate(); + while (parent != null) { + if (parent instanceof Layout) ((Layout)parent).invalidate(); parent = parent.parent; } } - + @Override - public Actor hit(float x, float y) { - return x > 0 && x < width && y > 0 && y < height?this: null; + public Actor hit (float x, float y) { + return x > 0 && x < width && y > 0 && y < height ? this : null; } - - /** - * Sets the preferred width and height of this widget. Invalidates - * all parents. + + /** Sets the preferred width and height of this widget. Invalidates all parents. * @param prefWidth the preferred width - * @param prefHeight the preferred height - */ + * @param prefHeight the preferred height */ public void setPrefSize (int prefWidth, int prefHeight) { this.prefWidth = width = prefWidth; - this.prefHeight = height = prefHeight; + this.prefHeight = height = prefHeight; invalidateHierarchy(); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java index a8e86068b3b..012539d70e2 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; @@ -30,30 +31,25 @@ import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.badlogic.gdx.scenes.scene2d.ui.utils.ScissorStack; -/** - * A container acting as a dialog or window. +/** A container acting as a dialog or window. * - *

        Functionality

        - * A Window is a {@link Table} that can be moved around by touching and dragging its titlebar.It can house - * multiple {@link Actor} instances in a table-layout. The difference to a pure Container is - * that the Window will automatically set the padding of the layout to respect the width and height - * of the border patches of its background NinePatch. See {@link Table} for more information on - * how Actor instances are laid out when using this class.

        + *

        Functionality

        A Window is a {@link Table} that can be moved around by touching and dragging its titlebar.It can house + * multiple {@link Actor} instances in a table-layout. The difference to a pure Container is that the Window will automatically + * set the padding of the layout to respect the width and height of the border patches of its background NinePatch. See + * {@link Table} for more information on how Actor instances are laid out when using this class.

        * - * A Window can also be set to be modal via a call to {@link #setModal(boolean)}, in which case all - * touch input will go to that window no matter where the user touched the screen. + * A Window can also be set to be modal via a call to {@link #setModal(boolean)}, in which case all touch input will go to that + * window no matter where the user touched the screen. * - *

        Layout

        - * The (preferred) width and height are determined by the values given in the constructor of this class. - * Please consult the {@link Table} documentation on how the width and height will be manipulated - * if the Window is contained in another Container, a not so common use case. Additionally you can set - * the (preferred) width and height via a call to {@link TableLayout#size(int, int)}. + *

        Layout

        The (preferred) width and height are determined by the values given in the constructor of this class. Please + * consult the {@link Table} documentation on how the width and height will be manipulated if the Window is contained in another + * Container, a not so common use case. Additionally you can set the (preferred) width and height via a call to + * {@link TableLayout#size(int, int)}. * - *

        Style

        - * A Window is a {@link Table} displaying a background {@link NinePatch} and its child Actors, clipped to the - * Window's area, taking into account the padding as described in the functionality section. Additionally the window - * will render a title string in its top border patches. The style is defined via - * an instance of {@link WindowStyle}, which can be either done programmatically or via a {@link Skin}.

        + *

        Style

        A Window is a {@link Table} displaying a background {@link NinePatch} and its child Actors, clipped to the + * Window's area, taking into account the padding as described in the functionality section. Additionally the window will render a + * title string in its top border patches. The style is defined via an instance of {@link WindowStyle}, which can be either done + * programmatically or via a {@link Skin}.

        * * A Pane's style definition in a skin XML file should look like this: * @@ -67,15 +63,15 @@ * * *
          - *
        • The name attribute defines the name of the style which you can later use with {@link Skin#newWindow(String, Stage, String, int, int, String)}.
        • + *
        • The name attribute defines the name of the style which you can later use with + * {@link Skin#newWindow(String, Stage, String, int, int, String)}.
        • *
        • The titleFont attribute references a {@link BitmapFont} by name, to be used to render the title string.
        • - * *
        • The titleFontColor attribute references a {@link Color} by name, to be used to render the title string.
        • - *
        • The background attribute references a {@link NinePatch} by name, to be used as the Window's background.
        • * - *
        + * * + *
      • The titleFontColor attribute references a {@link Color} by name, to be used to render the title string.
      • + *
      • The background attribute references a {@link NinePatch} by name, to be used as the Window's background.
      • * + * * - * @author mzechner - * - */ + * @author mzechner */ public class Window extends Table { final WindowStyle style; String title; @@ -88,17 +84,15 @@ public class Window extends Table { boolean isMovable = true; final Vector2 initial = new Vector2(); boolean isModal = false; - - /** - * Creates a new Window. The width and height are determined by the given parameters. + + /** Creates a new Window. The width and height are determined by the given parameters. * @param name the name * @param stage the {@link Stage}, used for clipping * @param title the title - * @param prefWidth the (preferred) width + * @param prefWidth the (preferred) width * @param prefHeight the (preferred) height - * @param style the {@link WindowStyle} - */ - public Window(String name, Stage stage, String title, int prefWidth, int prefHeight, WindowStyle style) { + * @param style the {@link WindowStyle} */ + public Window (String name, Stage stage, String title, int prefWidth, int prefHeight, WindowStyle style) { super(name); this.stage = stage; this.title = title; @@ -113,12 +107,11 @@ public Window(String name, Stage stage, String title, int prefWidth, int prefHei layout.padLeft(Integer.toString((int)(background.getLeftWidth()) + 1)); layout.padRight(Integer.toString((int)(background.getRightWidth()) + 1)); } - - - private void calculateBoundsAndScissors(Matrix4 transform) { + + private void calculateBoundsAndScissors (Matrix4 transform) { final NinePatch background = style.background; final BitmapFont titleFont = style.titleFont; - + widgetBounds.x = background.getLeftWidth(); widgetBounds.y = background.getBottomHeight(); widgetBounds.width = width - background.getLeftWidth() - background.getRightWidth(); @@ -131,136 +124,124 @@ private void calculateBoundsAndScissors(Matrix4 transform) { textBounds.set(titleFont.getBounds(title)); textBounds.height -= titleFont.getDescent(); } - + @Override - public void draw(SpriteBatch batch, float parentAlpha) { + public void draw (SpriteBatch batch, float parentAlpha) { final NinePatch backgroundPatch = style.background; final BitmapFont titleFont = style.titleFont; final Color titleFontColor = style.titleFontColor; - + setupTransform(batch); layout(); calculateBoundsAndScissors(batch.getTransformMatrix()); - + batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); backgroundPatch.draw(batch, 0, 0, width, height); float textY = height - (int)(backgroundPatch.getTopHeight() / 2) + (int)(textBounds.height / 2); titleFont.setColor(titleFontColor.r, titleFontColor.g, titleFontColor.b, titleFontColor.a * parentAlpha); titleFont.drawMultiLine(batch, title, (int)(width / 2), textY, 0, HAlignment.CENTER); batch.flush(); - + ScissorStack.pushScissors(scissors); super.drawChildren(batch, parentAlpha); ScissorStack.popScissors(); - + resetTransform(batch); - + } - - /** - * Defines the style of a window, see {@link Window} - * @author mzechner - * - */ + + /** Defines the style of a window, see {@link Window} + * @author mzechner */ public static class WindowStyle { public final NinePatch background; public final BitmapFont titleFont; public final Color titleFontColor = new Color(1, 1, 1, 1); - - public WindowStyle(BitmapFont titleFont, Color titleFontColor, NinePatch backgroundPatch) { + + public WindowStyle (BitmapFont titleFont, Color titleFontColor, NinePatch backgroundPatch) { this.background = backgroundPatch; this.titleFont = titleFont; - this.titleFontColor.set(titleFontColor); + this.titleFontColor.set(titleFontColor); } } - - @Override public boolean touchDown(float x, float y, int pointer) { - if(pointer != 0) return false; - if(hit(x, y) != null) { - if(parent.getActors().size() > 1) parent.swapActor(this, parent.getActors().get(parent.getActors().size()-1)); - if(titleBounds.contains(x, y)) { + + @Override + public boolean touchDown (float x, float y, int pointer) { + if (pointer != 0) return false; + if (hit(x, y) != null) { + if (parent.getActors().size() > 1) parent.swapActor(this, parent.getActors().get(parent.getActors().size() - 1)); + if (titleBounds.contains(x, y)) { focus(this, 0); if (isMovable) { move = true; } - initial.set(x,y); - } else if(!super.touchDown(x, y, pointer)) { + initial.set(x, y); + } else if (!super.touchDown(x, y, pointer)) { focus(this, 0); } return true; } else { - if(isModal && parent.getActors().size() > 1) parent.swapActor(this, parent.getActors().get(parent.getActors().size()-1)); + if (isModal && parent.getActors().size() > 1) + parent.swapActor(this, parent.getActors().get(parent.getActors().size() - 1)); return isModal; } } - - @Override public boolean touchUp(float x, float y, int pointer) { - if(pointer != 0) return false; - if(parent.focusedActor[0] == this) focus(null, 0); + + @Override + public boolean touchUp (float x, float y, int pointer) { + if (pointer != 0) return false; + if (parent.focusedActor[0] == this) focus(null, 0); move = false; return super.touchUp(x, y, pointer) || isModal; } - - @Override public boolean touchDragged(float x, float y, int pointer) { - if(move) { + + @Override + public boolean touchDragged (float x, float y, int pointer) { + if (move) { this.x += (x - initial.x); - this.y += (y - initial.y); + this.y += (y - initial.y); return true; } - if(parent.focusedActor[0] == this) return true; + if (parent.focusedActor[0] == this) return true; return super.touchDragged(x, y, pointer) || isModal; } - + @Override - public Actor hit(float x, float y) { - return (x > 0 && x < width && y > 0 && y < height)||isModal?this: null; + public Actor hit (float x, float y) { + return (x > 0 && x < width && y > 0 && y < height) || isModal ? this : null; } - - /** - * Sets the title of the Window - * @param title the title - */ - public void setTitle(String title) { + + /** Sets the title of the Window + * @param title the title */ + public void setTitle (String title) { this.title = title; } - - /** - * @return the title of the window - */ - public String getTitle() { + + /** @return the title of the window */ + public String getTitle () { return title; } - - /** - * Sets whether this Window is movable by touch or not. In case it is - * the user will be able to grab and move the window by its title bar - * @param isMovable whether the window is movable or not - */ - public void setMovable(boolean isMovable) { + + /** Sets whether this Window is movable by touch or not. In case it is the user will be able to grab and move the window by its + * title bar + * @param isMovable whether the window is movable or not */ + public void setMovable (boolean isMovable) { this.isMovable = isMovable; } - - /** - * @return whether the window is movable - */ - public boolean isMovable() { + + /** @return whether the window is movable */ + public boolean isMovable () { return isMovable; } - - /** - * Sets whether this Window is modal or not. In case it is - * it will receive all touch events, no matter where the user touched + + /** Sets whether this Window is modal or not. In case it is it will receive all touch events, no matter where the user touched * the screen. - * @param isModal whether the window is modal or not - */ - public void setModal(boolean isModal) { + * @param isModal whether the window is modal or not */ + public void setModal (boolean isModal) { this.isModal = isModal; } - - /** - * @return whether the window is modal - */ - public boolean isModal() { + + /** @return whether the window is modal */ + public boolean isModal () { return isModal; } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Cell.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Cell.java index 40cce66321b..cdcb0ec30ed 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Cell.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Cell.java @@ -27,7 +27,7 @@ package com.badlogic.gdx.scenes.scene2d.ui.tablelayout; -import static com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout.*; +import static com.badlogic.gdx.scenes.scene2d.ui.tablelayout.BaseTableLayout.*; /** @author Nathan Sweet */ public class Cell { diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Table.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Table.java index ab34af98f6d..59d98c6554b 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Table.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Table.java @@ -29,7 +29,6 @@ import java.util.List; -import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Toolkit.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Toolkit.java index 755446ef4f8..03e88546c87 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Toolkit.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/tablelayout/Toolkit.java @@ -32,7 +32,7 @@ import java.util.ArrayList; import java.util.List; -import static com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout.*; +import static com.badlogic.gdx.scenes.scene2d.ui.tablelayout.BaseTableLayout.*; /** @author Nathan Sweet */ public abstract class Toolkit { diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/AndroidClipboard.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/AndroidClipboard.java index df320df611b..33752248b0b 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/AndroidClipboard.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/AndroidClipboard.java @@ -13,16 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui.utils; public class AndroidClipboard extends Clipboard { - @Override public String getContents () { + @Override + public String getContents () { return ""; } - @Override public void setContents (String content) { - + @Override + public void setContents (String content) { + } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/Clipboard.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/Clipboard.java index 0cd5a826184..f3368c46b18 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/Clipboard.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/Clipboard.java @@ -13,36 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui.utils; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.GdxRuntimeException; -/** - * A very simple clipboard interface for text content. - * @author mzechner - * - */ +/** A very simple clipboard interface for text content. + * @author mzechner */ public abstract class Clipboard { - /** - * gets the current content of the clipboard if it contains text - * @return the clipboard content or null - */ - public abstract String getContents(); - - /** - * Sets the content of the system clipboard. - * @param content the content - */ - public abstract void setContents(String content); - - public static Clipboard getDefaultClipboard() { - if(Gdx.app.getType() == ApplicationType.Android) return new AndroidClipboard(); + /** gets the current content of the clipboard if it contains text + * @return the clipboard content or null */ + public abstract String getContents (); + + /** Sets the content of the system clipboard. + * @param content the content */ + public abstract void setContents (String content); + + public static Clipboard getDefaultClipboard () { + if (Gdx.app.getType() == ApplicationType.Android) + return new AndroidClipboard(); else { try { return (Clipboard)(Class.forName("com.badlogic.gdx.scenes.scene2d.ui.utils.DesktopClipboard").newInstance()); - } catch(Exception e) { + } catch (Exception e) { throw new GdxRuntimeException("Couldn't instantiate desktop clipboard", e); } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/DesktopClipboard.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/DesktopClipboard.java index 83690cdaf24..ae3ce7d6f0f 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/DesktopClipboard.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/DesktopClipboard.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui.utils; import java.awt.Toolkit; @@ -23,15 +24,12 @@ import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; -/** - * Implementation of the {@link Clipboard} interface for the desktop. Uses the - * system clipboard via the default {@link Toolkit}. - * @author mzechner - * - */ +/** Implementation of the {@link Clipboard} interface for the desktop. Uses the system clipboard via the default {@link Toolkit}. + * @author mzechner */ public class DesktopClipboard extends Clipboard implements ClipboardOwner { - @Override public String getContents () { + @Override + public String getContents () { String result = ""; java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = clipboard.getContents(null); @@ -48,12 +46,14 @@ public class DesktopClipboard extends Clipboard implements ClipboardOwner { return result; } - @Override public void setContents (String content) { + @Override + public void setContents (String content) { StringSelection stringSelection = new StringSelection(content); java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, this); } - @Override public void lostOwnership (java.awt.datatransfer.Clipboard arg0, Transferable arg1) { + @Override + public void lostOwnership (java.awt.datatransfer.Clipboard arg0, Transferable arg1) { } } diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/ScissorStack.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/ScissorStack.java index 960e6529be6..00f66e690bf 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/ScissorStack.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/utils/ScissorStack.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.scenes.scene2d.ui.utils; import com.badlogic.gdx.Gdx; @@ -25,120 +26,107 @@ import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; -/** - * A scissor stack is a stack of {@link Rectangle} to be used for clipping via {@link GLCommon#glScissor(int, int, int, int)}. When - * a new Rectangle is pushed onto the stack, it will be merged with the current top of stack. The minimum area of overlap is then - * set as the real top of the stack. - * @author mzechner - * - */ +/** A scissor stack is a stack of {@link Rectangle} to be used for clipping via {@link GLCommon#glScissor(int, int, int, int)}. + * When a new Rectangle is pushed onto the stack, it will be merged with the current top of stack. The minimum area of overlap is + * then set as the real top of the stack. + * @author mzechner */ public class ScissorStack { private static Array scissors = new Array(); - - /** - * Pushes a new scissor {@link Rectangle} onto the stack, merging it with the current - * top of the stack. The minimal area of overlap between the TOS rectangle and the provided - * rectangle is pushed onto the stack. This will invoke {@link GLCommon#glScissor(int, int, int, int)} - * with the final TOS rectangle. In case no scissor is yet on the stack this will also enable - * {@link GL10#GL_SCISSOR_TEST} automatically. - * @param scissor the scissor Rectangle - */ - public static void pushScissors(Rectangle scissor) { + + /** Pushes a new scissor {@link Rectangle} onto the stack, merging it with the current top of the stack. The minimal area of + * overlap between the TOS rectangle and the provided rectangle is pushed onto the stack. This will invoke + * {@link GLCommon#glScissor(int, int, int, int)} with the final TOS rectangle. In case no scissor is yet on the stack this + * will also enable {@link GL10#GL_SCISSOR_TEST} automatically. + * @param scissor the scissor Rectangle */ + public static void pushScissors (Rectangle scissor) { fix(scissor); - - if(scissors.size == 0) { - Gdx.gl.glEnable(GL10.GL_SCISSOR_TEST); - } - else { - //merge scissors - Rectangle parent = scissors.get(scissors.size-1); + + if (scissors.size == 0) { + Gdx.gl.glEnable(GL10.GL_SCISSOR_TEST); + } else { + // merge scissors + Rectangle parent = scissors.get(scissors.size - 1); float minX = Math.max(parent.x, scissor.x); float maxX = Math.min(parent.x + parent.width, scissor.x + scissor.width); scissor.x = minX; scissor.width = maxX - minX; - + float minY = Math.max(parent.y, scissor.y); float maxY = Math.min(parent.y + parent.height, scissor.y + scissor.height); scissor.y = minY; scissor.height = maxY - minY; - } - scissors.add(scissor); + } + scissors.add(scissor); Gdx.gl.glScissor((int)scissor.x, (int)scissor.y, (int)scissor.width, (int)scissor.height); } - - /** - * Pops the current scissor rectangle from the stack and sets the new scissor area to the - * new TOS rectangle. In case no more rectangles are on the stack, {@link GL10#GL_SCISSOR_TEST} - * is disabled. - */ - public static void popScissors() { - scissors.pop(); - if(scissors.size == 0) Gdx.gl.glDisable(GL10.GL_SCISSOR_TEST); + + /** Pops the current scissor rectangle from the stack and sets the new scissor area to the new TOS rectangle. In case no more + * rectangles are on the stack, {@link GL10#GL_SCISSOR_TEST} is disabled. */ + public static void popScissors () { + scissors.pop(); + if (scissors.size == 0) + Gdx.gl.glDisable(GL10.GL_SCISSOR_TEST); else { Rectangle scissor = scissors.peek(); Gdx.gl.glScissor((int)scissor.x, (int)scissor.y, (int)scissor.width, (int)scissor.height); } } - - private static void fix(Rectangle rect) { - if(rect.width < 0) { + + private static void fix (Rectangle rect) { + if (rect.width < 0) { rect.width = -rect.width; rect.x -= rect.width; } - if(rect.height < 0) { + if (rect.height < 0) { rect.height = -rect.height; rect.y -= rect.height; } } - + static Vector3 tmp = new Vector3(); - - /** - * Calculates a scissor rectangle in OpenGL ES window coordinates from a {@link Camera}, a transformation {@link Matrix4} - * and an axis aligned {@link Rectangle}. The rectangle will get transformed by the camera and transform matrices and is - * then projected to screen coordinates. Note that only axis aligned rectangles will work with this method. If either - * the Camera or the Matrix4 have rotational components, the output of this method will not be suitable for {@link GLCommon#glScissor(int, int, int, int)}. + + /** Calculates a scissor rectangle in OpenGL ES window coordinates from a {@link Camera}, a transformation {@link Matrix4} and + * an axis aligned {@link Rectangle}. The rectangle will get transformed by the camera and transform matrices and is then + * projected to screen coordinates. Note that only axis aligned rectangles will work with this method. If either the Camera or + * the Matrix4 have rotational components, the output of this method will not be suitable for + * {@link GLCommon#glScissor(int, int, int, int)}. * @param camera the {@link Camera} * @param batchTransform the transformation {@link Matrix4} * @param area the {@link Rectangle} to transform to window coordinates - * @param scissor the Rectangle to store the result in - */ - public static void calculateScissors(Camera camera, Matrix4 batchTransform, Rectangle area, Rectangle scissor) { + * @param scissor the Rectangle to store the result in */ + public static void calculateScissors (Camera camera, Matrix4 batchTransform, Rectangle area, Rectangle scissor) { tmp.set(area.x, area.y, 0); tmp.mul(batchTransform); - camera.project(tmp); + camera.project(tmp); scissor.x = tmp.x; scissor.y = tmp.y; - + tmp.set(area.x + area.width, area.y + area.height, 0); tmp.mul(batchTransform); - camera.project(tmp); + camera.project(tmp); scissor.width = tmp.x - scissor.x; - scissor.height = tmp.y - scissor.y; + scissor.height = tmp.y - scissor.y; } static final Rectangle viewport = new Rectangle(); - /** - * @return the current viewport in OpenGL ES window coordinates based on the currently applied scissor - */ + + /** @return the current viewport in OpenGL ES window coordinates based on the currently applied scissor */ public static Rectangle getViewport () { - if(scissors.size == 0) { + if (scissors.size == 0) { viewport.set(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); return viewport; } else { Rectangle scissor = scissors.peek(); viewport.set(scissor); return viewport; - } + } } - /** - * Transforms a point to real window coordinates (as oposed to OpenGL ES window coordinates), where - * the origin is in the top left and the the y-axis is pointing downwards + /** Transforms a point to real window coordinates (as oposed to OpenGL ES window coordinates), where the origin is in the top + * left and the the y-axis is pointing downwards * @param camera the {@link Camera} * @param transformMatrix the transformation {@link Matrix4} - * @param point the point to be transformed. - */ + * @param point the point to be transformed. */ public static void toWindowCoordinates (Camera camera, Matrix4 transformMatrix, Vector2 point) { tmp.set(point.x, point.y, 0); tmp.mul(transformMatrix); diff --git a/gdx/src/com/badlogic/gdx/utils/Array.java b/gdx/src/com/badlogic/gdx/utils/Array.java index 6aee0ec2676..77fea9873da 100644 --- a/gdx/src/com/badlogic/gdx/utils/Array.java +++ b/gdx/src/com/badlogic/gdx/utils/Array.java @@ -22,16 +22,12 @@ import com.badlogic.gdx.math.MathUtils; -/** - * A resizable, ordered or unordered array of objects. If unordered, this class avoids a memory copy when removing elements (the +/** A resizable, ordered or unordered array of objects. If unordered, this class avoids a memory copy when removing elements (the * last element is moved to the removed element's position). - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class Array implements Iterable { - /** - * Provides direct access to the underlying array. If the Array's generic type is not Object, this field may only be accessed - * if the {@link Array#Array(boolean, int, Class)} constructor was used. - */ + /** Provides direct access to the underlying array. If the Array's generic type is not Object, this field may only be accessed + * if the {@link Array#Array(boolean, int, Class)} constructor was used. */ public T[] items; public int size; @@ -39,53 +35,41 @@ public class Array implements Iterable { private ArrayIterator iterator; - /** - * Creates an ordered array with a capacity of 16. - */ + /** Creates an ordered array with a capacity of 16. */ public Array () { this(true, 16); } - /** - * Creates an ordered array with the specified capacity. - */ + /** Creates an ordered array with the specified capacity. */ public Array (int capacity) { this(true, capacity); } - /** - * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a + /** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a * memory copy. - * @param capacity Any elements added beyond this will cause the backing array to be grown. - */ + * @param capacity Any elements added beyond this will cause the backing array to be grown. */ public Array (boolean ordered, int capacity) { this.ordered = ordered; items = (T[])new Object[capacity]; } - /** - * Creates a new array with {@link #items} of the specified type. + /** Creates a new array with {@link #items} of the specified type. * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a * memory copy. - * @param capacity Any elements added beyond this will cause the backing array to be grown. - */ + * @param capacity Any elements added beyond this will cause the backing array to be grown. */ public Array (boolean ordered, int capacity, Class arrayType) { this.ordered = ordered; items = (T[])java.lang.reflect.Array.newInstance(arrayType, capacity); } - /** - * Creates an ordered array with {@link #items} of the specified type and a capacity of 16. - */ + /** Creates an ordered array with {@link #items} of the specified type and a capacity of 16. */ public Array (Class arrayType) { this(false, 16, arrayType); } - /** - * Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is + /** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is * ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be - * grown. - */ + * grown. */ public Array (Array array) { this(array.ordered, array.size, (Class)array.items.getClass().getComponentType()); size = array.size; @@ -186,9 +170,7 @@ public boolean removeValue (T value, boolean identity) { return false; } - /** - * Removes and returns the item at the specified index. - */ + /** Removes and returns the item at the specified index. */ public T removeIndex (int index) { if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index)); Object[] items = this.items; @@ -202,9 +184,7 @@ public T removeIndex (int index) { return value; } - /** - * Removes and returns the last item. - */ + /** Removes and returns the last item. */ public T pop () { --size; T item = items[size]; @@ -212,9 +192,7 @@ public T pop () { return item; } - /** - * Returns the last item. - */ + /** Returns the last item. */ public T peek () { return items[size - 1]; } @@ -226,19 +204,15 @@ public void clear () { size = 0; } - /** - * Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have - * been removed, or if it is known that more items will not be added. - */ + /** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have + * been removed, or if it is known that more items will not be added. */ public void shrink () { resize(size); } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. - * @return {@link #items} - */ + * @return {@link #items} */ public T[] ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= items.length) resize(Math.max(8, sizeNeeded)); @@ -253,17 +227,13 @@ protected T[] resize (int newSize) { return newItems; } - /** - * Sorts this array. The array elements must implement {@link Comparable}. This method is not thread safe (uses - * {@link Sort#instance()}). - */ + /** Sorts this array. The array elements must implement {@link Comparable}. This method is not thread safe (uses + * {@link Sort#instance()}). */ public void sort () { Sort.instance().sort(items, 0, size); } - /** - * Sorts the array. This method is not thread safe (uses {@link Sort#instance()}). - */ + /** Sorts the array. This method is not thread safe (uses {@link Sort#instance()}). */ public void sort (Comparator comparator) { Sort.instance().sort(items, comparator, 0, size); } @@ -286,10 +256,8 @@ public void shuffle () { } } - /** - * Returns an iterator for the items in the array. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link ArrayIterator} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the items in the array. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link ArrayIterator} constructor for nested or multithreaded iteration. */ public Iterator iterator () { if (iterator == null) iterator = new ArrayIterator(this); iterator.index = 0; diff --git a/gdx/src/com/badlogic/gdx/utils/AtomicQueue.java b/gdx/src/com/badlogic/gdx/utils/AtomicQueue.java index 2dc391637fd..8a02b9a67ca 100644 --- a/gdx/src/com/badlogic/gdx/utils/AtomicQueue.java +++ b/gdx/src/com/badlogic/gdx/utils/AtomicQueue.java @@ -25,11 +25,9 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; -/** - * A queue that allows one thread to call {@link #put(Object)} and another thread to call {@link #poll()}. Multiple threads must +/** A queue that allows one thread to call {@link #put(Object)} and another thread to call {@link #poll()}. Multiple threads must * not call these methods. - * @author Matthias Mann - */ + * @author Matthias Mann */ public class AtomicQueue { private final AtomicInteger writeIndex = new AtomicInteger(); private final AtomicInteger readIndex = new AtomicInteger(); diff --git a/gdx/src/com/badlogic/gdx/utils/Base64Coder.java b/gdx/src/com/badlogic/gdx/utils/Base64Coder.java index 6cbca6af2af..b9e15d2e710 100644 --- a/gdx/src/com/badlogic/gdx/utils/Base64Coder.java +++ b/gdx/src/com/badlogic/gdx/utils/Base64Coder.java @@ -13,26 +13,24 @@ // Please contact the author if you need another license. // This module is provided "as is", without warranties of any kind. - /** -* A Base64 encoder/decoder. -* -*

        -* This class is used to encode and decode data in Base64 format as described in RFC 1521. -* -*

        -* Project home page: www.source-code.biz/base64coder/java
        -* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
        -* Multi-licensed: EPL / LGPL / GPL / AL / BSD. -*/ + * A Base64 encoder/decoder. + * + *

        + * This class is used to encode and decode data in Base64 format as described in RFC 1521. + * + *

        + * Project home page: www.source-code.biz/base64coder/java
        + * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
        + * Multi-licensed: EPL / LGPL / GPL / AL / BSD. + */ package com.badlogic.gdx.utils; public class Base64Coder { // The line separator string of the operating system. - private static final String systemLineSeparator = System - .getProperty("line.separator"); + private static final String systemLineSeparator = System.getProperty("line.separator"); // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; @@ -54,56 +52,37 @@ public class Base64Coder { for (int i = 0; i < map2.length; i++) map2[i] = -1; for (int i = 0; i < 64; i++) - map2[map1[i]] = (byte) i; + map2[map1[i]] = (byte)i; } - /** - * Encodes a string into Base64 format. No blanks or line breaks are - * inserted. + /** Encodes a string into Base64 format. No blanks or line breaks are inserted. * - * @param s - * A String to be encoded. - * @return A String containing the Base64 encoded data. - */ - public static String encodeString(String s) { + * @param s A String to be encoded. + * @return A String containing the Base64 encoded data. */ + public static String encodeString (String s) { return new String(encode(s.getBytes())); } - /** - * Encodes a byte array into Base 64 format and breaks the output into lines - * of 76 characters. This method is compatible with + /** Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters. This method is compatible with * sun.misc.BASE64Encoder.encodeBuffer(byte[]). * - * @param in - * An array containing the data bytes to be encoded. - * @return A String containing the Base64 encoded data, broken into lines. - */ - public static String encodeLines(byte[] in) { + * @param in An array containing the data bytes to be encoded. + * @return A String containing the Base64 encoded data, broken into lines. */ + public static String encodeLines (byte[] in) { return encodeLines(in, 0, in.length, 76, systemLineSeparator); } - /** - * Encodes a byte array into Base 64 format and breaks the output into - * lines. + /** Encodes a byte array into Base 64 format and breaks the output into lines. * - * @param in - * An array containing the data bytes to be encoded. - * @param iOff - * Offset of the first byte in in to be processed. - * @param iLen - * Number of bytes to be processed in in, starting - * at iOff. - * @param lineLen - * Line length for the output data. Should be a multiple of 4. - * @param lineSeparator - * The line separator to be used to separate the output lines. - * @return A String containing the Base64 encoded data, broken into lines. - */ - public static String encodeLines(byte[] in, int iOff, int iLen, - int lineLen, String lineSeparator) { + * @param in An array containing the data bytes to be encoded. + * @param iOff Offset of the first byte in in to be processed. + * @param iLen Number of bytes to be processed in in, starting at iOff. + * @param lineLen Line length for the output data. Should be a multiple of 4. + * @param lineSeparator The line separator to be used to separate the output lines. + * @return A String containing the Base64 encoded data, broken into lines. */ + public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) { int blockLen = (lineLen * 3) / 4; - if (blockLen <= 0) - throw new IllegalArgumentException(); + if (blockLen <= 0) throw new IllegalArgumentException(); int lines = (iLen + blockLen - 1) / blockLen; int bufLen = ((iLen + 2) / 3) * 4 + lines * lineSeparator.length(); StringBuilder buf = new StringBuilder(bufLen); @@ -117,46 +96,30 @@ public static String encodeLines(byte[] in, int iOff, int iLen, return buf.toString(); } - /** - * Encodes a byte array into Base64 format. No blanks or line breaks are - * inserted in the output. + /** Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. * - * @param in - * An array containing the data bytes to be encoded. - * @return A character array containing the Base64 encoded data. - */ - public static char[] encode(byte[] in) { + * @param in An array containing the data bytes to be encoded. + * @return A character array containing the Base64 encoded data. */ + public static char[] encode (byte[] in) { return encode(in, 0, in.length); } - /** - * Encodes a byte array into Base64 format. No blanks or line breaks are - * inserted in the output. + /** Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. * - * @param in - * An array containing the data bytes to be encoded. - * @param iLen - * Number of bytes to process in in. - * @return A character array containing the Base64 encoded data. - */ - public static char[] encode(byte[] in, int iLen) { + * @param in An array containing the data bytes to be encoded. + * @param iLen Number of bytes to process in in. + * @return A character array containing the Base64 encoded data. */ + public static char[] encode (byte[] in, int iLen) { return encode(in, 0, iLen); } - /** - * Encodes a byte array into Base64 format. No blanks or line breaks are - * inserted in the output. + /** Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. * - * @param in - * An array containing the data bytes to be encoded. - * @param iOff - * Offset of the first byte in in to be processed. - * @param iLen - * Number of bytes to process in in, starting at - * iOff. - * @return A character array containing the Base64 encoded data. - */ - public static char[] encode(byte[] in, int iOff, int iLen) { + * @param in An array containing the data bytes to be encoded. + * @param iOff Offset of the first byte in in to be processed. + * @param iLen Number of bytes to process in in, starting at iOff. + * @return A character array containing the Base64 encoded data. */ + public static char[] encode (byte[] in, int iOff, int iLen) { int oDataLen = (iLen * 4 + 2) / 3; // output length without padding int oLen = ((iLen + 2) / 3) * 4; // output length including padding char[] out = new char[oLen]; @@ -181,91 +144,58 @@ public static char[] encode(byte[] in, int iOff, int iLen) { return out; } - /** - * Decodes a string from Base64 format. No blanks or line breaks are allowed - * within the Base64 encoded input data. + /** Decodes a string from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * - * @param s - * A Base64 String to be decoded. + * @param s A Base64 String to be decoded. * @return A String containing the decoded data. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static String decodeString(String s) { + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ + public static String decodeString (String s) { return new String(decode(s)); } - /** - * Decodes a byte array from Base64 format and ignores line separators, tabs - * and blanks. CR, LF, Tab and Space characters are ignored in the input - * data. This method is compatible with - * sun.misc.BASE64Decoder.decodeBuffer(String). + /** Decodes a byte array from Base64 format and ignores line separators, tabs and blanks. CR, LF, Tab and Space characters are + * ignored in the input data. This method is compatible with sun.misc.BASE64Decoder.decodeBuffer(String). * - * @param s - * A Base64 String to be decoded. + * @param s A Base64 String to be decoded. * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decodeLines(String s) { + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ + public static byte[] decodeLines (String s) { char[] buf = new char[s.length()]; int p = 0; for (int ip = 0; ip < s.length(); ip++) { char c = s.charAt(ip); - if (c != ' ' && c != '\r' && c != '\n' && c != '\t') - buf[p++] = c; + if (c != ' ' && c != '\r' && c != '\n' && c != '\t') buf[p++] = c; } return decode(buf, 0, p); } - /** - * Decodes a byte array from Base64 format. No blanks or line breaks are - * allowed within the Base64 encoded input data. + /** Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * - * @param s - * A Base64 String to be decoded. + * @param s A Base64 String to be decoded. * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decode(String s) { + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ + public static byte[] decode (String s) { return decode(s.toCharArray()); } - /** - * Decodes a byte array from Base64 format. No blanks or line breaks are - * allowed within the Base64 encoded input data. + /** Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * - * @param in - * A character array containing the Base64 encoded data. + * @param in A character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decode(char[] in) { + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ + public static byte[] decode (char[] in) { return decode(in, 0, in.length); } - /** - * Decodes a byte array from Base64 format. No blanks or line breaks are - * allowed within the Base64 encoded input data. + /** Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * - * @param in - * A character array containing the Base64 encoded data. - * @param iOff - * Offset of the first character in in to be - * processed. - * @param iLen - * Number of characters to process in in, starting - * at iOff. + * @param in A character array containing the Base64 encoded data. + * @param iOff Offset of the first character in in to be processed. + * @param iLen Number of characters to process in in, starting at iOff. * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * If the input is not valid Base64 encoded data. - */ - public static byte[] decode(char[] in, int iOff, int iLen) { - if (iLen % 4 != 0) - throw new IllegalArgumentException( - "Length of Base64 encoded input string is not a multiple of 4."); + * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ + public static byte[] decode (char[] in, int iOff, int iLen) { + if (iLen % 4 != 0) throw new IllegalArgumentException("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iOff + iLen - 1] == '=') iLen--; int oLen = (iLen * 3) / 4; @@ -279,29 +209,25 @@ public static byte[] decode(char[] in, int iOff, int iLen) { int i2 = ip < iEnd ? in[ip++] : 'A'; int i3 = ip < iEnd ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) - throw new IllegalArgumentException( - "Illegal character in Base64 encoded data."); + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) - throw new IllegalArgumentException( - "Illegal character in Base64 encoded data."); + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int o0 = (b0 << 2) | (b1 >>> 4); int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); int o2 = ((b2 & 3) << 6) | b3; - out[op++] = (byte) o0; - if (op < oLen) - out[op++] = (byte) o1; - if (op < oLen) - out[op++] = (byte) o2; + out[op++] = (byte)o0; + if (op < oLen) out[op++] = (byte)o1; + if (op < oLen) out[op++] = (byte)o2; } return out; } // Dummy constructor. - private Base64Coder() { + private Base64Coder () { } } // end class Base64Coder diff --git a/gdx/src/com/badlogic/gdx/utils/BufferUtils.java b/gdx/src/com/badlogic/gdx/utils/BufferUtils.java index bed46217bd3..264fb009406 100644 --- a/gdx/src/com/badlogic/gdx/utils/BufferUtils.java +++ b/gdx/src/com/badlogic/gdx/utils/BufferUtils.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.nio.Buffer; @@ -25,23 +26,17 @@ import java.nio.LongBuffer; import java.nio.ShortBuffer; -/** - * Class with static helper methods to increase the speed of array/direct buffer and direct buffer/direct buffer transfers - * - * @author mzechner +/** Class with static helper methods to increase the speed of array/direct buffer and direct buffer/direct buffer transfers * - */ + * @author mzechner */ public class BufferUtils { - /** - * Frees the memory allocated for the ByteBuffer. DO NOT USE THIS ON BYTEBUFFERS ALLOCATEd - * VIA METHODS IN THIS CLASS OR ByteBuffer.allocateDirect()! IT WILL EXPLODE! - */ - public static native void freeMemory(ByteBuffer buffer) /*-{ }-*/; - - public static native ByteBuffer newDisposableByteBuffer(int numBytes); - - /** - * Copies numFloats floats from src starting at offset to dst. Dst is assumed to be a direct {@link Buffer}. The method will + /** Frees the memory allocated for the ByteBuffer. DO NOT USE THIS ON BYTEBUFFERS ALLOCATEd VIA METHODS IN THIS CLASS OR + * ByteBuffer.allocateDirect()! IT WILL EXPLODE! */ + public static native void freeMemory (ByteBuffer buffer) /*-{ }-*/; + + public static native ByteBuffer newDisposableByteBuffer (int numBytes); + + /** 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 @@ -50,8 +45,7 @@ public class BufferUtils { * @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 - */ + * @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); @@ -60,186 +54,193 @@ public static void copy (float[] src, Buffer dst, int numFloats, int offset) { dst.limit(numFloats << 2); else if (dst instanceof FloatBuffer) dst.limit(numFloats); } - - /** - * Copies the contents of src to dst, starting from src[srcOffset], copying numElements - * elements. The {@link Buffer} instance's {@link Buffer#position()} is used to define - * the offset into the Buffer itself. The position will stay the same, the limit will be - * set to position + numElements. The Buffer must be a direct Buffer with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from src[srcOffset], copying numElements elements. The {@link Buffer} instance's + * {@link Buffer#position()} is used to define the offset into the Buffer itself. The position will stay the same, the limit + * will be set to position + numElements. The Buffer must be a direct Buffer with native byte order. No error checking is + * performed. * * @param src the source array. * @param srcOffset the offset into the source array. * @param dst the destination Buffer, its position is used as an offset. - * @param numElements the number of elements to copy. - */ - public static void copy (byte[] src, int srcOffset, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (byte[] src, int srcOffset, Buffer dst, int numElements) { copyJni(src, srcOffset, dst, positionInBytes(dst), numElements); dst.limit(dst.position() + bytesToElements(dst, numElements)); } - - /** - * Copies the contents of src to dst, starting from src[srcOffset], copying numElements - * elements. The {@link Buffer} instance's {@link Buffer#position()} is used to define - * the offset into the Buffer itself. The position will stay the same, the limit will be - * set to position + numElements. The Buffer must be a direct Buffer with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from src[srcOffset], copying numElements elements. The {@link Buffer} instance's + * {@link Buffer#position()} is used to define the offset into the Buffer itself. The position will stay the same, the limit + * will be set to position + numElements. The Buffer must be a direct Buffer with native byte order. No error checking is + * performed. * * @param src the source array. * @param srcOffset the offset into the source array. * @param dst the destination Buffer, its position is used as an offset. - * @param numElements the number of elements to copy. - */ - public static void copy (short[] src, int srcOffset, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (short[] src, int srcOffset, Buffer dst, int numElements) { copyJni(src, srcOffset << 1, dst, positionInBytes(dst), numElements << 1); dst.limit(dst.position() + bytesToElements(dst, numElements << 1)); } - - /** - * Copies the contents of src to dst, starting from src[srcOffset], copying numElements - * elements. The {@link Buffer} instance's {@link Buffer#position()} is used to define - * the offset into the Buffer itself. The position will stay the same, the limit will be - * set to position + numElements. The Buffer must be a direct Buffer with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from src[srcOffset], copying numElements elements. The {@link Buffer} instance's + * {@link Buffer#position()} is used to define the offset into the Buffer itself. The position will stay the same, the limit + * will be set to position + numElements. The Buffer must be a direct Buffer with native byte order. No error checking is + * performed. * * @param src the source array. * @param srcOffset the offset into the source array. * @param dst the destination Buffer, its position is used as an offset. - * @param numElements the number of elements to copy. - */ - public static void copy (char[] src, int srcOffset, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (char[] src, int srcOffset, Buffer dst, int numElements) { copyJni(src, srcOffset << 1, dst, positionInBytes(dst), numElements << 1); dst.limit(dst.position() + bytesToElements(dst, numElements << 1)); } - - /** - * Copies the contents of src to dst, starting from src[srcOffset], copying numElements - * elements. The {@link Buffer} instance's {@link Buffer#position()} is used to define - * the offset into the Buffer itself. The position will stay the same, the limit will be - * set to position + numElements. The Buffer must be a direct Buffer with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from src[srcOffset], copying numElements elements. The {@link Buffer} instance's + * {@link Buffer#position()} is used to define the offset into the Buffer itself. The position will stay the same, the limit + * will be set to position + numElements. The Buffer must be a direct Buffer with native byte order. No error checking is + * performed. * * @param src the source array. * @param srcOffset the offset into the source array. * @param dst the destination Buffer, its position is used as an offset. - * @param numElements the number of elements to copy. - */ - public static void copy (int[] src, int srcOffset, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (int[] src, int srcOffset, Buffer dst, int numElements) { copyJni(src, srcOffset << 2, dst, positionInBytes(dst), numElements << 2); dst.limit(dst.position() + bytesToElements(dst, numElements << 2)); } - - /** - * Copies the contents of src to dst, starting from src[srcOffset], copying numElements - * elements. The {@link Buffer} instance's {@link Buffer#position()} is used to define - * the offset into the Buffer itself. The position will stay the same, the limit will be - * set to position + numElements. The Buffer must be a direct Buffer with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from src[srcOffset], copying numElements elements. The {@link Buffer} instance's + * {@link Buffer#position()} is used to define the offset into the Buffer itself. The position will stay the same, the limit + * will be set to position + numElements. The Buffer must be a direct Buffer with native byte order. No error checking is + * performed. * * @param src the source array. * @param srcOffset the offset into the source array. * @param dst the destination Buffer, its position is used as an offset. - * @param numElements the number of elements to copy. - */ - public static void copy (long[] src, int srcOffset, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (long[] src, int srcOffset, Buffer dst, int numElements) { copyJni(src, srcOffset << 3, dst, positionInBytes(dst), numElements << 3); dst.limit(dst.position() + bytesToElements(dst, numElements << 3)); } - - /** - * Copies the contents of src to dst, starting from src[srcOffset], copying numElements - * elements. The {@link Buffer} instance's {@link Buffer#position()} is used to define - * the offset into the Buffer itself. The position will stay the same, the limit will be - * set to position + numElements. The Buffer must be a direct Buffer with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from src[srcOffset], copying numElements elements. The {@link Buffer} instance's + * {@link Buffer#position()} is used to define the offset into the Buffer itself. The position will stay the same, the limit + * will be set to position + numElements. The Buffer must be a direct Buffer with native byte order. No error checking is + * performed. * * @param src the source array. * @param srcOffset the offset into the source array. * @param dst the destination Buffer, its position is used as an offset. - * @param numElements the number of elements to copy. - */ - public static void copy (float[] src, int srcOffset, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (float[] src, int srcOffset, Buffer dst, int numElements) { copyJni(src, srcOffset << 2, dst, positionInBytes(dst), numElements << 2); dst.limit(dst.position() + bytesToElements(dst, numElements << 2)); } - - /** - * Copies the contents of src to dst, starting from src[srcOffset], copying numElements - * elements. The {@link Buffer} instance's {@link Buffer#position()} is used to define - * the offset into the Buffer itself. The position will stay the same, the limit will be - * set to position + numElements. The Buffer must be a direct Buffer with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from src[srcOffset], copying numElements elements. The {@link Buffer} instance's + * {@link Buffer#position()} is used to define the offset into the Buffer itself. The position will stay the same, the limit + * will be set to position + numElements. The Buffer must be a direct Buffer with native byte order. No error checking is + * performed. * * @param src the source array. * @param srcOffset the offset into the source array. * @param dst the destination Buffer, its position is used as an offset. - * @param numElements the number of elements to copy. - */ - public static void copy (double[] src, int srcOffset, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (double[] src, int srcOffset, Buffer dst, int numElements) { copyJni(src, srcOffset << 3, dst, positionInBytes(dst), numElements << 3); dst.limit(dst.position() + bytesToElements(dst, numElements << 3)); } - - /** - * Copies the contents of src to dst, starting from the current position of src, copying - * numElements elements (using the data type of src, no matter the datatype of dst). The - * dst {@link Buffer#position()} is used as the writing offset. The position of both Buffers - * will stay the same. The limit of the src Buffer will stay the same. The limit of the dst Buffer - * will be set to dst.position() + numElements, where numElements are translated to the number of - * elements appropriate for the dst Buffer data type. The Buffers must be direct Buffers with native byte order. - * No error checking is performed. + + /** Copies the contents of src to dst, starting from the current position of src, copying numElements elements (using the data + * type of src, no matter the datatype of dst). The dst {@link Buffer#position()} is used as the writing offset. The position + * of both Buffers will stay the same. The limit of the src Buffer will stay the same. The limit of the dst Buffer will be set + * to dst.position() + numElements, where numElements are translated to the number of elements appropriate for the dst Buffer + * data type. The Buffers must be direct Buffers with native byte order. No error checking is performed. * * @param src the source Buffer. * @param dst the destination Buffer. - * @param numElements the number of elements to copy. - */ - public static void copy(Buffer src, Buffer dst, int numElements) { + * @param numElements the number of elements to copy. */ + public static void copy (Buffer src, Buffer dst, int numElements) { int numBytes = elementsToBytes(src, numElements); copyJni(src, positionInBytes(src), dst, positionInBytes(dst), numBytes); dst.limit(dst.position() + bytesToElements(dst, numBytes)); } - - private static int positionInBytes(Buffer dst) { - if(dst instanceof ByteBuffer) return dst.position(); - else if(dst instanceof ShortBuffer) return dst.position() << 1; - else if(dst instanceof CharBuffer) return dst.position() << 1; - else if(dst instanceof IntBuffer) return dst.position() << 2; - else if(dst instanceof LongBuffer) return dst.position() << 3; - else if(dst instanceof FloatBuffer) return dst.position() << 2; - else if(dst instanceof DoubleBuffer) return dst.position() << 3; - else throw new GdxRuntimeException("Can't copy to a " + dst.getClass().getName() + " instance"); - } - - private static int bytesToElements(Buffer dst, int bytes) { - if(dst instanceof ByteBuffer) return bytes; - else if(dst instanceof ShortBuffer) return bytes >>> 1; - else if(dst instanceof CharBuffer) return bytes >>> 1; - else if(dst instanceof IntBuffer) return bytes >>> 2; - else if(dst instanceof LongBuffer) return bytes >>> 3; - else if(dst instanceof FloatBuffer) return bytes >>> 2; - else if(dst instanceof DoubleBuffer) return bytes >>> 3; - else throw new GdxRuntimeException("Can't copy to a " + dst.getClass().getName() + " instance"); + + private static int positionInBytes (Buffer dst) { + if (dst instanceof ByteBuffer) + return dst.position(); + else if (dst instanceof ShortBuffer) + return dst.position() << 1; + else if (dst instanceof CharBuffer) + return dst.position() << 1; + else if (dst instanceof IntBuffer) + return dst.position() << 2; + else if (dst instanceof LongBuffer) + return dst.position() << 3; + else if (dst instanceof FloatBuffer) + return dst.position() << 2; + else if (dst instanceof DoubleBuffer) + return dst.position() << 3; + else + throw new GdxRuntimeException("Can't copy to a " + dst.getClass().getName() + " instance"); + } + + private static int bytesToElements (Buffer dst, int bytes) { + if (dst instanceof ByteBuffer) + return bytes; + else if (dst instanceof ShortBuffer) + return bytes >>> 1; + else if (dst instanceof CharBuffer) + return bytes >>> 1; + else if (dst instanceof IntBuffer) + return bytes >>> 2; + else if (dst instanceof LongBuffer) + return bytes >>> 3; + else if (dst instanceof FloatBuffer) + return bytes >>> 2; + else if (dst instanceof DoubleBuffer) + return bytes >>> 3; + else + throw new GdxRuntimeException("Can't copy to a " + dst.getClass().getName() + " instance"); } - - private static int elementsToBytes(Buffer dst, int elements) { - if(dst instanceof ByteBuffer) return elements; - else if(dst instanceof ShortBuffer) return elements << 1; - else if(dst instanceof CharBuffer) return elements << 1; - else if(dst instanceof IntBuffer) return elements << 2; - else if(dst instanceof LongBuffer) return elements << 3; - else if(dst instanceof FloatBuffer) return elements << 2; - else if(dst instanceof DoubleBuffer) return elements << 3; - else throw new GdxRuntimeException("Can't copy to a " + dst.getClass().getName() + " instance"); + + private static int elementsToBytes (Buffer dst, int elements) { + if (dst instanceof ByteBuffer) + return elements; + else if (dst instanceof ShortBuffer) + return elements << 1; + else if (dst instanceof CharBuffer) + return elements << 1; + else if (dst instanceof IntBuffer) + return elements << 2; + else if (dst instanceof LongBuffer) + return elements << 3; + else if (dst instanceof FloatBuffer) + return elements << 2; + else if (dst instanceof DoubleBuffer) + return elements << 3; + else + throw new GdxRuntimeException("Can't copy to a " + dst.getClass().getName() + " instance"); } - + private native static void copyJni (float[] src, Buffer dst, int numFloats, int offset) /*-{ }-*/; + private native static void copyJni (byte[] src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; + private native static void copyJni (char[] src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; + private native static void copyJni (short[] src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; + private native static void copyJni (int[] src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; + private native static void copyJni (long[] src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; + private native static void copyJni (float[] src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; + private native static void copyJni (double[] src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; + private native static void copyJni (Buffer src, int srcOffset, Buffer dst, int dstOffset, int numBytes) /*-{ }-*/; public static FloatBuffer newFloatBuffer (int numFloats) { @@ -247,7 +248,7 @@ public static FloatBuffer newFloatBuffer (int numFloats) { buffer.order(ByteOrder.nativeOrder()); return buffer.asFloatBuffer(); } - + public static DoubleBuffer newDoubleBuffer (int numDoubles) { ByteBuffer buffer = ByteBuffer.allocateDirect(numDoubles * 8); buffer.order(ByteOrder.nativeOrder()); @@ -259,14 +260,14 @@ public static ByteBuffer newByteBuffer (int numBytes) { buffer.order(ByteOrder.nativeOrder()); return buffer; } - + public static ShortBuffer newShortBuffer (int numShorts) { ByteBuffer buffer = ByteBuffer.allocateDirect(numShorts * 2); buffer.order(ByteOrder.nativeOrder()); return buffer.asShortBuffer(); } - - public static CharBuffer newCharBuffer(int numChars) { + + public static CharBuffer newCharBuffer (int numChars) { ByteBuffer buffer = ByteBuffer.allocateDirect(numChars * 2); buffer.order(ByteOrder.nativeOrder()); return buffer.asCharBuffer(); @@ -277,15 +278,13 @@ public static IntBuffer newIntBuffer (int numInts) { buffer.order(ByteOrder.nativeOrder()); return buffer.asIntBuffer(); } - + public static LongBuffer newLongBuffer (int numLongs) { ByteBuffer buffer = ByteBuffer.allocateDirect(numLongs * 8); buffer.order(ByteOrder.nativeOrder()); return buffer.asLongBuffer(); } - /** - * Writes the specified number of zeros to the buffer. This is generally faster than reallocating a new buffer. - */ + /** Writes the specified number of zeros to the buffer. This is generally faster than reallocating a new buffer. */ public static native void clear (ByteBuffer buffer, int numBytes); } diff --git a/gdx/src/com/badlogic/gdx/utils/ComparableTimSort.java b/gdx/src/com/badlogic/gdx/utils/ComparableTimSort.java index 56dd8be24cb..532a9421ef2 100644 --- a/gdx/src/com/badlogic/gdx/utils/ComparableTimSort.java +++ b/gdx/src/com/badlogic/gdx/utils/ComparableTimSort.java @@ -13,18 +13,15 @@ package com.badlogic.gdx.utils; -/** - * This is a near duplicate of {@link TimSort}, modified for use with arrays of objects that implement {@link Comparable}, instead +/** This is a near duplicate of {@link TimSort}, modified for use with arrays of objects that implement {@link Comparable}, instead * of using explicit comparators. * *

        * If you are using an optimizing VM, you may find that ComparableTimSort offers no performance benefit over TimSort in * conjunction with a comparator that simply returns {@code ((Comparable)first).compareTo(Second)}. If this is the case, you are - * better off deleting ComparableTimSort to eliminate the code duplication. (See Arrays.java for details.) - */ + * better off deleting ComparableTimSort to eliminate the code duplication. (See Arrays.java for details.) */ class ComparableTimSort { - /** - * This is the minimum sized sequence that will be merged. Shorter sequences will be lengthened by calling binarySort. If the + /** This is the minimum sized sequence that will be merged. Shorter sequences will be lengthened by calling binarySort. If the * entire array is less than this length, no merges will be performed. * * This constant should be a power of two. It was 64 in Tim Peter's C implementation, but 32 was empirically determined to work @@ -33,55 +30,40 @@ class ComparableTimSort { * * If you decrease this constant, you must change the stackLen computation in the TimSort constructor, or you risk an * ArrayOutOfBounds exception. See listsort.txt for a discussion of the minimum stack length required as a function of the - * length of the array being sorted and the minimum merge sequence length. - */ + * length of the array being sorted and the minimum merge sequence length. */ private static final int MIN_MERGE = 32; - /** - * The array being sorted. - */ + /** The array being sorted. */ private Object[] a; - /** - * When we get into galloping mode, we stay there until both runs win less often than MIN_GALLOP consecutive times. - */ + /** When we get into galloping mode, we stay there until both runs win less often than MIN_GALLOP consecutive times. */ private static final int MIN_GALLOP = 7; - /** - * This controls when we get *into* galloping mode. It is initialized to MIN_GALLOP. The mergeLo and mergeHi methods nudge it - * higher for random data, and lower for highly structured data. - */ + /** This controls when we get *into* galloping mode. It is initialized to MIN_GALLOP. The mergeLo and mergeHi methods nudge it + * higher for random data, and lower for highly structured data. */ private int minGallop = MIN_GALLOP; - /** - * Maximum initial size of tmp array, which is used for merging. The array can grow to accommodate demand. + /** Maximum initial size of tmp array, which is used for merging. The array can grow to accommodate demand. * * Unlike Tim's original C version, we do not allocate this much storage when sorting smaller arrays. This change was required - * for performance. - */ + * for performance. */ private static final int INITIAL_TMP_STORAGE_LENGTH = 256; - /** - * Temp storage for merges. - */ + /** Temp storage for merges. */ private Object[] tmp; - /** - * A stack of pending runs yet to be merged. Run i starts at address base[i] and extends for len[i] elements. It's always true + /** A stack of pending runs yet to be merged. Run i starts at address base[i] and extends for len[i] elements. It's always true * (so long as the indices are in bounds) that: * * runBase[i] + runLen[i] == runBase[i + 1] * - * so we could cut the storage for this, but it's a minor amount, and keeping all the info explicit simplifies the code. - */ + * so we could cut the storage for this, but it's a minor amount, and keeping all the info explicit simplifies the code. */ private int stackSize = 0; // Number of pending runs on stack private final int[] runBase; private final int[] runLen; - /** - * Asserts have been placed in if-statements for performace. To enable them, set this field to true and enable them in VM with - * a command line flag. If you modify this class, please do test the asserts! - */ + /** Asserts have been placed in if-statements for performace. To enable them, set this field to true and enable them in VM with + * a command line flag. If you modify this class, please do test the asserts! */ private static final boolean DEBUG = false; ComparableTimSort () { @@ -105,10 +87,8 @@ public void doSort (Object[] a, int lo, int hi) { this.a = a; - /** - * March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and - * merging runs to maintain stack invariant. - */ + /** March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and + * merging runs to maintain stack invariant. */ int minRun = minRunLength(nRemaining); do { // Identify next run @@ -136,11 +116,9 @@ public void doSort (Object[] a, int lo, int hi) { if (DEBUG) assert stackSize == 1; } - /** - * Creates a TimSort instance to maintain the state of an ongoing sort. + /** Creates a TimSort instance to maintain the state of an ongoing sort. * - * @param a the array to be sorted - */ + * @param a the array to be sorted */ private ComparableTimSort (Object[] a) { this.a = a; @@ -182,10 +160,8 @@ static void sort (Object[] a, int lo, int hi) { return; } - /** - * March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and - * merging runs to maintain stack invariant. - */ + /** March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and + * merging runs to maintain stack invariant. */ ComparableTimSort ts = new ComparableTimSort(a); int minRun = minRunLength(nRemaining); do { @@ -214,8 +190,7 @@ static void sort (Object[] a, int lo, int hi) { if (DEBUG) assert ts.stackSize == 1; } - /** - * Sorts the specified portion of the specified array using a binary insertion sort. This is the best method for sorting small + /** Sorts the specified portion of the specified array using a binary insertion sort. This is the best method for sorting small * numbers of elements. It requires O(n log n) compares, but O(n^2) data movement (worst case). * * If the initial part of the specified range is already sorted, this method can take advantage of it: the method assumes that @@ -224,13 +199,14 @@ static void sort (Object[] a, int lo, int hi) { * @param a the array in which a range is to be sorted * @param lo the index of the first element in the range to be sorted * @param hi the index after the last element in the range to be sorted - * @param start the index of the first element in the range that is not already known to be sorted (@code lo <= start <= hi} - */ - @SuppressWarnings("fallthrough") private static void binarySort (Object[] a, int lo, int hi, int start) { + * @param start the index of the first element in the range that is not already known to be sorted (@code lo <= start <= hi} */ + @SuppressWarnings("fallthrough") + private static void binarySort (Object[] a, int lo, int hi, int start) { if (DEBUG) assert lo <= start && start <= hi; if (start == lo) start++; for (; start < hi; start++) { - @SuppressWarnings("unchecked") Comparable pivot = (Comparable)a[start]; + @SuppressWarnings("unchecked") + Comparable pivot = (Comparable)a[start]; // Set left (and right) to the index where a[start] (pivot) belongs int left = lo; @@ -268,8 +244,7 @@ static void sort (Object[] a, int lo, int hi) { } } - /** - * Returns the length of the run beginning at the specified position in the specified array and reverses the run if it is + /** Returns the length of the run beginning at the specified position in the specified array and reverses the run if it is * descending (ensuring that the run will always be ascending when the method returns). * * A run is the longest ascending sequence with: @@ -286,9 +261,9 @@ static void sort (Object[] a, int lo, int hi) { * @param a the array in which a run is to be counted and possibly reversed * @param lo index of the first element in the run * @param hi index after the last element that may be contained in the run. It is required that @code{lo < hi}. - * @return the length of the run beginning at the specified position in the specified array - */ - @SuppressWarnings("unchecked") private static int countRunAndMakeAscending (Object[] a, int lo, int hi) { + * @return the length of the run beginning at the specified position in the specified array */ + @SuppressWarnings("unchecked") + private static int countRunAndMakeAscending (Object[] a, int lo, int hi) { if (DEBUG) assert lo < hi; int runHi = lo + 1; if (runHi == hi) return 1; @@ -306,13 +281,11 @@ static void sort (Object[] a, int lo, int hi) { return runHi - lo; } - /** - * Reverse the specified range of the specified array. + /** Reverse the specified range of the specified array. * * @param a the array in which a range is to be reversed * @param lo the index of the first element in the range to be reversed - * @param hi the index after the last element in the range to be reversed - */ + * @param hi the index after the last element in the range to be reversed */ private static void reverseRange (Object[] a, int lo, int hi) { hi--; while (lo < hi) { @@ -322,8 +295,7 @@ private static void reverseRange (Object[] a, int lo, int hi) { } } - /** - * Returns the minimum acceptable run length for an array of the specified length. Natural runs shorter than this will be + /** Returns the minimum acceptable run length for an array of the specified length. Natural runs shorter than this will be * extended with {@link #binarySort}. * * Roughly speaking, the computation is: @@ -335,8 +307,7 @@ private static void reverseRange (Object[] a, int lo, int hi) { * For the rationale, see listsort.txt. * * @param n the length of the array to be sorted - * @return the length of the minimum run to be merged - */ + * @return the length of the minimum run to be merged */ private static int minRunLength (int n) { if (DEBUG) assert n >= 0; int r = 0; // Becomes 1 if any 1 bits are shifted off @@ -347,26 +318,22 @@ private static int minRunLength (int n) { return n + r; } - /** - * Pushes the specified run onto the pending-run stack. + /** Pushes the specified run onto the pending-run stack. * * @param runBase index of the first element in the run - * @param runLen the number of elements in the run - */ + * @param runLen the number of elements in the run */ private void pushRun (int runBase, int runLen) { this.runBase[stackSize] = runBase; this.runLen[stackSize] = runLen; stackSize++; } - /** - * Examines the stack of runs waiting to be merged and merges adjacent runs until the stack invariants are reestablished: + /** Examines the stack of runs waiting to be merged and merges adjacent runs until the stack invariants are reestablished: * * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1] 2. runLen[i - 2] > runLen[i - 1] * * This method is called each time a new run is pushed onto the stack, so the invariants are guaranteed to hold for i < - * stackSize upon entry to the method. - */ + * stackSize upon entry to the method. */ private void mergeCollapse () { while (stackSize > 1) { int n = stackSize - 2; @@ -381,9 +348,7 @@ private void mergeCollapse () { } } - /** - * Merges all runs on the stack until only one remains. This method is called once, to complete the sort. - */ + /** Merges all runs on the stack until only one remains. This method is called once, to complete the sort. */ private void mergeForceCollapse () { while (stackSize > 1) { int n = stackSize - 2; @@ -392,13 +357,12 @@ private void mergeForceCollapse () { } } - /** - * Merges the two runs at stack indices i and i+1. Run i must be the penultimate or antepenultimate run on the stack. In other + /** Merges the two runs at stack indices i and i+1. Run i must be the penultimate or antepenultimate run on the stack. In other * words, i must be equal to stackSize-2 or stackSize-3. * - * @param i stack index of the first of the two runs to merge - */ - @SuppressWarnings("unchecked") private void mergeAt (int i) { + * @param i stack index of the first of the two runs to merge */ + @SuppressWarnings("unchecked") + private void mergeAt (int i) { if (DEBUG) assert stackSize >= 2; if (DEBUG) assert i >= 0; if (DEBUG) assert i == stackSize - 2 || i == stackSize - 3; @@ -446,8 +410,7 @@ private void mergeForceCollapse () { mergeHi(base1, len1, base2, len2); } - /** - * Locates the position at which to insert the specified key into the specified sorted range; if the range contains an element + /** Locates the position at which to insert the specified key into the specified sorted range; if the range contains an element * equal to key, returns the index of the leftmost equal element. * * @param key the key whose insertion point to search for @@ -458,8 +421,7 @@ private void mergeForceCollapse () { * will run. * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k], pretending that a[b - 1] is minus infinity and a[b * + n] is infinity. In other words, key belongs at index b + k; or in other words, the first k elements of a should - * precede key, and the last n - k should follow it. - */ + * precede key, and the last n - k should follow it. */ private static int gallopLeft (Comparable key, Object[] a, int base, int len, int hint) { if (DEBUG) assert len > 0 && hint >= 0 && hint < len; @@ -514,8 +476,7 @@ private static int gallopLeft (Comparable key, Object[] a, int base, int return ofs; } - /** - * Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns the index after the + /** Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns the index after the * rightmost equal element. * * @param key the key whose insertion point to search for @@ -524,8 +485,7 @@ private static int gallopLeft (Comparable key, Object[] a, int base, int * @param len the length of the range; must be > 0 * @param hint the index at which to begin the search, 0 <= hint < n. The closer hint is to the result, the faster this method * will run. - * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] - */ + * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] */ private static int gallopRight (Comparable key, Object[] a, int base, int len, int hint) { if (DEBUG) assert len > 0 && hint >= 0 && hint < len; @@ -580,8 +540,7 @@ private static int gallopRight (Comparable key, Object[] a, int base, in return ofs; } - /** - * Merges two adjacent runs in place, in a stable fashion. The first element of the first run must be greater than the first + /** Merges two adjacent runs in place, in a stable fashion. The first element of the first run must be greater than the first * element of the second run (a[base1] > a[base2]), and the last element of the first run (a[base1 + len1-1]) must be greater * than all elements of the second run. * @@ -591,9 +550,9 @@ private static int gallopRight (Comparable key, Object[] a, int base, in * @param base1 index of first element in first run to be merged * @param len1 length of first run to be merged (must be > 0) * @param base2 index of first element in second run to be merged (must be aBase + aLen) - * @param len2 length of second run to be merged (must be > 0) - */ - @SuppressWarnings("unchecked") private void mergeLo (int base1, int len1, int base2, int len2) { + * @param len2 length of second run to be merged (must be > 0) */ + @SuppressWarnings("unchecked") + private void mergeLo (int base1, int len1, int base2, int len2) { if (DEBUG) assert len1 > 0 && len2 > 0 && base1 + len1 == base2; // Copy first run into temp array @@ -689,16 +648,15 @@ private static int gallopRight (Comparable key, Object[] a, int base, in } } - /** - * Like mergeLo, except that this method should be called only if len1 >= len2; mergeLo should be called if len1 <= len2. + /** Like mergeLo, except that this method should be called only if len1 >= len2; mergeLo should be called if len1 <= len2. * (Either method may be called if len1 == len2.) * * @param base1 index of first element in first run to be merged * @param len1 length of first run to be merged (must be > 0) * @param base2 index of first element in second run to be merged (must be aBase + aLen) - * @param len2 length of second run to be merged (must be > 0) - */ - @SuppressWarnings("unchecked") private void mergeHi (int base1, int len1, int base2, int len2) { + * @param len2 length of second run to be merged (must be > 0) */ + @SuppressWarnings("unchecked") + private void mergeHi (int base1, int len1, int base2, int len2) { if (DEBUG) assert len1 > 0 && len2 > 0 && base1 + len1 == base2; // Copy second run into temp array @@ -797,13 +755,11 @@ private static int gallopRight (Comparable key, Object[] a, int base, in } } - /** - * Ensures that the external array tmp has at least the specified number of elements, increasing its size if necessary. The + /** Ensures that the external array tmp has at least the specified number of elements, increasing its size if necessary. The * size increases exponentially to ensure amortized linear time complexity. * * @param minCapacity the minimum required capacity of the tmp array - * @return tmp, whether or not it grew - */ + * @return tmp, whether or not it grew */ private Object[] ensureCapacity (int minCapacity) { if (tmp.length < minCapacity) { // Compute smallest power of 2 > minCapacity @@ -826,15 +782,13 @@ private Object[] ensureCapacity (int minCapacity) { return tmp; } - /** - * Checks that fromIndex and toIndex are in range, and throws an appropriate exception if they aren't. + /** Checks that fromIndex and toIndex are in range, and throws an appropriate exception if they aren't. * * @param arrayLen the length of the array * @param fromIndex the index of the first element of the range * @param toIndex the index after the last element of the range * @throws IllegalArgumentException if fromIndex > toIndex - * @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > arrayLen - */ + * @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > arrayLen */ private static void rangeCheck (int arrayLen, int fromIndex, int toIndex) { if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); if (fromIndex < 0) throw new ArrayIndexOutOfBoundsException(fromIndex); diff --git a/gdx/src/com/badlogic/gdx/utils/Disposable.java b/gdx/src/com/badlogic/gdx/utils/Disposable.java index 1b93c6698ef..643bd5c9112 100644 --- a/gdx/src/com/badlogic/gdx/utils/Disposable.java +++ b/gdx/src/com/badlogic/gdx/utils/Disposable.java @@ -13,16 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; -/** - * Interface for disposable resources. - * @author mzechner - * - */ +/** Interface for disposable resources. + * @author mzechner */ public interface Disposable { - /** - * Releases all resources of this object. - */ - public void dispose(); + /** Releases all resources of this object. */ + public void dispose (); } diff --git a/gdx/src/com/badlogic/gdx/utils/FloatArray.java b/gdx/src/com/badlogic/gdx/utils/FloatArray.java index 84515b67144..ef6a54237db 100644 --- a/gdx/src/com/badlogic/gdx/utils/FloatArray.java +++ b/gdx/src/com/badlogic/gdx/utils/FloatArray.java @@ -13,51 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.util.Arrays; import com.badlogic.gdx.math.MathUtils; -/** - * A resizable, ordered or unordered float array. Avoids the boxing that occurs with ArrayList. If unordered, this class +/** A resizable, ordered or unordered float array. Avoids the boxing that occurs with ArrayList. If unordered, this class * avoids a memory copy when removing elements (the last element is moved to the removed element's position). - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class FloatArray { public float[] items; public int size; public boolean ordered; - /** - * Creates an ordered array with a capacity of 16. - */ + /** Creates an ordered array with a capacity of 16. */ public FloatArray () { this(false, 16); } - /** - * Creates an ordered array with the specified capacity. - */ + /** Creates an ordered array with the specified capacity. */ public FloatArray (int capacity) { this(false, capacity); } - /** - * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a + /** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a * memory copy. - * @param capacity Any elements added beyond this will cause the backing array to be grown. - */ + * @param capacity Any elements added beyond this will cause the backing array to be grown. */ public FloatArray (boolean ordered, int capacity) { this.ordered = ordered; items = new float[capacity]; } - /** - * Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is + /** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is * ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be - * grown. - */ + * grown. */ public FloatArray (FloatArray array) { this.ordered = array.ordered; size = array.size; @@ -140,9 +131,7 @@ public boolean removeValue (float value) { return false; } - /** - * Removes and returns the item at the specified index. - */ + /** Removes and returns the item at the specified index. */ public float removeIndex (int index) { if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index)); float[] items = this.items; @@ -155,16 +144,12 @@ public float removeIndex (int index) { return value; } - /** - * Removes and returns the last item. - */ + /** Removes and returns the last item. */ public float pop () { return items[--size]; } - /** - * Returns the last item. - */ + /** Returns the last item. */ public float peek () { return items[size - 1]; } @@ -173,19 +158,15 @@ public void clear () { size = 0; } - /** - * Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have - * been removed, or if it is known that more items will not be added. - */ + /** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have + * been removed, or if it is known that more items will not be added. */ public void shrink () { resize(size); } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. - * @return {@link #items} - */ + * @return {@link #items} */ public float[] ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= items.length) resize(Math.max(8, sizeNeeded)); diff --git a/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java b/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java index d8ef1ae58e5..eb6c141cf35 100644 --- a/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java +++ b/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; -import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -60,7 +60,7 @@ static public boolean loadLibrary (String nativeFile32, String nativeFile64) { if (path != null) { System.load(path); } - + return path != null; } @@ -86,13 +86,12 @@ static public String extractLibrary (String native32, String native64) { return nativeFile.exists() ? nativeFile.getAbsolutePath() : null; } - /** - * Loads the libgdx native libraries. - */ + /** Loads the libgdx native libraries. */ static public void load () { - if(disableNativesLoading) { - System.out.println("So you don't like our native lib loading? Good, you are on your own now. We don't give support from here on out"); - return; + if (disableNativesLoading) { + System.out + .println("So you don't like our native lib loading? Good, you are on your own now. We don't give support from here on out"); + return; } if (nativesLoaded) return; diff --git a/gdx/src/com/badlogic/gdx/utils/GdxRuntimeException.java b/gdx/src/com/badlogic/gdx/utils/GdxRuntimeException.java index 4d274c22362..9dc4c801ee6 100644 --- a/gdx/src/com/badlogic/gdx/utils/GdxRuntimeException.java +++ b/gdx/src/com/badlogic/gdx/utils/GdxRuntimeException.java @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; -/** - * Typed runtime exception used throughout libgdx - * - * @author mzechner +/** Typed runtime exception used throughout libgdx * - */ + * @author mzechner */ public class GdxRuntimeException extends RuntimeException { private static final long serialVersionUID = 6735854402467673117L; diff --git a/gdx/src/com/badlogic/gdx/utils/IdentityMap.java b/gdx/src/com/badlogic/gdx/utils/IdentityMap.java index 47f7265df2d..f7067a5e7a8 100644 --- a/gdx/src/com/badlogic/gdx/utils/IdentityMap.java +++ b/gdx/src/com/badlogic/gdx/utils/IdentityMap.java @@ -13,24 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.util.Iterator; import java.util.NoSuchElementException; -import java.util.Random; import com.badlogic.gdx.math.MathUtils; -/** - * An unordered map that uses identity comparison. This implementation is a cuckoo hash map using 3 hashes, random walking, and a +/** An unordered map that uses identity comparison. This implementation is a cuckoo hash map using 3 hashes, random walking, and a * small stash for problematic keys. Null keys are not allowed. Null values are allowed. No allocation is done except when growing * the table size.
        *
        * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class IdentityMap { private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; @@ -51,26 +49,20 @@ public class IdentityMap { private Values values; private Keys keys; - /** - * Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the - * backing table. - */ + /** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the + * backing table. */ public IdentityMap () { this(32, 0.8f); } - /** - * Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing - * table. - */ + /** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing + * table. */ public IdentityMap (int initialCapacity) { this(initialCapacity, 0.8f); } - /** - * Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items - * before growing the backing table. - */ + /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items + * before growing the backing table. */ public IdentityMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (capacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); @@ -144,9 +136,7 @@ public V put (K key, V value) { return null; } - /** - * Skips checks for existing keys. - */ + /** Skips checks for existing keys. */ private void putResize (K key, V value) { // Check for empty buckets. int hashCode = System.identityHashCode(key); @@ -360,10 +350,8 @@ public void clear () { stashSize = 0; } - /** - * Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be - * an expensive operation. - */ + /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be + * an expensive operation. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { @@ -400,10 +388,8 @@ private boolean containsKeyStash (K key) { return false; } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many - * items to avoid multiple backing array resizes. - */ + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int)(sizeNeeded / loadFactor))); @@ -470,10 +456,8 @@ public String toString () { return buffer.toString(); } - /** - * Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Entries entries () { if (entries == null) entries = new Entries(this); @@ -482,10 +466,8 @@ public Entries entries () { return entries; } - /** - * Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Values values () { if (values == null) values = new Values(this); @@ -494,10 +476,8 @@ public Values values () { return values; } - /** - * Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time - * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time + * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Keys keys () { if (keys == null) keys = new Keys(this); @@ -563,9 +543,7 @@ public Entries (IdentityMap map) { super(map); } - /** - * Note the same entry instance is returned each time this method is called. - */ + /** Note the same entry instance is returned each time this method is called. */ public Entry next () { if (!hasNext) throw new NoSuchElementException(); K[] keyTable = map.keyTable; @@ -605,9 +583,7 @@ public Iterator iterator () { return this; } - /** - * Returns a new array containing the remaining values. - */ + /** Returns a new array containing the remaining values. */ public Array toArray () { Array array = new Array(true, map.size); while (hasNext) @@ -636,9 +612,7 @@ public Iterator iterator () { return this; } - /** - * Returns a new array containing the remaining keys. - */ + /** Returns a new array containing the remaining keys. */ public Array toArray () { Array array = new Array(true, map.size); while (hasNext) diff --git a/gdx/src/com/badlogic/gdx/utils/IntArray.java b/gdx/src/com/badlogic/gdx/utils/IntArray.java index 53038f63944..763c37473f2 100644 --- a/gdx/src/com/badlogic/gdx/utils/IntArray.java +++ b/gdx/src/com/badlogic/gdx/utils/IntArray.java @@ -13,51 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.util.Arrays; import com.badlogic.gdx.math.MathUtils; -/** - * A resizable, ordered or unordered int array. Avoids the boxing that occurs with ArrayList. If unordered, this class +/** A resizable, ordered or unordered int array. Avoids the boxing that occurs with ArrayList. If unordered, this class * avoids a memory copy when removing elements (the last element is moved to the removed element's position). - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class IntArray { public int[] items; public int size; public boolean ordered; - /** - * Creates an ordered array with a capacity of 16. - */ + /** Creates an ordered array with a capacity of 16. */ public IntArray () { this(false, 16); } - /** - * Creates an ordered array with the specified capacity. - */ + /** Creates an ordered array with the specified capacity. */ public IntArray (int capacity) { this(false, capacity); } - /** - * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a + /** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a * memory copy. - * @param capacity Any elements added beyond this will cause the backing array to be grown. - */ + * @param capacity Any elements added beyond this will cause the backing array to be grown. */ public IntArray (boolean ordered, int capacity) { this.ordered = ordered; items = new int[capacity]; } - /** - * Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is + /** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is * ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be - * grown. - */ + * grown. */ public IntArray (IntArray array) { this.ordered = array.ordered; size = array.size; @@ -140,9 +131,7 @@ public boolean removeValue (int value) { return false; } - /** - * Removes and returns the item at the specified index. - */ + /** Removes and returns the item at the specified index. */ public int removeIndex (int index) { if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index)); int[] items = this.items; @@ -155,16 +144,12 @@ public int removeIndex (int index) { return value; } - /** - * Removes and returns the last item. - */ + /** Removes and returns the last item. */ public int pop () { return items[--size]; } - /** - * Returns the last item. - */ + /** Returns the last item. */ public int peek () { return items[size - 1]; } @@ -173,19 +158,15 @@ public void clear () { size = 0; } - /** - * Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have - * been removed, or if it is known that more items will not be added. - */ + /** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have + * been removed, or if it is known that more items will not be added. */ public void shrink () { resize(size); } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. - * @return {@link #items} - */ + * @return {@link #items} */ public int[] ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= items.length) resize(Math.max(8, sizeNeeded)); diff --git a/gdx/src/com/badlogic/gdx/utils/IntMap.java b/gdx/src/com/badlogic/gdx/utils/IntMap.java index 4ef3799f20d..44de64f9538 100644 --- a/gdx/src/com/badlogic/gdx/utils/IntMap.java +++ b/gdx/src/com/badlogic/gdx/utils/IntMap.java @@ -13,24 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.util.Iterator; import java.util.NoSuchElementException; -import java.util.Random; import com.badlogic.gdx.math.MathUtils; -import com.badlogic.gdx.utils.ObjectMap.Entry; -/** - * An unordered map that uses int keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small stash +/** An unordered map that uses int keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small stash * for problematic keys. Null values are allowed. No allocation is done except when growing the table size.
        *
        * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class IntMap { private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; @@ -54,26 +51,20 @@ public class IntMap { private Values values; private Keys keys; - /** - * Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the - * backing table. - */ + /** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the + * backing table. */ public IntMap () { this(32, 0.8f); } - /** - * Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing - * table. - */ + /** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing + * table. */ public IntMap (int initialCapacity) { this(initialCapacity, 0.8f); } - /** - * Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items - * before growing the backing table. - */ + /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items + * before growing the backing table. */ public IntMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (capacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); @@ -157,9 +148,7 @@ public void putAll (IntMap map) { put(entry.key, entry.value); } - /** - * Skips checks for existing keys. - */ + /** Skips checks for existing keys. */ private void putResize (int key, V value) { if (key == 0) { zeroValue = value; @@ -387,10 +376,8 @@ public void clear () { hasZeroValue = false; } - /** - * Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be - * an expensive operation. - */ + /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be + * an expensive operation. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { @@ -430,10 +417,8 @@ private boolean containsKeyStash (int key) { return false; } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many - * items to avoid multiple backing array resizes. - */ + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int)(sizeNeeded / loadFactor))); @@ -500,10 +485,8 @@ public String toString () { return buffer.toString(); } - /** - * Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Entries entries () { if (entries == null) entries = new Entries(this); @@ -512,10 +495,8 @@ public Entries entries () { return entries; } - /** - * Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Values values () { if (values == null) values = new Values(this); @@ -524,10 +505,8 @@ public Values values () { return values; } - /** - * Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time - * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time + * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Keys keys () { if (keys == null) keys = new Keys(this); @@ -603,9 +582,7 @@ public Entries (IntMap map) { super(map); } - /** - * Note the same entry instance is returned each time this method is called. - */ + /** Note the same entry instance is returned each time this method is called. */ public Entry next () { if (!hasNext) throw new NoSuchElementException(); int[] keyTable = map.keyTable; @@ -654,9 +631,7 @@ public Iterator iterator () { return this; } - /** - * Returns a new array containing the remaining values. - */ + /** Returns a new array containing the remaining values. */ public Array toArray () { Array array = new Array(true, map.size); while (hasNext) @@ -677,9 +652,7 @@ public int next () { return key; } - /** - * Returns a new array containing the remaining values. - */ + /** Returns a new array containing the remaining values. */ public IntArray toArray () { IntArray array = new IntArray(true, map.size); while (hasNext) diff --git a/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java b/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java index 52479c2fd1d..b686efa3a23 100644 --- a/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java +++ b/gdx/src/com/badlogic/gdx/utils/LittleEndianInputStream.java @@ -13,109 +13,97 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.io.DataInput; import java.io.DataInputStream; -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 - * - */ +/** Taken from http://www.javafaq.nu/java-example-code-1079.html + * @author mzechner */ public class LittleEndianInputStream extends FilterInputStream implements DataInput { - private DataInputStream din; - - public LittleEndianInputStream(InputStream in) { - super(in); - din=new DataInputStream(in); - } - - public void readFully(byte[] b) throws IOException { - din.readFully(b); - } - - public void readFully(byte[] b, int off, int len) throws IOException { - din.readFully(b, off, len); - } - - public int skipBytes(int n) throws IOException { - return din.skipBytes(n); - } - - public boolean readBoolean() throws IOException { - return din.readBoolean(); - } - - public byte readByte() throws IOException { - return din.readByte(); - } - - public int readUnsignedByte() throws IOException { - return din.readUnsignedByte(); - } - - public short readShort() throws IOException { - int low=din.read(); - int high=din.read(); - return (short)((high << 8) | (low & 0xff)); - } - - public int readUnsignedShort() throws IOException { - int low=din.read(); - int high=din.read(); - return ((high & 0xff) << 8) | (low & 0xff); - } - - public char readChar() throws IOException { - return din.readChar(); - } - - public int readInt() throws IOException { - int[] res=new int[4]; - for(int i=3;i>=0;i--) - res[i]=din.read(); - - return ((res[0] & 0xff) << 24) | - ((res[1] & 0xff) << 16) | - ((res[2] & 0xff) << 8) | - (res[3] & 0xff); - } - - public long readLong() throws IOException { - int[] res=new int[8]; - for(int i=7;i>=0;i--) - res[i]=din.read(); - - return (((long)(res[0] & 0xff) << 56) | - ((long)(res[1] & 0xff) << 48) | - ((long)(res[2] & 0xff) << 40) | - ((long)(res[3] & 0xff) << 32) | - ((long)(res[4] & 0xff) << 24) | - ((long)(res[5] & 0xff) << 16) | - ((long)(res[6] & 0xff) << 8) | - ((long)(res[7] & 0xff))); - } - - public float readFloat() throws IOException { - return Float.intBitsToFloat(readInt()); - } - - public double readDouble() throws IOException { - return Double.longBitsToDouble(readLong()); - } - - public final String readLine() throws IOException { - return din.readLine(); - } - - public String readUTF() throws IOException { - return din.readUTF(); - } + private DataInputStream din; + + public LittleEndianInputStream (InputStream in) { + super(in); + din = new DataInputStream(in); + } + + public void readFully (byte[] b) throws IOException { + din.readFully(b); + } + + public void readFully (byte[] b, int off, int len) throws IOException { + din.readFully(b, off, len); + } + + public int skipBytes (int n) throws IOException { + return din.skipBytes(n); + } + + public boolean readBoolean () throws IOException { + return din.readBoolean(); + } + + public byte readByte () throws IOException { + return din.readByte(); + } + + public int readUnsignedByte () throws IOException { + return din.readUnsignedByte(); + } + + public short readShort () throws IOException { + int low = din.read(); + int high = din.read(); + return (short)((high << 8) | (low & 0xff)); + } + + public int readUnsignedShort () throws IOException { + int low = din.read(); + int high = din.read(); + return ((high & 0xff) << 8) | (low & 0xff); + } + + public char readChar () throws IOException { + return din.readChar(); + } + + public int readInt () throws IOException { + int[] res = new int[4]; + for (int i = 3; i >= 0; i--) + res[i] = din.read(); + + return ((res[0] & 0xff) << 24) | ((res[1] & 0xff) << 16) | ((res[2] & 0xff) << 8) | (res[3] & 0xff); + } + + public long readLong () throws IOException { + int[] res = new int[8]; + for (int i = 7; i >= 0; i--) + res[i] = din.read(); + + return (((long)(res[0] & 0xff) << 56) | ((long)(res[1] & 0xff) << 48) | ((long)(res[2] & 0xff) << 40) + | ((long)(res[3] & 0xff) << 32) | ((long)(res[4] & 0xff) << 24) | ((long)(res[5] & 0xff) << 16) + | ((long)(res[6] & 0xff) << 8) | ((long)(res[7] & 0xff))); + } + + public float readFloat () throws IOException { + return Float.intBitsToFloat(readInt()); + } + + public double readDouble () throws IOException { + return Double.longBitsToDouble(readLong()); + } + + public final String readLine () throws IOException { + return din.readLine(); + } + + public String readUTF () throws IOException { + return din.readUTF(); + } } diff --git a/gdx/src/com/badlogic/gdx/utils/Logger.java b/gdx/src/com/badlogic/gdx/utils/Logger.java index 2feca7a5c58..ef7eb00fd8d 100644 --- a/gdx/src/com/badlogic/gdx/utils/Logger.java +++ b/gdx/src/com/badlogic/gdx/utils/Logger.java @@ -1,29 +1,27 @@ + package com.badlogic.gdx.utils; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; -/** - * Simple logger that uses the {@link Application} logging facilities - * to output messages. - * @author mzechner - * - */ +/** Simple logger that uses the {@link Application} logging facilities to output messages. + * @author mzechner */ public class Logger { private final String tag; private boolean enabled = true; - - public Logger(String tag) { + + public Logger (String tag) { this.tag = tag; } - - public void log(String message) { - if(enabled) { + + public void log (String message) { + if (enabled) { Gdx.app.log(tag, message); } } - - public void setEnabled(boolean enabled) { - this.enabled = enabled;; + + public void setEnabled (boolean enabled) { + this.enabled = enabled; + ; } } diff --git a/gdx/src/com/badlogic/gdx/utils/LongArray.java b/gdx/src/com/badlogic/gdx/utils/LongArray.java index 8c339e87d69..1f3da61b5fa 100644 --- a/gdx/src/com/badlogic/gdx/utils/LongArray.java +++ b/gdx/src/com/badlogic/gdx/utils/LongArray.java @@ -13,51 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.util.Arrays; import com.badlogic.gdx.math.MathUtils; -/** - * A resizable, ordered or unordered long array. Avoids the boxing that occurs with ArrayList. If unordered, this class +/** A resizable, ordered or unordered long array. Avoids the boxing that occurs with ArrayList. If unordered, this class * avoids a memory copy when removing elements (the last element is moved to the removed element's position). - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class LongArray { public long[] items; public int size; public boolean ordered; - /** - * Creates an ordered array with a capacity of 16. - */ + /** Creates an ordered array with a capacity of 16. */ public LongArray () { this(false, 16); } - /** - * Creates an ordered array with the specified capacity. - */ + /** Creates an ordered array with the specified capacity. */ public LongArray (int capacity) { this(false, capacity); } - /** - * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a + /** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a * memory copy. - * @param capacity Any elements added beyond this will cause the backing array to be grown. - */ + * @param capacity Any elements added beyond this will cause the backing array to be grown. */ public LongArray (boolean ordered, int capacity) { this.ordered = ordered; items = new long[capacity]; } - /** - * Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is + /** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is * ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be - * grown. - */ + * grown. */ public LongArray (LongArray array) { this.ordered = array.ordered; size = array.size; @@ -140,9 +131,7 @@ public boolean removeValue (long value) { return false; } - /** - * Removes and returns the item at the specified index. - */ + /** Removes and returns the item at the specified index. */ public long removeIndex (int index) { if (index >= size) throw new IndexOutOfBoundsException(String.valueOf(index)); long[] items = this.items; @@ -155,16 +144,12 @@ public long removeIndex (int index) { return value; } - /** - * Removes and returns the last item. - */ + /** Removes and returns the last item. */ public long pop () { return items[--size]; } - /** - * Returns the last item. - */ + /** Returns the last item. */ public long peek () { return items[size - 1]; } @@ -173,19 +158,15 @@ public void clear () { size = 0; } - /** - * Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have - * been removed, or if it is known that more items will not be added. - */ + /** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items have + * been removed, or if it is known that more items will not be added. */ public void shrink () { resize(size); } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. - * @return {@link #items} - */ + * @return {@link #items} */ public long[] ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= items.length) resize(Math.max(8, sizeNeeded)); diff --git a/gdx/src/com/badlogic/gdx/utils/LongMap.java b/gdx/src/com/badlogic/gdx/utils/LongMap.java index a1e2b613eef..fb555537450 100644 --- a/gdx/src/com/badlogic/gdx/utils/LongMap.java +++ b/gdx/src/com/badlogic/gdx/utils/LongMap.java @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.util.Iterator; import java.util.NoSuchElementException; -import java.util.Random; import com.badlogic.gdx.math.MathUtils; -/** - * An unordered map that uses long keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small +/** An unordered map that uses long keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small * stash for problematic keys. Null values are allowed. No allocation is done except when growing the table size.
        *
        * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class LongMap { private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; @@ -53,26 +51,20 @@ public class LongMap { private Values values; private Keys keys; - /** - * Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the - * backing table. - */ + /** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the + * backing table. */ public LongMap () { this(32, 0.8f); } - /** - * Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing - * table. - */ + /** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing + * table. */ public LongMap (int initialCapacity) { this(initialCapacity, 0.8f); } - /** - * Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items - * before growing the backing table. - */ + /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items + * before growing the backing table. */ public LongMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (capacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); @@ -156,9 +148,7 @@ public void putAll (LongMap map) { put(entry.key, entry.value); } - /** - * Skips checks for existing keys. - */ + /** Skips checks for existing keys. */ private void putResize (long key, V value) { if (key == 0) { zeroValue = value; @@ -386,10 +376,8 @@ public void clear () { hasZeroValue = false; } - /** - * Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be - * an expensive operation. - */ + /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be + * an expensive operation. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { @@ -429,10 +417,8 @@ private boolean containsKeyStash (long key) { return false; } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many - * items to avoid multiple backing array resizes. - */ + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int)(sizeNeeded / loadFactor))); @@ -499,10 +485,8 @@ public String toString () { return buffer.toString(); } - /** - * Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Entries entries () { if (entries == null) entries = new Entries(this); @@ -511,10 +495,8 @@ public Entries entries () { return entries; } - /** - * Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Values values () { if (values == null) values = new Values(this); @@ -523,10 +505,8 @@ public Values values () { return values; } - /** - * Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time - * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time + * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Keys keys () { if (keys == null) keys = new Keys(this); @@ -602,9 +582,7 @@ public Entries (LongMap map) { super(map); } - /** - * Note the same entry instance is returned each time this method is called. - */ + /** Note the same entry instance is returned each time this method is called. */ public Entry next () { if (!hasNext) throw new NoSuchElementException(); long[] keyTable = map.keyTable; @@ -653,9 +631,7 @@ public Iterator iterator () { return this; } - /** - * Returns a new array containing the remaining values. - */ + /** Returns a new array containing the remaining values. */ public Array toArray () { Array array = new Array(true, map.size); while (hasNext) @@ -676,9 +652,7 @@ public long next () { return key; } - /** - * Returns a new array containing the remaining values. - */ + /** Returns a new array containing the remaining values. */ public LongArray toArray () { LongArray array = new LongArray(true, map.size); while (hasNext) diff --git a/gdx/src/com/badlogic/gdx/utils/NumberUtils.java b/gdx/src/com/badlogic/gdx/utils/NumberUtils.java index 8080c03c101..dd674eea0dd 100644 --- a/gdx/src/com/badlogic/gdx/utils/NumberUtils.java +++ b/gdx/src/com/badlogic/gdx/utils/NumberUtils.java @@ -1,23 +1,24 @@ + package com.badlogic.gdx.utils; public class NumberUtils { - public static int floatToIntBits(float value) { + public static int floatToIntBits (float value) { return Float.floatToIntBits(value); } - - public static int floatToRawIntBits(float value) { + + public static int floatToRawIntBits (float value) { return Float.floatToRawIntBits(value); } - - public static float intBitsToFloat(int value) { + + public static float intBitsToFloat (int value) { return Float.intBitsToFloat(value); } - - public static long doubleToLongBits(double value) { + + public static long doubleToLongBits (double value) { return Double.doubleToLongBits(value); } - - public static double longBitsToDouble(long value) { + + public static double longBitsToDouble (long value) { return Double.longBitsToDouble(value); } } diff --git a/gdx/src/com/badlogic/gdx/utils/ObjectMap.java b/gdx/src/com/badlogic/gdx/utils/ObjectMap.java index 326f5692c58..6d9f772532d 100644 --- a/gdx/src/com/badlogic/gdx/utils/ObjectMap.java +++ b/gdx/src/com/badlogic/gdx/utils/ObjectMap.java @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; import java.util.Iterator; import java.util.NoSuchElementException; -import java.util.Random; import com.badlogic.gdx.math.MathUtils; -/** - * An unordered map. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small stash for problematic +/** An unordered map. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small stash for problematic * keys. Null keys are not allowed. Null values are allowed. No allocation is done except when growing the table size.
        *
        * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class ObjectMap { private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; @@ -50,26 +48,20 @@ public class ObjectMap { private Values values; private Keys keys; - /** - * Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the - * backing table. - */ + /** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the + * backing table. */ public ObjectMap () { this(32, 0.8f); } - /** - * Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing - * table. - */ + /** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing + * table. */ public ObjectMap (int initialCapacity) { this(initialCapacity, 0.8f); } - /** - * Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items - * before growing the backing table. - */ + /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items + * before growing the backing table. */ public ObjectMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); if (capacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); @@ -148,9 +140,7 @@ public void putAll (ObjectMap map) { put(entry.key, entry.value); } - /** - * Skips checks for existing keys. - */ + /** Skips checks for existing keys. */ private void putResize (K key, V value) { // Check for empty buckets. int hashCode = key.hashCode(); @@ -364,10 +354,8 @@ public void clear () { stashSize = 0; } - /** - * Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be - * an expensive operation. - */ + /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be + * an expensive operation. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { @@ -404,10 +392,8 @@ private boolean containsKeyStash (K key) { return false; } - /** - * Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many - * items to avoid multiple backing array resizes. - */ + /** Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many + * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int)(sizeNeeded / loadFactor))); @@ -474,10 +460,8 @@ public String toString () { return buffer.toString(); } - /** - * Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Entries entries () { if (entries == null) entries = new Entries(this); @@ -486,10 +470,8 @@ public Entries entries () { return entries; } - /** - * Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each - * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each + * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Values values () { if (values == null) values = new Values(this); @@ -498,10 +480,8 @@ public Values values () { return values; } - /** - * Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time - * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. - */ + /** Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time + * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Keys keys () { if (keys == null) keys = new Keys(this); @@ -567,9 +547,7 @@ public Entries (ObjectMap map) { super(map); } - /** - * Note the same entry instance is returned each time this method is called. - */ + /** Note the same entry instance is returned each time this method is called. */ public Entry next () { if (!hasNext) throw new NoSuchElementException(); K[] keyTable = map.keyTable; @@ -609,9 +587,7 @@ public Iterator iterator () { return this; } - /** - * Returns a new array containing the remaining values. - */ + /** Returns a new array containing the remaining values. */ public Array toArray () { Array array = new Array(true, map.size); while (hasNext) @@ -640,9 +616,7 @@ public Iterator iterator () { return this; } - /** - * Returns a new array containing the remaining keys. - */ + /** Returns a new array containing the remaining keys. */ public Array toArray () { Array array = new Array(true, map.size); while (hasNext) diff --git a/gdx/src/com/badlogic/gdx/utils/PauseableThread.java b/gdx/src/com/badlogic/gdx/utils/PauseableThread.java index c5b775dc576..cf6377ac130 100644 --- a/gdx/src/com/badlogic/gdx/utils/PauseableThread.java +++ b/gdx/src/com/badlogic/gdx/utils/PauseableThread.java @@ -13,25 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + 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 +/** 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 - * - */ + * @author mzechner */ 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. - */ + * @param runnable the runnable. */ public PauseableThread (Runnable runnable) { this.runnable = runnable; } @@ -53,16 +49,12 @@ public void run () { } } - /** - * Pauses the thread. This call is non-blocking - */ + /** Pauses the thread. This call is non-blocking */ public void onPause () { paused = true; } - /** - * Resumes the thread. This call is non-blocking - */ + /** Resumes the thread. This call is non-blocking */ public void onResume () { synchronized (this) { paused = false; @@ -70,16 +62,12 @@ public void onResume () { } } - /** - * @return whether this thread is paused or not - */ + /** @return whether this thread is paused or not */ public boolean isPaused () { return paused; } - /** - * Stops this thread - */ + /** Stops this thread */ public void stopThread () { exit = true; if (paused) onResume(); diff --git a/gdx/src/com/badlogic/gdx/utils/Pool.java b/gdx/src/com/badlogic/gdx/utils/Pool.java index 43030920b9f..cd3b15569de 100644 --- a/gdx/src/com/badlogic/gdx/utils/Pool.java +++ b/gdx/src/com/badlogic/gdx/utils/Pool.java @@ -13,34 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; -/** - * A pool of objects that can be resused to avoid allocation. - * @author Nathan Sweet - */ +/** A pool of objects that can be resused to avoid allocation. + * @author Nathan Sweet */ abstract public class Pool { public final int max; private final Array freeObjects; - /** - * Creates a pool with an initial capacity of 16 and no maximum. - */ + /** Creates a pool with an initial capacity of 16 and no maximum. */ public Pool () { this(16, Integer.MAX_VALUE); } - /** - * Creates a pool with the specified initial capacity and no maximum. - */ + /** Creates a pool with the specified initial capacity and no maximum. */ public Pool (int initialCapacity) { this(initialCapacity, Integer.MAX_VALUE); } - /** - * @param max The maximum number of free objects to store in this pool. - */ + /** @param max The maximum number of free objects to store in this pool. */ public Pool (int initialCapacity, int max) { freeObjects = new Array(false, initialCapacity); this.max = max; @@ -48,36 +41,28 @@ public Pool (int initialCapacity, int max) { abstract protected T newObject (); - /** - * Returns an object from this pool. The object may be new (from {@link #newObject()}) or reused (previously - * {@link #free(Object) freed}). - */ + /** Returns an object from this pool. The object may be new (from {@link #newObject()}) or reused (previously + * {@link #free(Object) freed}). */ public T obtain () { return freeObjects.size == 0 ? newObject() : freeObjects.pop(); } - /** - * Puts the specified object in the pool, making it eligible to be returned by {@link #obtain()}. If the pool already contains - * {@link #max} free objects, the specified object is ignored. - */ + /** Puts the specified object in the pool, making it eligible to be returned by {@link #obtain()}. If the pool already contains + * {@link #max} free objects, the specified object is ignored. */ public void free (T object) { if (object == null) throw new IllegalArgumentException("object cannot be null."); if (freeObjects.size < max) freeObjects.add(object); } - /** - * Puts the specified objects in the pool. - * @see #free(Object) - */ + /** Puts the specified objects in the pool. + * @see #free(Object) */ public void free (Array objects) { for (int i = 0, n = Math.min(objects.size, max - freeObjects.size); i < n; i++) freeObjects.add(objects.get(i)); } - - /** - * Removes all free objects from this pool. - */ - public void clear() { + + /** Removes all free objects from this pool. */ + public void clear () { freeObjects.clear(); } } diff --git a/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java b/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java index b5103602f38..bb130ba9c71 100644 --- a/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java +++ b/gdx/src/com/badlogic/gdx/utils/PooledLinkedList.java @@ -13,15 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.utils; -/** - * A simple linked list that pools its nodes. This is a highly specialized class used in a couple of 2D scene graph classes. I +/** 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 - * - */ + * @author mzechner */ public class PooledLinkedList { static final class Item { public T payload; @@ -64,18 +62,14 @@ public void add (T object) { size++; } - /** - * Starts iterating over the lists items - */ + /** Starts iterating over the lists items */ public void iter () { iter = head; } - /** - * Gets the next item in the list + /** Gets the next item in the list * - * @return the next item in the list or null if there are no more items - */ + * @return the next item in the list or null if there are no more items */ public T next () { if (iter == null) return null; @@ -85,9 +79,7 @@ public T 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; @@ -121,35 +113,35 @@ public void remove () { n.prev = p; } -// public static void main (String[] argv) { -// PooledLinkedList list = new PooledLinkedList(10); +// 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(); -// list.remove(); -// list.next(); -// list.next(); -// list.remove(); +// list.add(1); +// list.add(2); +// list.add(3); +// list.add(4); +// list.iter(); +// list.next(); +// list.next(); +// list.remove(); +// list.next(); +// list.next(); +// list.remove(); // -// list.iter(); -// Integer v = null; -// while ((v = list.next()) != null) -// System.out.println(v); +// list.iter(); +// Integer v = null; +// while ((v = list.next()) != null) +// System.out.println(v); // -// list.iter(); -// list.next(); -// list.next(); -// list.remove(); +// list.iter(); +// list.next(); +// list.next(); +// list.remove(); // -// list.iter(); -// list.next(); -// list.remove(); -// } +// list.iter(); +// list.next(); +// list.remove(); +// } public void clear () { iter(); diff --git a/gdx/src/com/badlogic/gdx/utils/ScreenUtils.java b/gdx/src/com/badlogic/gdx/utils/ScreenUtils.java index bd37a1dd69b..db562afa966 100644 --- a/gdx/src/com/badlogic/gdx/utils/ScreenUtils.java +++ b/gdx/src/com/badlogic/gdx/utils/ScreenUtils.java @@ -21,65 +21,44 @@ import com.badlogic.gdx.Gdx; 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.g2d.TextureRegion; -import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.math.MathUtils; -/** - * Class with static helper methods that provide access to the default OpenGL - * FrameBuffer. These methods can be used to get the entire screen content or a - * portion thereof. - * - * @author espitz +/** Class with static helper methods that provide access to the default OpenGL FrameBuffer. These methods can be used to get the + * entire screen content or a portion thereof. * - */ + * @author espitz */ public class ScreenUtils { - /** - * Returns the default framebuffer contents as a {@link TextureRegion} with - * a width and height equal to the current screen size. The base - * {@link Texture} always has {@link MathUtils#nextPowerOfTwo} dimensions - * and RGBA8888 {@link Format}. It can be accessed via - * {@link TextureRegion#getTexture}. The texture is not managed and has to - * be reloaded manually on a context loss. The returned TextureRegion is - * flipped along the Y axis by default. - */ - public static TextureRegion getFrameBufferTexture() { + /** Returns the default framebuffer contents as a {@link TextureRegion} with a width and height equal to the current screen + * size. The base {@link Texture} always has {@link MathUtils#nextPowerOfTwo} dimensions and RGBA8888 {@link Format}. It can be + * accessed via {@link TextureRegion#getTexture}. The texture is not managed and has to be reloaded manually on a context loss. + * The returned TextureRegion is flipped along the Y axis by default. */ + public static TextureRegion getFrameBufferTexture () { final int w = Gdx.graphics.getWidth(); final int h = Gdx.graphics.getHeight(); return getFrameBufferTexture(0, 0, w, h); } - /** - * Returns a portion of the default framebuffer contents specified by x, y, - * width and height as a {@link TextureRegion} with the same dimensions. The - * base {@link Texture} always has {@link MathUtils#nextPowerOfTwo} - * dimensions and RGBA8888 {@link Format}. It can be accessed via - * {@link TextureRegion#getTexture}. This texture is not managed and has to - * be reloaded manually on a context loss. If the width and height specified - * are larger than the framebuffer dimensions, the Texture will be padded - * accordingly. Pixels that fall outside of the current screen will have - * RGBA values of 0. + /** Returns a portion of the default framebuffer contents specified by x, y, width and height as a {@link TextureRegion} with + * the same dimensions. The base {@link Texture} always has {@link MathUtils#nextPowerOfTwo} dimensions and RGBA8888 + * {@link Format}. It can be accessed via {@link TextureRegion#getTexture}. This texture is not managed and has to be reloaded + * manually on a context loss. If the width and height specified are larger than the framebuffer dimensions, the Texture will + * be padded accordingly. Pixels that fall outside of the current screen will have RGBA values of 0. * - * @param x - * the x position of the framebuffer contents to capture - * @param y - * the y position of the framebuffer contents to capture - * @param w - * the width of the framebuffer contents to capture - * @param h - * the height of the framebuffer contents to capture - */ - public static TextureRegion getFrameBufferTexture(int x, int y, int w, int h) { + * @param x the x position of the framebuffer contents to capture + * @param y the y position of the framebuffer contents to capture + * @param w the width of the framebuffer contents to capture + * @param h the height of the framebuffer contents to capture */ + public static TextureRegion getFrameBufferTexture (int x, int y, int w, int h) { final int potW = MathUtils.nextPowerOfTwo(w); final int potH = MathUtils.nextPowerOfTwo(h); final Pixmap pixmap = new Pixmap(potW, potH, Format.RGBA8888); ByteBuffer pixels = pixmap.getPixels(); - Gdx.gl.glReadPixels(x, y, potW, potH, GL10.GL_RGBA, - GL10.GL_UNSIGNED_BYTE, pixels); + Gdx.gl.glReadPixels(x, y, potW, potH, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixels); Texture texture = new Texture(pixmap); TextureRegion textureRegion = new TextureRegion(texture, 0, h, w, -h); @@ -88,42 +67,29 @@ public static TextureRegion getFrameBufferTexture(int x, int y, int w, int h) { return textureRegion; } - /** - * Returns the default framebuffer contents as a byte[] array with a length - * equal to screen width * height * 4. The byte[] will always contain - * RGBA8888 data. Because of differences in screen and image origins the - * framebuffer contents should be flipped along the Y axis if you intend - * save them to disk as a bitmap. Flipping is not a cheap operation, so use - * this functionality wisely. + /** Returns the default framebuffer contents as a byte[] array with a length equal to screen width * height * 4. The byte[] will + * always contain RGBA8888 data. Because of differences in screen and image origins the framebuffer contents should be flipped + * along the Y axis if you intend save them to disk as a bitmap. Flipping is not a cheap operation, so use this functionality + * wisely. * - * @param flipY - * whether to flip pixels along Y axis - */ - public static byte[] getFrameBufferPixels(boolean flipY) { + * @param flipY whether to flip pixels along Y axis */ + public static byte[] getFrameBufferPixels (boolean flipY) { final int w = Gdx.graphics.getWidth(); final int h = Gdx.graphics.getHeight(); return getFrameBufferPixels(0, 0, w, h, flipY); } - /** - * Returns a portion of the default framebuffer contents specified by x, y, - * width and height, as a byte[] array with a length equal to the specified - * width * height * 4. The byte[] will always contain RGBA8888 data. If the - * width and height specified are larger than the framebuffer dimensions, - * the Texture will be padded accordingly. Pixels that fall outside of the - * current screen will have RGBA values of 0. Because of differences in - * screen and image origins the framebuffer contents should be flipped along - * the Y axis if you intend save them to disk as a bitmap. Flipping is not - * cheap operation, so use this functionality wisely. + /** Returns a portion of the default framebuffer contents specified by x, y, width and height, as a byte[] array with a length + * equal to the specified width * height * 4. The byte[] will always contain RGBA8888 data. If the width and height specified + * are larger than the framebuffer dimensions, the Texture will be padded accordingly. Pixels that fall outside of the current + * screen will have RGBA values of 0. Because of differences in screen and image origins the framebuffer contents should be + * flipped along the Y axis if you intend save them to disk as a bitmap. Flipping is not cheap operation, so use this + * functionality wisely. * - * @param flipY - * whether to flip pixels along Y axis - */ - public static byte[] getFrameBufferPixels(int x, int y, int w, int h, - boolean flipY) { + * @param flipY whether to flip pixels along Y axis */ + public static byte[] getFrameBufferPixels (int x, int y, int w, int h, boolean flipY) { final ByteBuffer pixels = BufferUtils.newByteBuffer(w * h * 4); - Gdx.gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, - pixels); + Gdx.gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixels); final int numBytes = w * h * 4; byte[] lines = new byte[numBytes]; if (flipY) { diff --git a/gdx/src/com/badlogic/gdx/utils/Sort.java b/gdx/src/com/badlogic/gdx/utils/Sort.java index fbaeb17e490..a7b21237071 100644 --- a/gdx/src/com/badlogic/gdx/utils/Sort.java +++ b/gdx/src/com/badlogic/gdx/utils/Sort.java @@ -15,14 +15,12 @@ import java.util.Comparator; -/** - * Provides methods to sort arrays of objects. Sorting requires working memory and this class allows that memory to be reused to +/** Provides methods to sort arrays of objects. Sorting requires working memory and this class allows that memory to be reused to * avoid allocation. The sorting is otherwise identical to the Arrays.sort methods (uses timsort).
        *
        * Note that sorting primitive arrays with the Arrays.sort methods does not allocate memory (unless sorting large arrays of char, * short, or byte). - * @author Nathan Sweet - */ + * @author Nathan Sweet */ public class Sort { static private Sort instance; @@ -59,9 +57,7 @@ public void sort (T[] a, Comparator c, int fromIndex, int toIndex) { timSort.doSort(a, c, fromIndex, toIndex); } - /** - * Returns a Sort instance for convenience. Multiple threads must not use this instance at the same time. - */ + /** Returns a Sort instance for convenience. Multiple threads must not use this instance at the same time. */ static public Sort instance () { if (instance == null) instance = new Sort(); return instance; diff --git a/gdx/src/com/badlogic/gdx/utils/SortedIntList.java b/gdx/src/com/badlogic/gdx/utils/SortedIntList.java index 0bf585597e1..1ce339ddce6 100644 --- a/gdx/src/com/badlogic/gdx/utils/SortedIntList.java +++ b/gdx/src/com/badlogic/gdx/utils/SortedIntList.java @@ -1,110 +1,95 @@ -package com.badlogic.gdx.utils; +package com.badlogic.gdx.utils; -/** - * A sorted double linked list which uses ints for indexing - * - * @param - */ +/** A sorted double linked list which uses ints for indexing + * + * @param */ public class SortedIntList implements Iterable> { - private NodePool nodePool = new NodePool(); //avoid allocating nodes + private NodePool nodePool = new NodePool(); // avoid allocating nodes private Iterator iterator; int size = 0; Node first; - /** - * Creates an ascending list - */ - public SortedIntList() { + /** Creates an ascending list */ + public SortedIntList () { } - /** - * Inserts an element into the list at the given index - * + /** Inserts an element into the list at the given index + * * @param index Index of the element * @param value Element to insert - * @return Element replaced by newly inserted element, null if nothing was replaced - */ - public E insert(int index, E value) { - if(first != null) { + * @return Element replaced by newly inserted element, null if nothing was replaced */ + public E insert (int index, E value) { + if (first != null) { Node c = first; - //iterate to the right until we can't move any further because the next number is bigger than index - while(c.n != null && c.n.index <= index) { + // iterate to the right until we can't move any further because the next number is bigger than index + while (c.n != null && c.n.index <= index) { c = c.n; } - //add one to the right - if(index > c.index) { + // add one to the right + if (index > c.index) { c.n = nodePool.obtain(c, c.n, value, index); - if(c.n.n != null) { + if (c.n.n != null) { c.n.n.p = c.n; } size++; } - //the new element is smaller than every other element - else if(index < c.index) { + // the new element is smaller than every other element + else if (index < c.index) { Node newFirst = nodePool.obtain(null, first, value, index); first.p = newFirst; first = newFirst; size++; } - //that element already exists so swap the value + // that element already exists so swap the value else { c.value = value; } - } - else { + } else { first = nodePool.obtain(null, null, value, index); size++; } return null; } - /** - * Retrieves an element at a given index - * + /** Retrieves an element at a given index + * * @param index Index of the element to retrieve - * @return Matching element, null otherwise - */ - public E get(int index) { + * @return Matching element, null otherwise */ + public E get (int index) { E match = null; - if(first != null) { + if (first != null) { Node c = first; - while(c.n != null && c.index < index) { + while (c.n != null && c.index < index) { c = c.n; } - if(c.index == index) { + if (c.index == index) { match = c.value; } } return match; } - /** - * Clears list - */ - public void clear() { - for(; first != null; first = first.n) { + /** Clears list */ + public void clear () { + for (; first != null; first = first.n) { nodePool.free(first); } size = 0; } - /** - * @return size of list equal to elements contained in it - */ - public int size() { + /** @return size of list equal to elements contained in it */ + public int size () { return size; } - /** - * Returns an iterator to traverse the list.
        + /** Returns an iterator to traverse the list.
        * Only one iterator can be active per list at any given time. - * - * @return Iterator to traverse list - */ - public java.util.Iterator> iterator() { - if(iterator == null) { + * + * @return Iterator to traverse list */ + public java.util.Iterator> iterator () { + if (iterator == null) { iterator = new Iterator(); } return iterator.reset(); @@ -115,29 +100,29 @@ class Iterator implements java.util.Iterator> { private Node previousPosition; @Override - public boolean hasNext() { + public boolean hasNext () { return position != null; } @Override - public Node next() { + public Node next () { previousPosition = position; position = position.n; return previousPosition; } @Override - public void remove() { - //the contract specifies to remove the last returned element, if nothing was returned yet assumably do nothing - if(previousPosition != null) { - //if we are at the second element set it as the first element - if(previousPosition == first) { + public void remove () { + // the contract specifies to remove the last returned element, if nothing was returned yet assumably do nothing + if (previousPosition != null) { + // if we are at the second element set it as the first element + if (previousPosition == first) { first = position; } - //else remove last returned element by changing the chain + // else remove last returned element by changing the chain else { previousPosition.p.n = position; - if(position != null) { + if (position != null) { position.p = previousPosition.p; } } @@ -145,7 +130,7 @@ public void remove() { } } - public Iterator reset() { + public Iterator reset () { position = first; previousPosition = null; return this; @@ -153,31 +138,23 @@ public Iterator reset() { } public static class Node { - /** - * Node previous to this - */ + /** Node previous to this */ protected Node p; - /** - * Node next to this - */ + /** Node next to this */ protected Node n; - /** - * Value held - */ + /** Value held */ public E value; - /** - * Index value in list - */ + /** Index value in list */ public int index; } static class NodePool extends Pool> { @Override - protected Node newObject() { + protected Node newObject () { return new Node(); } - public Node obtain(Node p, Node n, E value, int index) { + public Node obtain (Node p, Node n, E value, int index) { Node newNode = super.obtain(); newNode.p = p; newNode.n = n; diff --git a/gdx/src/com/badlogic/gdx/utils/TimSort.java b/gdx/src/com/badlogic/gdx/utils/TimSort.java index 48f03662b50..4a7ecae57d2 100644 --- a/gdx/src/com/badlogic/gdx/utils/TimSort.java +++ b/gdx/src/com/badlogic/gdx/utils/TimSort.java @@ -16,8 +16,7 @@ import java.util.Arrays; import java.util.Comparator; -/** - * A stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when running on partially sorted +/** A stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when running on partially sorted * arrays, while offering performance comparable to a traditional mergesort when run on random arrays. Like all proper mergesorts, * this sort is stable and runs O(n log n) time (worst case). In the worst case, this sort requires temporary storage space for * n/2 object references; in the best case, it requires only a small constant amount of space. @@ -37,11 +36,9 @@ * * While the API to this class consists solely of static methods, it is (privately) instantiable; a TimSort instance holds the * state of an ongoing sort, assuming the input array is large enough to warrant the full-blown TimSort. Small arrays are sorted - * in place, using a binary insertion sort. - */ + * in place, using a binary insertion sort. */ class TimSort { - /** - * This is the minimum sized sequence that will be merged. Shorter sequences will be lengthened by calling binarySort. If the + /** This is the minimum sized sequence that will be merged. Shorter sequences will be lengthened by calling binarySort. If the * entire array is less than this length, no merges will be performed. * * This constant should be a power of two. It was 64 in Tim Peter's C implementation, but 32 was empirically determined to work @@ -50,60 +47,43 @@ class TimSort { * * If you decrease this constant, you must change the stackLen computation in the TimSort constructor, or you risk an * ArrayOutOfBounds exception. See listsort.txt for a discussion of the minimum stack length required as a function of the - * length of the array being sorted and the minimum merge sequence length. - */ + * length of the array being sorted and the minimum merge sequence length. */ private static final int MIN_MERGE = 32; - /** - * The array being sorted. - */ + /** The array being sorted. */ private T[] a; - /** - * The comparator for this sort. - */ + /** The comparator for this sort. */ private Comparator c; - /** - * When we get into galloping mode, we stay there until both runs win less often than MIN_GALLOP consecutive times. - */ + /** When we get into galloping mode, we stay there until both runs win less often than MIN_GALLOP consecutive times. */ private static final int MIN_GALLOP = 7; - /** - * This controls when we get *into* galloping mode. It is initialized to MIN_GALLOP. The mergeLo and mergeHi methods nudge it - * higher for random data, and lower for highly structured data. - */ + /** This controls when we get *into* galloping mode. It is initialized to MIN_GALLOP. The mergeLo and mergeHi methods nudge it + * higher for random data, and lower for highly structured data. */ private int minGallop = MIN_GALLOP; - /** - * Maximum initial size of tmp array, which is used for merging. The array can grow to accommodate demand. + /** Maximum initial size of tmp array, which is used for merging. The array can grow to accommodate demand. * * Unlike Tim's original C version, we do not allocate this much storage when sorting smaller arrays. This change was required - * for performance. - */ + * for performance. */ private static final int INITIAL_TMP_STORAGE_LENGTH = 256; - /** - * Temp storage for merges. - */ + /** Temp storage for merges. */ private T[] tmp; // Actual runtime type will be Object[], regardless of T - /** - * A stack of pending runs yet to be merged. Run i starts at address base[i] and extends for len[i] elements. It's always true + /** A stack of pending runs yet to be merged. Run i starts at address base[i] and extends for len[i] elements. It's always true * (so long as the indices are in bounds) that: * * runBase[i] + runLen[i] == runBase[i + 1] * - * so we could cut the storage for this, but it's a minor amount, and keeping all the info explicit simplifies the code. - */ + * so we could cut the storage for this, but it's a minor amount, and keeping all the info explicit simplifies the code. */ private int stackSize = 0; // Number of pending runs on stack private final int[] runBase; private final int[] runLen; - /** - * Asserts have been placed in if-statements for performace. To enable them, set this field to true and enable them in VM with - * a command line flag. If you modify this class, please do test the asserts! - */ + /** Asserts have been placed in if-statements for performace. To enable them, set this field to true and enable them in VM with + * a command line flag. If you modify this class, please do test the asserts! */ private static final boolean DEBUG = false; TimSort () { @@ -128,10 +108,8 @@ public void doSort (T[] a, Comparator c, int lo, int hi) { this.a = a; this.c = c; - /** - * March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and - * merging runs to maintain stack invariant. - */ + /** March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and + * merging runs to maintain stack invariant. */ int minRun = minRunLength(nRemaining); do { // Identify next run @@ -159,12 +137,10 @@ public void doSort (T[] a, Comparator c, int lo, int hi) { if (DEBUG) assert stackSize == 1; } - /** - * Creates a TimSort instance to maintain the state of an ongoing sort. + /** Creates a TimSort instance to maintain the state of an ongoing sort. * * @param a the array to be sorted - * @param c the comparator to determine the order of the sort - */ + * @param c the comparator to determine the order of the sort */ private TimSort (T[] a, Comparator c) { this.a = a; this.c = c; @@ -212,10 +188,8 @@ static void sort (T[] a, int lo, int hi, Comparator c) { return; } - /** - * March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and - * merging runs to maintain stack invariant. - */ + /** March over the array once, left to right, finding natural runs, extending short natural runs to minRun elements, and + * merging runs to maintain stack invariant. */ TimSort ts = new TimSort(a, c); int minRun = minRunLength(nRemaining); do { @@ -244,8 +218,7 @@ static void sort (T[] a, int lo, int hi, Comparator c) { if (DEBUG) assert ts.stackSize == 1; } - /** - * Sorts the specified portion of the specified array using a binary insertion sort. This is the best method for sorting small + /** Sorts the specified portion of the specified array using a binary insertion sort. This is the best method for sorting small * numbers of elements. It requires O(n log n) compares, but O(n^2) data movement (worst case). * * If the initial part of the specified range is already sorted, this method can take advantage of it: the method assumes that @@ -255,9 +228,9 @@ static void sort (T[] a, int lo, int hi, Comparator c) { * @param lo the index of the first element in the range to be sorted * @param hi the index after the last element in the range to be sorted * @param start the index of the first element in the range that is not already known to be sorted (@code lo <= start <= hi} - * @param c comparator to used for the sort - */ - @SuppressWarnings("fallthrough") private static void binarySort (T[] a, int lo, int hi, int start, Comparator c) { + * @param c comparator to used for the sort */ + @SuppressWarnings("fallthrough") + private static void binarySort (T[] a, int lo, int hi, int start, Comparator c) { if (DEBUG) assert lo <= start && start <= hi; if (start == lo) start++; for (; start < hi; start++) { @@ -299,8 +272,7 @@ static void sort (T[] a, int lo, int hi, Comparator c) { } } - /** - * Returns the length of the run beginning at the specified position in the specified array and reverses the run if it is + /** Returns the length of the run beginning at the specified position in the specified array and reverses the run if it is * descending (ensuring that the run will always be ascending when the method returns). * * A run is the longest ascending sequence with: @@ -318,8 +290,7 @@ static void sort (T[] a, int lo, int hi, Comparator c) { * @param lo index of the first element in the run * @param hi index after the last element that may be contained in the run. It is required that @code{lo < hi}. * @param c the comparator to used for the sort - * @return the length of the run beginning at the specified position in the specified array - */ + * @return the length of the run beginning at the specified position in the specified array */ private static int countRunAndMakeAscending (T[] a, int lo, int hi, Comparator c) { if (DEBUG) assert lo < hi; int runHi = lo + 1; @@ -338,13 +309,11 @@ private static int countRunAndMakeAscending (T[] a, int lo, int hi, Comparat return runHi - lo; } - /** - * Reverse the specified range of the specified array. + /** Reverse the specified range of the specified array. * * @param a the array in which a range is to be reversed * @param lo the index of the first element in the range to be reversed - * @param hi the index after the last element in the range to be reversed - */ + * @param hi the index after the last element in the range to be reversed */ private static void reverseRange (Object[] a, int lo, int hi) { hi--; while (lo < hi) { @@ -354,8 +323,7 @@ private static void reverseRange (Object[] a, int lo, int hi) { } } - /** - * Returns the minimum acceptable run length for an array of the specified length. Natural runs shorter than this will be + /** Returns the minimum acceptable run length for an array of the specified length. Natural runs shorter than this will be * extended with {@link #binarySort}. * * Roughly speaking, the computation is: @@ -367,8 +335,7 @@ private static void reverseRange (Object[] a, int lo, int hi) { * For the rationale, see listsort.txt. * * @param n the length of the array to be sorted - * @return the length of the minimum run to be merged - */ + * @return the length of the minimum run to be merged */ private static int minRunLength (int n) { if (DEBUG) assert n >= 0; int r = 0; // Becomes 1 if any 1 bits are shifted off @@ -379,26 +346,22 @@ private static int minRunLength (int n) { return n + r; } - /** - * Pushes the specified run onto the pending-run stack. + /** Pushes the specified run onto the pending-run stack. * * @param runBase index of the first element in the run - * @param runLen the number of elements in the run - */ + * @param runLen the number of elements in the run */ private void pushRun (int runBase, int runLen) { this.runBase[stackSize] = runBase; this.runLen[stackSize] = runLen; stackSize++; } - /** - * Examines the stack of runs waiting to be merged and merges adjacent runs until the stack invariants are reestablished: + /** Examines the stack of runs waiting to be merged and merges adjacent runs until the stack invariants are reestablished: * * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1] 2. runLen[i - 2] > runLen[i - 1] * * This method is called each time a new run is pushed onto the stack, so the invariants are guaranteed to hold for i < - * stackSize upon entry to the method. - */ + * stackSize upon entry to the method. */ private void mergeCollapse () { while (stackSize > 1) { int n = stackSize - 2; @@ -413,9 +376,7 @@ private void mergeCollapse () { } } - /** - * Merges all runs on the stack until only one remains. This method is called once, to complete the sort. - */ + /** Merges all runs on the stack until only one remains. This method is called once, to complete the sort. */ private void mergeForceCollapse () { while (stackSize > 1) { int n = stackSize - 2; @@ -424,12 +385,10 @@ private void mergeForceCollapse () { } } - /** - * Merges the two runs at stack indices i and i+1. Run i must be the penultimate or antepenultimate run on the stack. In other + /** Merges the two runs at stack indices i and i+1. Run i must be the penultimate or antepenultimate run on the stack. In other * words, i must be equal to stackSize-2 or stackSize-3. * - * @param i stack index of the first of the two runs to merge - */ + * @param i stack index of the first of the two runs to merge */ private void mergeAt (int i) { if (DEBUG) assert stackSize >= 2; if (DEBUG) assert i >= 0; @@ -478,8 +437,7 @@ private void mergeAt (int i) { mergeHi(base1, len1, base2, len2); } - /** - * Locates the position at which to insert the specified key into the specified sorted range; if the range contains an element + /** Locates the position at which to insert the specified key into the specified sorted range; if the range contains an element * equal to key, returns the index of the leftmost equal element. * * @param key the key whose insertion point to search for @@ -491,8 +449,7 @@ private void mergeAt (int i) { * @param c the comparator used to order the range, and to search * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k], pretending that a[b - 1] is minus infinity and a[b * + n] is infinity. In other words, key belongs at index b + k; or in other words, the first k elements of a should - * precede key, and the last n - k should follow it. - */ + * precede key, and the last n - k should follow it. */ private static int gallopLeft (T key, T[] a, int base, int len, int hint, Comparator c) { if (DEBUG) assert len > 0 && hint >= 0 && hint < len; int lastOfs = 0; @@ -546,8 +503,7 @@ private static int gallopLeft (T key, T[] a, int base, int len, int hint, Co return ofs; } - /** - * Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns the index after the + /** Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns the index after the * rightmost equal element. * * @param key the key whose insertion point to search for @@ -557,8 +513,7 @@ private static int gallopLeft (T key, T[] a, int base, int len, int hint, Co * @param hint the index at which to begin the search, 0 <= hint < n. The closer hint is to the result, the faster this method * will run. * @param c the comparator used to order the range, and to search - * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] - */ + * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] */ private static int gallopRight (T key, T[] a, int base, int len, int hint, Comparator c) { if (DEBUG) assert len > 0 && hint >= 0 && hint < len; @@ -613,8 +568,7 @@ private static int gallopRight (T key, T[] a, int base, int len, int hint, C return ofs; } - /** - * Merges two adjacent runs in place, in a stable fashion. The first element of the first run must be greater than the first + /** Merges two adjacent runs in place, in a stable fashion. The first element of the first run must be greater than the first * element of the second run (a[base1] > a[base2]), and the last element of the first run (a[base1 + len1-1]) must be greater * than all elements of the second run. * @@ -624,8 +578,7 @@ private static int gallopRight (T key, T[] a, int base, int len, int hint, C * @param base1 index of first element in first run to be merged * @param len1 length of first run to be merged (must be > 0) * @param base2 index of first element in second run to be merged (must be aBase + aLen) - * @param len2 length of second run to be merged (must be > 0) - */ + * @param len2 length of second run to be merged (must be > 0) */ private void mergeLo (int base1, int len1, int base2, int len2) { if (DEBUG) assert len1 > 0 && len2 > 0 && base1 + len1 == base2; @@ -723,15 +676,13 @@ private void mergeLo (int base1, int len1, int base2, int len2) { } } - /** - * Like mergeLo, except that this method should be called only if len1 >= len2; mergeLo should be called if len1 <= len2. + /** Like mergeLo, except that this method should be called only if len1 >= len2; mergeLo should be called if len1 <= len2. * (Either method may be called if len1 == len2.) * * @param base1 index of first element in first run to be merged * @param len1 length of first run to be merged (must be > 0) * @param base2 index of first element in second run to be merged (must be aBase + aLen) - * @param len2 length of second run to be merged (must be > 0) - */ + * @param len2 length of second run to be merged (must be > 0) */ private void mergeHi (int base1, int len1, int base2, int len2) { if (DEBUG) assert len1 > 0 && len2 > 0 && base1 + len1 == base2; @@ -833,13 +784,11 @@ private void mergeHi (int base1, int len1, int base2, int len2) { } } - /** - * Ensures that the external array tmp has at least the specified number of elements, increasing its size if necessary. The + /** Ensures that the external array tmp has at least the specified number of elements, increasing its size if necessary. The * size increases exponentially to ensure amortized linear time complexity. * * @param minCapacity the minimum required capacity of the tmp array - * @return tmp, whether or not it grew - */ + * @return tmp, whether or not it grew */ private T[] ensureCapacity (int minCapacity) { if (tmp.length < minCapacity) { // Compute smallest power of 2 > minCapacity @@ -862,15 +811,13 @@ private T[] ensureCapacity (int minCapacity) { return tmp; } - /** - * Checks that fromIndex and toIndex are in range, and throws an appropriate exception if they aren't. + /** Checks that fromIndex and toIndex are in range, and throws an appropriate exception if they aren't. * * @param arrayLen the length of the array * @param fromIndex the index of the first element of the range * @param toIndex the index after the last element of the range * @throws IllegalArgumentException if fromIndex > toIndex - * @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > arrayLen - */ + * @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > arrayLen */ private static void rangeCheck (int arrayLen, int fromIndex, int toIndex) { if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); if (fromIndex < 0) throw new ArrayIndexOutOfBoundsException(fromIndex); diff --git a/gdx/src/com/badlogic/gdx/utils/XmlWriter.java b/gdx/src/com/badlogic/gdx/utils/XmlWriter.java index e32209ef924..bf61eb1e480 100644 --- a/gdx/src/com/badlogic/gdx/utils/XmlWriter.java +++ b/gdx/src/com/badlogic/gdx/utils/XmlWriter.java @@ -119,9 +119,7 @@ public XmlWriter pop () throws IOException { return this; } - /** - * Calls {@link #pop()} for each remaining open element, if any, and closes the stream. - */ + /** Calls {@link #pop()} for each remaining open element, if any, and closes the stream. */ public void close () throws IOException { while (!stack.isEmpty()) pop(); diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/AndroidTestStarter.java b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/AndroidTestStarter.java index 98576fb49ba..daf60785b5e 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/AndroidTestStarter.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/AndroidTestStarter.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.android; import java.util.ArrayList; @@ -28,13 +29,14 @@ public class AndroidTestStarter extends ListActivity { - @Override public void onCreate (Bundle savedInstanceState) { + @Override + public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayList testNames = new ArrayList(); - for(String name: GdxTests.getNames()) { + for (String name : GdxTests.getNames()) { testNames.add(name); - } - testNames.add(MatrixTest.class.getSimpleName()); + } + testNames.add(MatrixTest.class.getSimpleName()); setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, testNames.toArray(new String[0]))); } diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/GdxTestActivity.java b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/GdxTestActivity.java index 252c26e4ead..18b83f32c49 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/GdxTestActivity.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/GdxTestActivity.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.android; import android.os.Bundle; diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MatrixTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MatrixTest.java index 92931f3d01e..c783995e175 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MatrixTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MatrixTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.android; import javax.microedition.khronos.opengles.GL10; @@ -27,18 +28,20 @@ public class MatrixTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - + BitmapFont font; SpriteBatch batch; String results = "no results"; - - @Override public void create() { + + @Override + public void create () { font = new BitmapFont(); batch = new SpriteBatch(); - + Matrix4 m1 = new Matrix4(); Matrix4 m2 = new Matrix4(); float[] a1 = new float[16]; @@ -46,34 +49,35 @@ public class MatrixTest extends GdxTest { float[] a3 = new float[16]; Matrix.setIdentityM(a1, 0); Matrix.setIdentityM(a2, 0); - Matrix.setIdentityM(a3, 0); - + Matrix.setIdentityM(a3, 0); + long startTime = System.nanoTime(); int ops = 0; - while(System.nanoTime() - startTime < 5000000000l) { + while (System.nanoTime() - startTime < 5000000000l) { Matrix.multiplyMM(a1, 0, a2, 0, a3, 0); ops++; } results = "Matrix ops: " + ops + "\n"; - + // warm up startTime = System.nanoTime(); ops = 0; - while(System.nanoTime() - startTime < 2000000000l) { + while (System.nanoTime() - startTime < 2000000000l) { m1.mul(m2); ops++; - } - + } + startTime = System.nanoTime(); ops = 0; - while(System.nanoTime() - startTime < 5000000000l) { + while (System.nanoTime() - startTime < 5000000000l) { m1.mul(m2); ops++; } results += "Matrix4 ops: " + ops + "\n"; } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.drawMultiLine(batch, results, 20, 300); diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MicroBenchmarks.java b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MicroBenchmarks.java index 7cfd13f840a..a6cb5e78bd8 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MicroBenchmarks.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/MicroBenchmarks.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.android; import java.nio.ByteBuffer; @@ -35,7 +36,8 @@ public class MicroBenchmarks extends Activity { TextView tv; Thread testThread = new Thread(new Runnable() { - @Override public void run () { + @Override + public void run () { ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * Float.SIZE / 8); buffer.order(ByteOrder.nativeOrder()); FloatBuffer floatBuffer = buffer.asFloatBuffer(); @@ -111,7 +113,8 @@ void toc (final String info) { tv.post(new Runnable() { - @Override public void run () { + @Override + public void run () { StringBuilder buff = new StringBuilder(tv.getText()); buff.append(info).append(", ").append(time).append(" secs\n"); tv.setText(buff.toString()); diff --git a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/WindowedTest.java b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/WindowedTest.java index 59482e84dcd..5517d3ae3c4 100644 --- a/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/WindowedTest.java +++ b/tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/WindowedTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.android; import javax.microedition.khronos.opengles.GL10; @@ -55,7 +56,8 @@ public void onCreate (Bundle bundle) { b1.setOnClickListener(new OnClickListener() { - @Override public void onClick (View arg0) { + @Override + public void onClick (View arg0) { color.set((float)Math.random(), (float)Math.random(), (float)Math.random(), 1); } @@ -63,7 +65,8 @@ public void onCreate (Bundle bundle) { b2.setOnClickListener(new OnClickListener() { - @Override public void onClick (View v) { + @Override + public void onClick (View v) { Intent intent = new Intent(WindowedTest.this, WindowedTest.class); WindowedTest.this.startActivity(intent); } @@ -74,29 +77,36 @@ public void onPause () { super.onPause(); } - @Override public void onDestroy () { + @Override + public void onDestroy () { super.onDestroy(); Log.w("WindowedTest", "destroying"); } - @Override public void create () { + @Override + public void create () { } - @Override public void render () { + @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 () { } - @Override public void pause () { + @Override + public void pause () { } - @Override public void resume () { + @Override + public void resume () { } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } } diff --git a/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleDebugStarter.java b/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleDebugStarter.java index 4975969bdba..a4580f615a5 100644 --- a/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleDebugStarter.java +++ b/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleDebugStarter.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.angle; import com.badlogic.gdx.backends.angle.AngleApplication; diff --git a/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleTestStarter.java b/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleTestStarter.java index d212b02c201..c507a3575b3 100644 --- a/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleTestStarter.java +++ b/tests/gdx-tests-angle/src/com/badlogic/gdx/tests/angle/AngleTestStarter.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.angle; import java.awt.BorderLayout; @@ -44,8 +45,7 @@ public TestList () { for (String name : GdxTests.getNames()) { GdxTest test = GdxTests.newTest(name); - if (test != null && (test.needsGL20()|| - name.contains("InputTest"))) { + if (test != null && (test.needsGL20() || name.contains("InputTest"))) { tests.add(name); } } @@ -66,7 +66,8 @@ public void mouseClicked (MouseEvent event) { }); button.addActionListener(new ActionListener() { - @Override public void actionPerformed (ActionEvent e) { + @Override + public void actionPerformed (ActionEvent e) { String testName = (String)list.getSelectedValue(); GdxTest test = GdxTests.newTest(testName); new AngleApplication(test, testName, 480, 320, false); diff --git a/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglDebugStarter.java b/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglDebugStarter.java index 3c5c1835749..a893355ca9c 100644 --- a/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglDebugStarter.java +++ b/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglDebugStarter.java @@ -13,17 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.tests.jogl; -import org.lwjgl.opengl.DisplayMode; +package com.badlogic.gdx.tests.jogl; import com.badlogic.gdx.backends.jogl.JoglApplication; import com.badlogic.gdx.backends.jogl.JoglApplicationConfiguration; public class JoglDebugStarter { - public static void main (String[] argv) { - JoglApplicationConfiguration config = new JoglApplicationConfiguration(); + public static void main (String[] argv) { + JoglApplicationConfiguration config = new JoglApplicationConfiguration(); config.useGL20 = true; new JoglApplication(new com.badlogic.gdx.tests.ProjectiveTextureTest(), config); } diff --git a/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglTestStarter.java b/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglTestStarter.java index aeeee8a8cae..27b4c86b7f9 100644 --- a/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglTestStarter.java +++ b/tests/gdx-tests-jogl/src/com/badlogic/gdx/tests/jogl/JoglTestStarter.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.jogl; import java.awt.BorderLayout; @@ -54,7 +55,8 @@ public void mouseClicked (MouseEvent event) { }); button.addActionListener(new ActionListener() { - @Override public void actionPerformed (ActionEvent e) { + @Override + public void actionPerformed (ActionEvent e) { String testName = (String)list.getSelectedValue(); GdxTest test = GdxTests.newTest(testName); new JoglApplication(test, testName, 480, 320, test.needsGL20()); diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LocalLwjglTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LocalLwjglTest.java index f95b403f239..7196449e0e8 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LocalLwjglTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LocalLwjglTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests.lwjgl; import com.badlogic.gdx.ApplicationListener; @@ -8,58 +9,58 @@ import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; -public class LocalLwjglTest implements ApplicationListener -{ - private Mesh mesh; +public class LocalLwjglTest implements ApplicationListener { + private Mesh mesh; + + @Override + public void create () { + float[] vertices = new float[] {0, 0, 0, // point 0 (invisible) + -0.5f, -0.5f, 0, // point 1 + 0.5f, -0.5f, 0, // point 2 + 0, 0.5f, 0}; // point 3 + + if (mesh == null) { + mesh = new Mesh(true, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position")); + mesh.setVertices(vertices, 3, 3 * 3); // Heres the problem, the offset does NOT work as expected + mesh.setIndices(new short[] {0, 1, 2}); + +// Get the vertices again and see whats in them + float[] testv = new float[12]; + mesh.getVertices(testv); + + int i = 0; + while (i < testv.length) { + System.out.print(i + ":" + testv[i++]); + System.out.print(" " + i + ":" + testv[i++]); + System.out.print(" " + i + ":" + testv[i++] + "\n"); + } + } + } - @Override - public void create() - { - float[] vertices = new float[] { 0, 0, 0, //point 0 (invisible) - -0.5f, -0.5f, 0, //point 1 - 0.5f, -0.5f, 0, //point 2 - 0, 0.5f, 0}; //point 3 - - if (mesh == null) - { - mesh = new Mesh(true, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position")); - mesh.setVertices(vertices,3,3*3); //Heres the problem, the offset does NOT work as expected - mesh.setIndices(new short[] { 0, 1, 2 }); - -// Get the vertices again and see whats in them - float[] testv = new float[12]; - mesh.getVertices(testv); - - int i = 0; - while(i < testv.length) - { - System.out.print(i+":"+testv[i++]); - System.out.print(" "+i+":"+testv[i++]); - System.out.print(" "+i+":"+testv[i++]+"\n"); - } - } - } + @Override + public void dispose () { + } - @Override - public void dispose() { } + @Override + public void pause () { + } - @Override - public void pause() { } + @Override + public void render () { + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + Gdx.gl10.glColor4f(1, 1, 1, 1); + mesh.render(GL10.GL_TRIANGLES); + } - @Override - public void render() { - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - Gdx.gl10.glColor4f(1, 1, 1, 1); - mesh.render(GL10.GL_TRIANGLES); - } + @Override + public void resize (int width, int height) { + } - @Override - public void resize(int width, int height) { } + @Override + public void resume () { + } - @Override - public void resume() { } - - public static void main(String[] argv) { - new LwjglApplication(new LocalLwjglTest(), "test", 480, 320, false); - } + public static void main (String[] argv) { + new LwjglApplication(new LocalLwjglTest(), "test", 480, 320, false); + } } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglAppletTest.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglAppletTest.java index 18777a8f2b4..e1bda1cb17e 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglAppletTest.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglAppletTest.java @@ -13,6 +13,7 @@ * 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.lwjgl.LwjglApplet; diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java index 7aa5fdc8676..d2b008de8bf 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java @@ -13,31 +13,17 @@ * 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.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; -import com.badlogic.gdx.tests.AssetManagerTest; -import com.badlogic.gdx.tests.BufferUtilsTest; -import com.badlogic.gdx.tests.DecalTest; -import com.badlogic.gdx.tests.ETC1Test; -import com.badlogic.gdx.tests.FilterPerformanceTest; -import com.badlogic.gdx.tests.InverseKinematicsTest; import com.badlogic.gdx.tests.IsoCamTest; -import com.badlogic.gdx.tests.MipMapTest; -import com.badlogic.gdx.tests.ObjTest; -import com.badlogic.gdx.tests.PickingTest; -import com.badlogic.gdx.tests.ProjectiveTextureTest; -import com.badlogic.gdx.tests.ShadowMappingTest; -import com.badlogic.gdx.tests.SimpleDecalTest; -import com.badlogic.gdx.tests.TextureDataTest; -import com.badlogic.gdx.tests.TransformationTest; -import com.badlogic.gdx.tests.UITest; public class LwjglDebugStarter { public static void main (String[] argv) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); - + config.useGL20 = true; new LwjglApplication(new IsoCamTest(), config); } diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglTestStarter.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglTestStarter.java index a7537980629..f0d2be45e7c 100644 --- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglTestStarter.java +++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglTestStarter.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.lwjgl; import java.awt.BorderLayout; @@ -66,7 +67,8 @@ public void keyPressed (KeyEvent e) { list.setSelectedValue(Preferences.systemNodeForPackage(GdxTests.class).get("last", null), true); button.addActionListener(new ActionListener() { - @Override public void actionPerformed (ActionEvent e) { + @Override + public void actionPerformed (ActionEvent e) { String testName = (String)list.getSelectedValue(); GdxTest test = GdxTests.newTest(testName); new LwjglApplication(test, testName, 480, 320, test.needsGL20()); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/AccelerometerTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/AccelerometerTest.java index b11888644fc..852c2935224 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AccelerometerTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AccelerometerTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -7,25 +8,27 @@ import com.badlogic.gdx.tests.utils.GdxTest; public class AccelerometerTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } BitmapFont font; SpriteBatch batch; - - @Override public void create() { + + @Override + public void create () { font = new BitmapFont(); batch = new SpriteBatch(); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); - font.drawMultiLine(batch, "accel: [" + Gdx.input.getAccelerometerX() + "," + Gdx.input.getAccelerometerY() + "," + Gdx.input.getAccelerometerZ() + "]\n" + - "orientation: " + Gdx.input.getNativeOrientation() + "\n" + - "rotation: " + Gdx.input.getRotation() + "\n" + - "wh: " + Gdx.graphics.getDesktopDisplayMode() + "\n", 0, 100); + font.drawMultiLine(batch, "accel: [" + Gdx.input.getAccelerometerX() + "," + Gdx.input.getAccelerometerY() + "," + + Gdx.input.getAccelerometerZ() + "]\n" + "orientation: " + Gdx.input.getNativeOrientation() + "\n" + "rotation: " + + Gdx.input.getRotation() + "\n" + "wh: " + Gdx.graphics.getDesktopDisplayMode() + "\n", 0, 100); batch.end(); } -} \ No newline at end of file +} diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionSequenceTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionSequenceTest.java index f96561863d4..a14928a3f18 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionSequenceTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionSequenceTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -22,13 +23,8 @@ import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.OnActionCompleted; import com.badlogic.gdx.scenes.scene2d.Stage; -import com.badlogic.gdx.scenes.scene2d.actions.Delay; -import com.badlogic.gdx.scenes.scene2d.actions.FadeIn; -import com.badlogic.gdx.scenes.scene2d.actions.FadeOut; import com.badlogic.gdx.scenes.scene2d.actions.MoveBy; import com.badlogic.gdx.scenes.scene2d.actions.Parallel; -import com.badlogic.gdx.scenes.scene2d.actions.RotateBy; -import com.badlogic.gdx.scenes.scene2d.actions.ScaleTo; import com.badlogic.gdx.scenes.scene2d.actions.Sequence; import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.tests.utils.GdxTest; @@ -36,7 +32,7 @@ public class ActionSequenceTest extends GdxTest implements OnActionCompleted { @Override - public boolean needsGL20() { + public boolean needsGL20 () { return false; } @@ -46,50 +42,47 @@ public boolean needsGL20() { Stage stage; @Override - public void create() { + public void create () { stage = new Stage(480, 320, true); - Texture texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), - false); + Texture texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), false); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); img = new Image("actor", texture); img.width = img.height = 100; img.originX = 50; img.originY = 50; img.x = img.y = 100; - + img2 = new Image("actor2", texture); img2.width = img2.height = 100; img2.originX = 50; img2.originY = 50; img2.x = img2.y = 100; - - + img3 = new Image("actor3", texture); img3.width = img3.height = 100; img3.originX = 50; img3.originY = 50; img3.x = img3.y = 100; - stage.addActor(img); stage.addActor(img2); stage.addActor(img3); } @Override - public void render() { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + img.action(Sequence.$()); img2.action(Parallel.$(Sequence.$(), MoveBy.$(0, 0, 1))); img3.action(Sequence.$(Parallel.$(MoveBy.$(0, 0, 2)))); - + stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f)); stage.draw(); } @Override - public void completed(Action action) { + public void completed (Action action) { System.out.println("completed"); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionTest.java index ff16994a394..4a073ca6d2f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ActionTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -22,29 +23,22 @@ import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.OnActionCompleted; import com.badlogic.gdx.scenes.scene2d.Stage; -import com.badlogic.gdx.scenes.scene2d.actions.FadeTo; -import com.badlogic.gdx.scenes.scene2d.actions.Parallel; -import com.badlogic.gdx.scenes.scene2d.actions.Remove; -import com.badlogic.gdx.scenes.scene2d.actions.RotateBy; -import com.badlogic.gdx.scenes.scene2d.actions.ScaleTo; -import com.badlogic.gdx.scenes.scene2d.actions.Sequence; import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.tests.utils.GdxTest; public class ActionTest extends GdxTest implements OnActionCompleted { @Override - public boolean needsGL20() { + public boolean needsGL20 () { return false; } Stage stage; @Override - public void create() { + public void create () { stage = new Stage(480, 320, true); - Texture texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), - false); + Texture texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), false); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); final Image img = new Image("actor", texture); img.width = img.height = 100; @@ -56,88 +50,87 @@ public void create() { // img.action(Forever.$(Parallel.$(RotateTo.$(1, 1)))); // img.action(Delay.$(RotateBy.$(45, 2), // 1).setCompletionListener(this)); -// Action actionMoveBy = MoveBy.$(30, 0, 0.5f).setCompletionListener( -// new OnActionCompleted() { +// Action actionMoveBy = MoveBy.$(30, 0, 0.5f).setCompletionListener( +// new OnActionCompleted() { +// +// @Override +// public void completed(Action action) { +// System.out.println("move by complete"); +// } +// }); // -// @Override -// public void completed(Action action) { -// System.out.println("move by complete"); -// } -// }); +// Action actionDelay = Delay.$(actionMoveBy, 1).setCompletionListener( +// new OnActionCompleted() { // -// Action actionDelay = Delay.$(actionMoveBy, 1).setCompletionListener( -// new OnActionCompleted() { +// @Override +// public void completed(Action action) { +// System.out.println("delay complete"); +// } +// }); +// +// img.action(actionDelay); + +// img.action(Repeat.$(Sequence.$(MoveBy.$(50, 0, 1), MoveBy.$(0, 50, 1), MoveBy.$(-50, 0, 1), MoveBy.$(0, -50, 1)), 3)); +// img.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))); +// OnActionCompleted listener = new OnActionCompleted() { +// @Override public void completed (Action action) { +// img.action(Parallel.$(Sequence.$(FadeOut.$(2), FadeIn.$(2)), +// Sequence.$(ScaleTo.$(0.1f, 0.1f, 1.5f), ScaleTo.$(1.0f, 1.0f, 1.5f))).setCompletionListener(this)); +// } +// }; // -// @Override -// public void completed(Action action) { -// System.out.println("delay complete"); -// } -// }); +// img.action(Parallel.$(Sequence.$(FadeOut.$(2), FadeIn.$(2)), +// Sequence.$(ScaleTo.$(0.1f, 0.1f, 1.5f), ScaleTo.$(1.0f, 1.0f, 1.5f))).setCompletionListener(listener)); + +// img.action( +// Sequence.$( +// Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.4f, 1.4f, 2), FadeTo.$(0.7f, 2)), +// Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.0f, 1.0f, 2), FadeTo.$(1.0f, 2)), +// Remove.$() +// ) +// ); +// +// Action action = Repeat.$(Sequence.$( +// MoveBy.$(8, 0, 0.5f), +// MoveBy.$(0, 8, 0.5f), +// MoveBy.$(-8, 0, 0.5f), +// MoveBy.$(0, -8, 0.5f)), 20); +// Action action2 = action.copy(); +// img.action(action2); + +// float scale = 1; +// float showDuration = 1; +// ScaleTo scaleCountdown = ScaleTo.$(scale * 1.0f, scale * 1.0f, 1.0f); +// scaleCountdown.setInterpolator(DecelerateInterpolator.$(3.0f)); +// Parallel parallel = Parallel.$(scaleCountdown); +// // Sequence.$(FadeIn.$(0.25f), Delay.$(FadeOut.$(0.25f), 0.5f))); +// Sequence cdAnim = Sequence.$(Delay.$(parallel, showDuration), Remove.$()); +// cdAnim.setCompletionListener(this); +// img.action(cdAnim); // -// img.action(actionDelay); +// Delay delay = Delay.$(MoveBy.$(100, 100, 1).setCompletionListener(this), 1); +// delay.setCompletionListener(this); +// img.action(Sequence.$(delay).setCompletionListener(this)); -// img.action(Repeat.$(Sequence.$(MoveBy.$(50, 0, 1), MoveBy.$(0, 50, 1), MoveBy.$(-50, 0, 1), MoveBy.$(0, -50, 1)), 3)); -// img.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))); -// OnActionCompleted listener = new OnActionCompleted() { -// @Override public void completed (Action action) { -// img.action(Parallel.$(Sequence.$(FadeOut.$(2), FadeIn.$(2)), -// Sequence.$(ScaleTo.$(0.1f, 0.1f, 1.5f), ScaleTo.$(1.0f, 1.0f, 1.5f))).setCompletionListener(this)); -// } -// }; -// -// img.action(Parallel.$(Sequence.$(FadeOut.$(2), FadeIn.$(2)), -// Sequence.$(ScaleTo.$(0.1f, 0.1f, 1.5f), ScaleTo.$(1.0f, 1.0f, 1.5f))).setCompletionListener(listener)); - -// img.action( -// Sequence.$( -// Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.4f, 1.4f, 2), FadeTo.$(0.7f, 2)), -// Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.0f, 1.0f, 2), FadeTo.$(1.0f, 2)), -// Remove.$() -// ) -// ); -// -// Action action = Repeat.$(Sequence.$( -// MoveBy.$(8, 0, 0.5f), -// MoveBy.$(0, 8, 0.5f), -// MoveBy.$(-8, 0, 0.5f), -// MoveBy.$(0, -8, 0.5f)), 20); -// Action action2 = action.copy(); -// img.action(action2); - - -// float scale = 1; -// float showDuration = 1; -// ScaleTo scaleCountdown = ScaleTo.$(scale * 1.0f, scale * 1.0f, 1.0f); -// scaleCountdown.setInterpolator(DecelerateInterpolator.$(3.0f)); -// Parallel parallel = Parallel.$(scaleCountdown); -// // Sequence.$(FadeIn.$(0.25f), Delay.$(FadeOut.$(0.25f), 0.5f))); -// Sequence cdAnim = Sequence.$(Delay.$(parallel, showDuration), Remove.$()); -// cdAnim.setCompletionListener(this); -// img.action(cdAnim); -// -// Delay delay = Delay.$(MoveBy.$(100, 100, 1).setCompletionListener(this), 1); -// delay.setCompletionListener(this); -// img.action(Sequence.$(delay).setCompletionListener(this)); - stage.addActor(img); } @Override - public void render() { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f)); stage.draw(); } @Override - public void completed(Action action) { + public void completed (Action action) { System.out.println("completed Action: " + action); } } 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 2bbd86725b0..338ad68f75d 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AlphaTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AlphaTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -21,7 +22,6 @@ 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.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; @@ -29,18 +29,20 @@ public class AlphaTest extends GdxTest { SpriteBatch batch; Texture texture; - @Override public void create () { + @Override + public void create () { Pixmap pixmap = new Pixmap(256, 256, Format.RGBA8888); pixmap.setColor(0, 1, 0, 0.7f); pixmap.fill(); texture = new Texture(pixmap, false); - texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); + texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); batch = new SpriteBatch(); pixmap.dispose(); } - @Override public void render () { + @Override + public void render () { Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); @@ -48,7 +50,8 @@ public class AlphaTest extends GdxTest { batch.end(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/AnimationTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/AnimationTest.java index 46a02681fd6..1b26dd07ce0 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AnimationTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AnimationTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -27,74 +28,75 @@ public class AnimationTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - + class Caveman { static final float VELOCITY = 20; public final Vector2 pos; public final boolean headsLeft; public float stateTime; - - public Caveman(float x, float y, boolean headsLeft) { + + public Caveman (float x, float y, boolean headsLeft) { pos = new Vector2().set(x, y); this.headsLeft = headsLeft; this.stateTime = (float)Math.random(); - } - - public void update(float deltaTime) { + } + + public void update (float deltaTime) { stateTime += deltaTime; - pos.x = pos.x + (headsLeft?-VELOCITY*deltaTime:VELOCITY*deltaTime); - if(pos.x < -64) pos.x = Gdx.graphics.getWidth(); - if(pos.x > Gdx.graphics.getWidth() + 64) pos.x = -64; + pos.x = pos.x + (headsLeft ? -VELOCITY * deltaTime : VELOCITY * deltaTime); + if (pos.x < -64) pos.x = Gdx.graphics.getWidth(); + if (pos.x > Gdx.graphics.getWidth() + 64) pos.x = -64; } } - + Animation leftWalk; Animation rightWalk; Caveman[] cavemen; SpriteBatch batch; FPSLogger fpsLog; - @Override public void create () { + @Override + public void create () { Texture texture = new Texture(Gdx.files.internal("data/walkanim.png")); TextureRegion[] leftWalkFrames = TextureRegion.split(texture, 64, 64)[0]; TextureRegion[] rightWalkFrames = new TextureRegion[leftWalkFrames.length]; - for(int i = 0; i < rightWalkFrames.length; i++) { + for (int i = 0; i < rightWalkFrames.length; i++) { TextureRegion frame = new TextureRegion(leftWalkFrames[i]); frame.flip(true, false); rightWalkFrames[i] = frame; } leftWalk = new Animation(0.25f, leftWalkFrames); rightWalk = new Animation(0.25f, rightWalkFrames); - + cavemen = new Caveman[100]; - for(int i = 0; i < 100; i++) { + for (int i = 0; i < 100; i++) { cavemen[i] = new Caveman((float)Math.random() * Gdx.graphics.getWidth(), - (float)Math.random() * Gdx.graphics.getHeight(), - Math.random() > 0.5?true:false); + (float)Math.random() * Gdx.graphics.getHeight(), Math.random() > 0.5 ? true : false); } batch = new SpriteBatch(); fpsLog = new FPSLogger(); } - @Override public void render () { + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); batch.begin(); - for(int i = 0; i < cavemen.length; i++) { + for (int i = 0; i < cavemen.length; i++) { Caveman caveman = cavemen[i]; - TextureRegion frame = caveman.headsLeft? - leftWalk.getKeyFrame(caveman.stateTime, true): - rightWalk.getKeyFrame(caveman.stateTime, true); - batch.draw(frame, caveman.pos.x, caveman.pos.y); + TextureRegion frame = caveman.headsLeft ? leftWalk.getKeyFrame(caveman.stateTime, true) : rightWalk.getKeyFrame( + caveman.stateTime, true); + batch.draw(frame, caveman.pos.x, caveman.pos.y); } batch.end(); - - for(int i = 0; i < cavemen.length; i++) { + + for (int i = 0; i < cavemen.length; i++) { cavemen[i].update(Gdx.graphics.getDeltaTime()); } - + fpsLog.log(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/AssetManagerTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/AssetManagerTest.java index c8ee1f62cea..43025f1fe4a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AssetManagerTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AssetManagerTest.java @@ -1,13 +1,11 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetErrorListener; import com.badlogic.gdx.assets.AssetManager; -import com.badlogic.gdx.audio.Music; -import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL10; -import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; @@ -24,29 +22,30 @@ public boolean needsGL20 () { BitmapFont font; SpriteBatch batch; int frame = 0; - - public void create() { + + public void create () { Gdx.app.setLogLevel(Application.LOG_ERROR); manager = new AssetManager(); manager.setErrorListener(this); -// manager.preload("data/animation.png", Texture.class); -// manager.preload("data/badlogic.jpg", Texture.class); -// manager.preload("data/cloudconnected.ogg", Music.class); -// manager.preload("data/shotgun.wav", Sound.class); +// manager.preload("data/animation.png", Texture.class); +// manager.preload("data/badlogic.jpg", Texture.class); +// manager.preload("data/cloudconnected.ogg", Music.class); +// manager.preload("data/shotgun.wav", Sound.class); manager.preload("data/pack1.png", Texture.class); manager.preload("data/pack", TextureAtlas.class); manager.preload("data/verdana39.png", Texture.class); manager.preload("data/verdana39.fnt", BitmapFont.class); Texture.setAssetManager(manager); batch = new SpriteBatch(); - - font = new BitmapFont(Gdx.files.internal("data/font.fnt"), false); + + font = new BitmapFont(Gdx.files.internal("data/font.fnt"), false); } - + boolean diagnosed = false; - public void render() { + + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - if(manager.update() & !diagnosed) { + if (manager.update() & !diagnosed) { Gdx.app.log("AssetManagerTest", "\n" + manager.getDiagonistics()); diagnosed = true; manager.remove("data/pack"); @@ -54,13 +53,16 @@ public void render() { Gdx.app.log("AssetManagerTest", "after disposal\n" + manager.getDiagonistics()); } frame++; -// if(manager.getQueuedAssets() > 0) Gdx.app.log("AssetManagerTest", "frames: " + frame + ", loaded: " + manager.getLoadedAssets() + ", queued: " + manager.getQueuedAssets()); - +// if(manager.getQueuedAssets() > 0) Gdx.app.log("AssetManagerTest", "frames: " + frame + ", loaded: " + manager.getLoadedAssets() +// + ", queued: " + manager.getQueuedAssets()); + batch.begin(); - if(manager.isLoaded("data/animation.png")) batch.draw(manager.get("data/animation.png", Texture.class), 100, 100); - if(manager.isLoaded("data/badlogic.jpg")) batch.draw(manager.get("data/badlogic.jpg", Texture.class), 200, 100); - if(manager.isLoaded("data/pack")) batch.draw(manager.get("data/pack", TextureAtlas.class).findRegion("particle-star"), 164, 100); - if(manager.isLoaded("data/verdana39.fnt")) manager.get("data/verdana39.fnt", BitmapFont.class).draw(batch, "This is a test", 100, 200); + if (manager.isLoaded("data/animation.png")) batch.draw(manager.get("data/animation.png", Texture.class), 100, 100); + if (manager.isLoaded("data/badlogic.jpg")) batch.draw(manager.get("data/badlogic.jpg", Texture.class), 200, 100); + if (manager.isLoaded("data/pack")) + batch.draw(manager.get("data/pack", TextureAtlas.class).findRegion("particle-star"), 164, 100); + if (manager.isLoaded("data/verdana39.fnt")) + manager.get("data/verdana39.fnt", BitmapFont.class).draw(batch, "This is a test", 100, 200); font.draw(batch, "loaded: " + manager.getProgress(), 0, 30); batch.end(); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/AtlasIssueTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/AtlasIssueTest.java index 30f621eb9ce..43c808fca25 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AtlasIssueTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AtlasIssueTest.java @@ -13,16 +13,15 @@ * 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.Files.FileType; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; -import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.tests.utils.GdxTest; @@ -36,7 +35,7 @@ public void create () { batch = new SpriteBatch(); batch.setProjectionMatrix(new Matrix4().setToOrtho2D(0, 0, 855, 480)); atlas = new TextureAtlas(Gdx.files.internal("data/issue_pack"), Gdx.files.internal("data/")); - sprite = atlas.createSprite("map"); + sprite = atlas.createSprite("map"); font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); Gdx.gl.glClearColor(0, 1, 0, 1); } @@ -45,7 +44,7 @@ public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); sprite.draw(batch); - font.draw(batch, "fps:"+Gdx.graphics.getFramesPerSecond(), 26, 65); + font.draw(batch, "fps:" + Gdx.graphics.getFramesPerSecond(), 26, 65); batch.end(); } 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 b075bf58af1..e8ac1ea5f19 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioDeviceTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioDeviceTest.java @@ -13,6 +13,7 @@ * 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,11 +24,13 @@ public class AudioDeviceTest extends GdxTest { Thread thread; boolean stop = false; - @Override public void create () { + @Override + public void create () { if (thread == null) { final AudioDevice device = Gdx.app.getAudio().newAudioDevice(44100, false); thread = new Thread(new Runnable() { - @Override public void run () { + @Override + public void run () { final float frequency = 440; float increment = (float)(2 * Math.PI) * frequency / 44100; // angular increment for each sample float angle = 0; @@ -50,7 +53,8 @@ public class AudioDeviceTest extends GdxTest { } } - @Override public void dispose () { + @Override + public void dispose () { stop = true; try { thread.join(); @@ -59,7 +63,8 @@ public class AudioDeviceTest extends GdxTest { } } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } 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 5588caef218..51e0f93de8a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioRecorderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/AudioRecorderTest.java @@ -13,6 +13,7 @@ * 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,14 +29,16 @@ public class AudioRecorderTest extends GdxTest { AudioRecorder recorder; ImmediateModeRenderer10 renderer; - @Override public void create () { + @Override + public void create () { device = Gdx.audio.newAudioDevice(44100, true); recorder = Gdx.audio.newAudioRecoder(44100, true); renderer = new ImmediateModeRenderer10(); Thread t = new Thread(new Runnable() { - @Override public void run () { + @Override + public void run () { while (true) { recorder.read(samples, 0, samples.length); device.writeSamples(samples, 0, samples.length); @@ -46,7 +49,8 @@ public class AudioRecorderTest extends GdxTest { t.start(); } - @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); @@ -59,17 +63,20 @@ public class AudioRecorderTest extends GdxTest { // renderer.end(); } - @Override public void pause () { + @Override + public void pause () { device.dispose(); recorder.dispose(); } - @Override public void resume () { + @Override + public void resume () { device = Gdx.audio.newAudioDevice(44100, true); recorder = Gdx.audio.newAudioRecoder(44100, true); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontAlignmentTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontAlignmentTest.java index 85ac029a75b..bfe81c667c6 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontAlignmentTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontAlignmentTest.java @@ -13,6 +13,7 @@ * 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; @@ -27,9 +28,7 @@ import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; -/** - * Shows how to align single line, wrapped, and multi line text within a rectangle. - */ +/** Shows how to align single line, wrapped, and multi line text within a rectangle. */ public class BitmapFontAlignmentTest extends GdxTest { private SpriteBatch spriteBatch; private BitmapFont font; @@ -37,7 +36,8 @@ public class BitmapFontAlignmentTest extends GdxTest { private Sprite logoSprite; int renderMode; - @Override public void create () { + @Override + public void create () { Gdx.input.setInputProcessor(new InputAdapter() { public boolean touchDown (int x, int y, int pointer, int newParam) { renderMode = (renderMode + 1) % 6; @@ -47,7 +47,7 @@ public boolean touchDown (int x, int y, int pointer, int newParam) { spriteBatch = new SpriteBatch(); - logoSprite = new Sprite(new Texture(Gdx.files.internal("data/badlogic.jpg"), false)); + logoSprite = new Sprite(new Texture(Gdx.files.internal("data/badlogic.jpg"), false)); logoSprite.setColor(1, 1, 1, 0.6f); logoSprite.setBounds(50, 100, 400, 100); @@ -56,7 +56,8 @@ public boolean touchDown (int x, int y, int pointer, int newParam) { cache = new BitmapFontCache(font); } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); spriteBatch.begin(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontFlipTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontFlipTest.java index 6ef833db6b8..da209164eaf 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontFlipTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontFlipTest.java @@ -13,21 +13,19 @@ * 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.InputAdapter; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; 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.g2d.BitmapFont; +import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; -import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.tests.utils.GdxTest; @@ -40,7 +38,8 @@ public class BitmapFontFlipTest extends GdxTest { private BitmapFontCache cacheScaled1, cacheScaled2, cacheScaled3, cacheScaled4, cacheScaled5; int renderMode; - @Override public void create () { + @Override + public void create () { Gdx.input.setInputProcessor(new InputAdapter() { public boolean touchDown (int x, int y, int pointer, int newParam) { renderMode = (renderMode + 1) % 4; @@ -56,7 +55,7 @@ public boolean touchDown (int x, int y, int pointer, int newParam) { logoSprite.setPosition(0, 320 - 256); logoSprite.setColor(1, 1, 1, 0.5f); - font = new BitmapFont(Gdx.files.internal("data/verdana39.fnt"),Gdx.files.internal("data/verdana39.png"), true); + font = new BitmapFont(Gdx.files.internal("data/verdana39.fnt"), Gdx.files.internal("data/verdana39.png"), true); cache1 = new BitmapFontCache(font); cache2 = new BitmapFontCache(font); @@ -94,7 +93,8 @@ private void createCaches (String type, BitmapFontCache cache1, BitmapFontCache cache5.setWrappedText(text, 0, 320 - 300, 480, HAlignment.CENTER); } - @Override public void render () { + @Override + public void render () { red.a = (red.a + Gdx.graphics.getDeltaTime() * 0.1f) % 1; GL10 gl = Gdx.graphics.getGL10(); 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 50207aa9bb7..e84b607d5eb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/BitmapFontTest.java @@ -32,7 +32,8 @@ public class BitmapFontTest extends GdxTest { private BitmapFont font; ImmediateModeRenderer10 renderer; - @Override public void create () { + @Override + public void create () { spriteBatch = new SpriteBatch(); TextureAtlas textureAtlas = new TextureAtlas("data/main"); @@ -41,7 +42,8 @@ public class BitmapFontTest extends GdxTest { renderer = new ImmediateModeRenderer10(); } - @Override public void render () { + @Override + public void render () { // red.a = (red.a + Gdx.graphics.getDeltaTime() * 0.1f) % 1; int viewHeight = Gdx.graphics.getHeight(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/BobTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/BobTest.java index 8da29053c88..cb1204f7083 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/BobTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/BobTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -21,15 +22,14 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; 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.Usage; import com.badlogic.gdx.tests.utils.GdxTest; public class BobTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -53,7 +53,8 @@ public void create () { } } - @Override public void render () { + @Override + public void render () { float deltaTime = Math.min(Gdx.graphics.getDeltaTime(), 0.1f); for (int i = 0; i < NUM_BOBS; i++) { bobs[i].update(deltaTime); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DInitialOverlapTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DInitialOverlapTest.java index c2b71b78cfa..f3d5a554d9e 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DInitialOverlapTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DInitialOverlapTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.math.Vector2; @@ -50,7 +51,8 @@ Body makeBody () { return body; } - @Override public void create () { + @Override + public void create () { // World with no gravity world = new World(new Vector2(0, 0), true); @@ -60,21 +62,22 @@ Body makeBody () { b1 = makeBody(); b2 = makeBody(); - /************************************************* - * From my testing, this line seems to trigger the weird behavior. If I comment this line out (the setTransform call), then + /************************************************* From my testing, this line seems to trigger the weird behavior. If I comment this line out (the setTransform call), then * filtering seems to work, and I don't see the bug anymore. Keep in mind I am running on a Ubuntu 10.10 x86_64 box, so I - * don't know if all platforms will exhibit this behavior in the same way. - ************************************************/ + * don't know if all platforms will exhibit this behavior in the same way. ************************************************/ b1.setTransform(new Vector2(0.1f, 0f), 0); } - @Override public void dispose () { + @Override + public void dispose () { } - @Override public void pause () { + @Override + public void pause () { } - @Override public void render () { + @Override + public void render () { if (i < 30) { // don't bother continuing after 30 time steps... world.step(1.0f / 75.0f, 3, 3); System.out.println("b1 (" + b1.getWorldCenter().x + "," + b1.getWorldCenter().y + ")" + " b2 (" + b2.getWorldCenter().x @@ -83,13 +86,16 @@ Body makeBody () { } } - @Override public void resize (int arg0, int arg1) { + @Override + public void resize (int arg0, int arg1) { } - @Override public void resume () { + @Override + public void resume () { } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } 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 8064d6db7e2..3b370ded612 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.ArrayList; @@ -40,7 +41,6 @@ import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.Manifold; -import com.badlogic.gdx.physics.box2d.Manifold.ManifoldPoint; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.QueryCallback; import com.badlogic.gdx.physics.box2d.World; @@ -55,11 +55,11 @@ public class Box2DTest extends GdxTest implements InputProcessor { /** the immediate mode renderer to output our debug drawings **/ private ImmediateModeRenderer10 renderer; - + /** box2d debug renderer **/ private Box2DDebugRenderer debugRenderer; - /** a spritebatch and a font for text rendering and a Texture to draw our boxes**/ + /** a spritebatch and a font for text rendering and a Texture to draw our boxes **/ private SpriteBatch batch; private BitmapFont font; private TextureRegion textureRegion; @@ -79,7 +79,8 @@ public class Box2DTest extends GdxTest implements InputProcessor { /** a hit body **/ Body hitBody = null; - @Override public void create () { + @Override + public void create () { // 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 @@ -87,12 +88,12 @@ public class Box2DTest extends GdxTest implements InputProcessor { // 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(48,32); + camera = new OrthographicCamera(48, 32); camera.position.set(0, 16, 0); // next we setup the immediate mode renderer renderer = new ImmediateModeRenderer10(); - + // next we create the box2d debug renderer debugRenderer = new Box2DDebugRenderer(); @@ -140,39 +141,39 @@ private void createPhysicsWorld () { groundPoly.dispose(); createBoxes(); - + // You can savely ignore the rest of this method :) world.setContactListener(new ContactListener() { @Override - public void beginContact(Contact contact) { -// System.out.println("begin contact"); + public void beginContact (Contact contact) { +// System.out.println("begin contact"); } @Override - public void endContact(Contact contact) { -// System.out.println("end contact"); + public void endContact (Contact contact) { +// System.out.println("end contact"); } @Override - public void preSolve(Contact contact, Manifold oldManifold) { -// Manifold.ManifoldType type = oldManifold.getType(); -// Vector2 localPoint = oldManifold.getLocalPoint(); -// Vector2 localNormal = oldManifold.getLocalNormal(); -// int pointCount = oldManifold.getPointCount(); -// ManifoldPoint[] points = oldManifold.getPoints(); -// System.out.println("pre solve, " + type + -// ", point: " + localPoint + -// ", local normal: " + localNormal + -// ", #points: " + pointCount + -// ", [" + points[0] + ", " + points[1] + "]"); + public void preSolve (Contact contact, Manifold oldManifold) { +// Manifold.ManifoldType type = oldManifold.getType(); +// Vector2 localPoint = oldManifold.getLocalPoint(); +// Vector2 localNormal = oldManifold.getLocalNormal(); +// int pointCount = oldManifold.getPointCount(); +// ManifoldPoint[] points = oldManifold.getPoints(); +// System.out.println("pre solve, " + type + +// ", point: " + localPoint + +// ", local normal: " + localNormal + +// ", #points: " + pointCount + +// ", [" + points[0] + ", " + points[1] + "]"); } @Override - public void postSolve(Contact contact, ContactImpulse impulse) { -// float[] ni = impulse.getNormalImpulses(); -// float[] ti = impulse.getTangentImpulses(); -// System.out.println("post solve, normal impulses: " + ni[0] + ", " + ni[1] + ", tangent impulses: " + ti[0] + ", " + ti[1]); - } + public void postSolve (Contact contact, ContactImpulse impulse) { +// float[] ni = impulse.getNormalImpulses(); +// float[] ti = impulse.getTangentImpulses(); +// System.out.println("post solve, normal impulses: " + ni[0] + ", " + ni[1] + ", tangent impulses: " + ti[0] + ", " + ti[1]); + } }); } @@ -194,7 +195,7 @@ private void createBoxes () { boxBodyDef.position.x = -24 + (float)(Math.random() * 48); boxBodyDef.position.y = 10 + (float)(Math.random() * 100); Body boxBody = world.createBody(boxBodyDef); - + boxBody.createFixture(boxPoly, 1); // add the box to our list of boxes @@ -205,7 +206,8 @@ private void createBoxes () { 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 @@ -233,24 +235,23 @@ private void createBoxes () { for (int i = 0; i < boxes.size(); i++) { Body box = boxes.get(i); Vector2 position = box.getPosition(); // that's the box's center position - float angle = MathUtils.radiansToDegrees *box.getAngle(); // the rotation angle around the center - batch.draw(textureRegion, - position.x - 1, position.y - 1, // the bottom left corner of the box, unrotated - 1f, 1f, // the rotation center relative to the bottom left corner of the box - 2, 2, // the width and height of the box - 1, 1, // the scale on the x- and y-axis - angle); // the rotation angle + float angle = MathUtils.radiansToDegrees * box.getAngle(); // the rotation angle around the center + batch.draw(textureRegion, position.x - 1, position.y - 1, // the bottom left corner of the box, unrotated + 1f, 1f, // the rotation center relative to the bottom left corner of the box + 2, 2, // the width and height of the box + 1, 1, // the scale on the x- and y-axis + angle); // the rotation angle } batch.end(); - // next we use the debug renderer. Note that we - // simply apply the camera again and then call + // next we use the debug renderer. Note that we + // simply apply the camera again and then call // the renderer. the camera.apply() call is actually // not needed as the opengl matrices are already set - // by the spritebatch which in turn uses the camera matrices :) + // by the spritebatch which in turn uses the camera matrices :) camera.apply(Gdx.gl10); debugRenderer.render(world); - + // finally we render all contact points gl.glPointSize(4); renderer.begin(GL10.GL_POINTS); @@ -274,9 +275,9 @@ private void createBoxes () { gl.glPointSize(1); // finally we render the time it took to update the world - // for this we have to set the projection matrix again, so + // for this we have to set the projection matrix again, so // we work in pixel coordinates - batch.getProjectionMatrix().setToOrtho2D(0,0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.begin(); font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond() + " update time: " + updateTime, 0, 20); batch.end(); @@ -314,7 +315,8 @@ private void renderBox (GL10 gl, Body body, float halfWidth, float halfHeight) { /** we instantiate this vector and the callback here so we don't irritate the GC **/ Vector3 testPoint = new Vector3(); QueryCallback callback = new QueryCallback() { - @Override public boolean reportFixture (Fixture fixture) { + @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; @@ -329,11 +331,12 @@ private void renderBox (GL10 gl, Body body, float halfWidth, float halfHeight) { } }; - @Override public boolean touchDown (int x, int y, int pointer, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { // translate the mouse coordinates to world coordinates testPoint.set(x, y, 0); camera.unproject(testPoint); - + // ask the world which bodies are within the given // bounding box around the mouse pointer hitBody = null; @@ -364,18 +367,20 @@ private void renderBox (GL10 gl, Body body, float halfWidth, float halfHeight) { /** another temporary vector **/ Vector2 target = new Vector2(); - @Override public boolean touchDragged (int x, int y, int pointer) { + @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.unproject(testPoint.set(x, y,0)); + if (mouseJoint != null) { + camera.unproject(testPoint.set(x, y, 0)); mouseJoint.setTarget(target.set(testPoint.x, testPoint.y)); } return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { // if a mouse joint exists we simply destroy it if (mouseJoint != null) { world.destroyJoint(mouseJoint); @@ -384,11 +389,13 @@ private void renderBox (GL10 gl, Body body, float halfWidth, float halfHeight) { return false; } - @Override public void dispose () { + @Override + public void dispose () { world.dispose(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -397,23 +404,28 @@ private void renderBox (GL10 gl, Body body, float halfWidth, float halfHeight) { // MOVE ALONG // --------------------------------------------------------------- - @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 touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTestCollection.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTestCollection.java index 64bdf5b278c..a349584123a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTestCollection.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DTestCollection.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Application; @@ -47,11 +48,13 @@ public class Box2DTestCollection extends GdxTest implements InputProcessor { private Application app = null; - @Override public void render () { + @Override + public void render () { tests[testIndex].render(); } - @Override public void create () { + @Override + public void create () { if (this.app == null) { this.app = Gdx.app; Box2DTest test = tests[testIndex]; @@ -61,7 +64,8 @@ public class Box2DTestCollection extends GdxTest implements InputProcessor { Gdx.input.setInputProcessor(this); } - @Override public boolean keyDown (int keycode) { + @Override + public boolean keyDown (int keycode) { if (keycode == Keys.SPACE) { app.log("TestCollection", "disposing test '" + tests[testIndex].getClass().getName()); tests[testIndex].dispose(); @@ -77,40 +81,48 @@ public class Box2DTestCollection extends GdxTest implements InputProcessor { return false; } - @Override public boolean keyTyped (char character) { + @Override + public boolean keyTyped (char character) { tests[testIndex].keyTyped(character); return false; } - @Override public boolean keyUp (int keycode) { + @Override + public boolean keyUp (int keycode) { tests[testIndex].keyUp(keycode); return false; } - @Override public boolean touchDown (int x, int y, int pointer, int button) { + @Override + public boolean touchDown (int x, int y, int pointer, int button) { tests[testIndex].touchDown(x, y, pointer, button); return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { tests[testIndex].touchDragged(x, y, pointer); return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { tests[testIndex].touchUp(x, y, pointer, button); return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/BufferUtilsTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/BufferUtilsTest.java index 15885ac0a06..bc7173e47bb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/BufferUtilsTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/BufferUtilsTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import java.nio.ByteBuffer; @@ -15,15 +16,17 @@ public class BufferUtilsTest extends GdxTest { static final int NUM_MB = 5; - - @Override public boolean needsGL20 () { + + @Override + public boolean needsGL20 () { return false; } - - @Override public void create() { - ByteBuffer bytebuffer = BufferUtils.newDisposableByteBuffer(1000*1000); + + @Override + public void create () { + ByteBuffer bytebuffer = BufferUtils.newDisposableByteBuffer(1000 * 1000); BufferUtils.freeMemory(bytebuffer); - + ByteBuffer bb = BufferUtils.newByteBuffer(8); CharBuffer cb = BufferUtils.newCharBuffer(8); ShortBuffer sb = BufferUtils.newShortBuffer(8); @@ -31,68 +34,68 @@ public class BufferUtilsTest extends GdxTest { LongBuffer lb = BufferUtils.newLongBuffer(8); FloatBuffer fb = BufferUtils.newFloatBuffer(8); DoubleBuffer db = BufferUtils.newDoubleBuffer(8); - + bb.position(4); - BufferUtils.copy(new byte[] { 1, 2, 3, 4 }, 0, bb, 4); - checkInt(bb.get(), 1); + BufferUtils.copy(new byte[] {1, 2, 3, 4}, 0, bb, 4); + checkInt(bb.get(), 1); checkInt(bb.get(), 2); checkInt(bb.get(), 3); checkInt(bb.get(), 4); - + cb.position(4); - BufferUtils.copy(new char[] { 1, 2, 3, 4 }, 0, cb, 4); - checkInt(cb.get(), 1); + BufferUtils.copy(new char[] {1, 2, 3, 4}, 0, cb, 4); + checkInt(cb.get(), 1); checkInt(cb.get(), 2); checkInt(cb.get(), 3); checkInt(cb.get(), 4); - + sb.position(4); - BufferUtils.copy(new short[] { 1, 2, 3, 4 }, 0, sb, 4); - checkInt(sb.get(), 1); + BufferUtils.copy(new short[] {1, 2, 3, 4}, 0, sb, 4); + checkInt(sb.get(), 1); checkInt(sb.get(), 2); checkInt(sb.get(), 3); checkInt(sb.get(), 4); - + ib.position(4); - BufferUtils.copy(new int[] { 1, 2, 3, 4 }, 0, ib, 4); - checkInt(ib.get(), 1); + BufferUtils.copy(new int[] {1, 2, 3, 4}, 0, ib, 4); + checkInt(ib.get(), 1); checkInt(ib.get(), 2); checkInt(ib.get(), 3); checkInt(ib.get(), 4); - + lb.position(4); - BufferUtils.copy(new long[] { 1, 2, 3, 4 }, 0, lb, 4); - checkInt(lb.get(), 1); + BufferUtils.copy(new long[] {1, 2, 3, 4}, 0, lb, 4); + checkInt(lb.get(), 1); checkInt(lb.get(), 2); checkInt(lb.get(), 3); checkInt(lb.get(), 4); - + fb.position(4); - BufferUtils.copy(new float[] { 1, 2, 3, 4 }, 0, fb, 4); - checkFloat(fb.get(), 1); + BufferUtils.copy(new float[] {1, 2, 3, 4}, 0, fb, 4); + checkFloat(fb.get(), 1); checkFloat(fb.get(), 2); checkFloat(fb.get(), 3); checkFloat(fb.get(), 4); - + db.position(4); - BufferUtils.copy(new double[] { 1, 2, 3, 4 }, 0, db, 4); - checkFloat(db.get(), 1); + BufferUtils.copy(new double[] {1, 2, 3, 4}, 0, db, 4); + checkFloat(db.get(), 1); checkFloat(db.get(), 2); checkFloat(db.get(), 3); checkFloat(db.get(), 4); - + ByteBuffer bb2 = BufferUtils.newByteBuffer(4); bb.position(4); BufferUtils.copy(bb, bb2, 4); - checkInt(bb2.get(), 1); + checkInt(bb2.get(), 1); checkInt(bb2.get(), 2); checkInt(bb2.get(), 3); checkInt(bb2.get(), 4); - + bench(); } - - private void bench() { + + private void bench () { benchByte(); benchShort(); benchInt(); @@ -100,241 +103,253 @@ private void bench() { benchFloat(); benchDouble(); } - - private void benchByte() { - ByteBuffer bb = BufferUtils.newByteBuffer(1024*1024); - byte[] bytes = new byte[1024*1024]; + + private void benchByte () { + ByteBuffer bb = BufferUtils.newByteBuffer(1024 * 1024); + byte[] bytes = new byte[1024 * 1024]; int len = bytes.length; final int NUM_MB = 5; - + // relative put long start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - bb.clear(); - for(int i = 0; i < len; i++) bb.put(bytes[i]); + for (int j = 0; j < NUM_MB; j++) { + bb.clear(); + for (int i = 0; i < len; i++) + bb.put(bytes[i]); } Gdx.app.log("BufferUtilsTest", "ByteBuffer relative put: " + (System.nanoTime() - start) / 1000000000.0f); - + // absolute put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - bb.clear(); - for(int i = 0; i < len; i++) bb.put(i, bytes[i]); + for (int j = 0; j < NUM_MB; j++) { + bb.clear(); + for (int i = 0; i < len; i++) + bb.put(i, bytes[i]); } Gdx.app.log("BufferUtilsTest", "ByteBuffer absolute put: " + (System.nanoTime() - start) / 1000000000.0f); - + // bulk put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - bb.clear(); + for (int j = 0; j < NUM_MB; j++) { + bb.clear(); bb.put(bytes); } Gdx.app.log("BufferUtilsTest", "ByteBuffer bulk put: " + (System.nanoTime() - start) / 1000000000.0f); - + // JNI put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - bb.clear(); + for (int j = 0; j < NUM_MB; j++) { + bb.clear(); BufferUtils.copy(bytes, 0, bb, len); } Gdx.app.log("BufferUtilsTest", "ByteBuffer native bulk put: " + (System.nanoTime() - start) / 1000000000.0f); } - - private void benchShort() { - ShortBuffer sb = BufferUtils.newShortBuffer(1024*1024 / 2); - short[] shorts = new short[1024*1024 / 2]; - int len = shorts.length; - + + private void benchShort () { + ShortBuffer sb = BufferUtils.newShortBuffer(1024 * 1024 / 2); + short[] shorts = new short[1024 * 1024 / 2]; + int len = shorts.length; + // relative put long start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - sb.clear(); - for(int i = 0; i < len; i++) sb.put(shorts[i]); + for (int j = 0; j < NUM_MB; j++) { + sb.clear(); + for (int i = 0; i < len; i++) + sb.put(shorts[i]); } Gdx.app.log("BufferUtilsTest", "ShortBuffer relative put: " + (System.nanoTime() - start) / 1000000000.0f); - + // absolute put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - sb.clear(); - for(int i = 0; i < len; i++) sb.put(i, shorts[i]); + for (int j = 0; j < NUM_MB; j++) { + sb.clear(); + for (int i = 0; i < len; i++) + sb.put(i, shorts[i]); } Gdx.app.log("BufferUtilsTest", "ShortBuffer absolute put: " + (System.nanoTime() - start) / 1000000000.0f); - + // bulk put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - sb.clear(); + for (int j = 0; j < NUM_MB; j++) { + sb.clear(); sb.put(shorts); } Gdx.app.log("BufferUtilsTest", "ShortBuffer bulk put: " + (System.nanoTime() - start) / 1000000000.0f); - + // JNI put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - sb.clear(); + for (int j = 0; j < NUM_MB; j++) { + sb.clear(); BufferUtils.copy(shorts, 0, sb, len); } Gdx.app.log("BufferUtilsTest", "ShortBuffer native bulk put: " + (System.nanoTime() - start) / 1000000000.0f); } - - private void benchInt() { - IntBuffer ib = BufferUtils.newIntBuffer(1024*1024 / 4); - int[] ints = new int[1024*1024 / 4]; - int len = ints.length; - + + private void benchInt () { + IntBuffer ib = BufferUtils.newIntBuffer(1024 * 1024 / 4); + int[] ints = new int[1024 * 1024 / 4]; + int len = ints.length; + // relative put long start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - ib.clear(); - for(int i = 0; i < len; i++) ib.put(ints[i]); + for (int j = 0; j < NUM_MB; j++) { + ib.clear(); + for (int i = 0; i < len; i++) + ib.put(ints[i]); } Gdx.app.log("BufferUtilsTest", "IntBuffer relative put: " + (System.nanoTime() - start) / 1000000000.0f); - + // absolute put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - ib.clear(); - for(int i = 0; i < len; i++) ib.put(i, ints[i]); + for (int j = 0; j < NUM_MB; j++) { + ib.clear(); + for (int i = 0; i < len; i++) + ib.put(i, ints[i]); } Gdx.app.log("BufferUtilsTest", "IntBuffer absolute put: " + (System.nanoTime() - start) / 1000000000.0f); - + // bulk put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - ib.clear(); + for (int j = 0; j < NUM_MB; j++) { + ib.clear(); ib.put(ints); } Gdx.app.log("BufferUtilsTest", "IntBuffer bulk put: " + (System.nanoTime() - start) / 1000000000.0f); - + // JNI put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - ib.clear(); + for (int j = 0; j < NUM_MB; j++) { + ib.clear(); BufferUtils.copy(ints, 0, ib, len); } Gdx.app.log("BufferUtilsTest", "IntBuffer native bulk put: " + (System.nanoTime() - start) / 1000000000.0f); } - - private void benchLong() { - LongBuffer lb = BufferUtils.newLongBuffer(1024*1024 / 8); - long[] longs = new long[1024*1024 / 8]; - int len = longs.length; - + + private void benchLong () { + LongBuffer lb = BufferUtils.newLongBuffer(1024 * 1024 / 8); + long[] longs = new long[1024 * 1024 / 8]; + int len = longs.length; + // relative put long start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - lb.clear(); - for(int i = 0; i < len; i++) lb.put(longs[i]); + for (int j = 0; j < NUM_MB; j++) { + lb.clear(); + for (int i = 0; i < len; i++) + lb.put(longs[i]); } Gdx.app.log("BufferUtilsTest", "LongBuffer relative put: " + (System.nanoTime() - start) / 1000000000.0f); - + // absolute put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - lb.clear(); - for(int i = 0; i < len; i++) lb.put(i, longs[i]); + for (int j = 0; j < NUM_MB; j++) { + lb.clear(); + for (int i = 0; i < len; i++) + lb.put(i, longs[i]); } Gdx.app.log("BufferUtilsTest", "LongBuffer absolute put: " + (System.nanoTime() - start) / 1000000000.0f); - + // bulk put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - lb.clear(); + for (int j = 0; j < NUM_MB; j++) { + lb.clear(); lb.put(longs); } Gdx.app.log("BufferUtilsTest", "LongBuffer bulk put: " + (System.nanoTime() - start) / 1000000000.0f); - + // JNI put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - lb.clear(); + for (int j = 0; j < NUM_MB; j++) { + lb.clear(); BufferUtils.copy(longs, 0, lb, len); } Gdx.app.log("BufferUtilsTest", "LongBuffer native bulk put: " + (System.nanoTime() - start) / 1000000000.0f); } - - private void benchFloat() { - FloatBuffer fb = BufferUtils.newFloatBuffer(1024*1024 / 4); - float[] floats = new float[1024*1024 / 4]; - int len = floats.length; - + + private void benchFloat () { + FloatBuffer fb = BufferUtils.newFloatBuffer(1024 * 1024 / 4); + float[] floats = new float[1024 * 1024 / 4]; + int len = floats.length; + // relative put long start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - fb.clear(); - for(int i = 0; i < len; i++) fb.put(floats[i]); + for (int j = 0; j < NUM_MB; j++) { + fb.clear(); + for (int i = 0; i < len; i++) + fb.put(floats[i]); } Gdx.app.log("BufferUtilsTest", "FloatBuffer relative put: " + (System.nanoTime() - start) / 1000000000.0f); - + // absolute put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - fb.clear(); - for(int i = 0; i < len; i++) fb.put(i, floats[i]); + for (int j = 0; j < NUM_MB; j++) { + fb.clear(); + for (int i = 0; i < len; i++) + fb.put(i, floats[i]); } Gdx.app.log("BufferUtilsTest", "FloatBuffer absolute put: " + (System.nanoTime() - start) / 1000000000.0f); - + // bulk put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - fb.clear(); + for (int j = 0; j < NUM_MB; j++) { + fb.clear(); fb.put(floats); } Gdx.app.log("BufferUtilsTest", "FloatBuffer bulk put: " + (System.nanoTime() - start) / 1000000000.0f); - + // JNI put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - fb.clear(); + for (int j = 0; j < NUM_MB; j++) { + fb.clear(); BufferUtils.copy(floats, 0, fb, len); } - Gdx.app.log("BufferUtilsTest", "FloatBuffer native bulk put: " + (System.nanoTime() - start) / 1000000000.0f); + Gdx.app.log("BufferUtilsTest", "FloatBuffer native bulk put: " + (System.nanoTime() - start) / 1000000000.0f); } - - private void benchDouble() { - DoubleBuffer db = BufferUtils.newDoubleBuffer(1024*1024 / 8); - double[] doubles = new double[1024*1024 / 8]; - int len = doubles.length; - + + private void benchDouble () { + DoubleBuffer db = BufferUtils.newDoubleBuffer(1024 * 1024 / 8); + double[] doubles = new double[1024 * 1024 / 8]; + int len = doubles.length; + // relative put long start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - db.clear(); - for(int i = 0; i < len; i++) db.put(doubles[i]); + for (int j = 0; j < NUM_MB; j++) { + db.clear(); + for (int i = 0; i < len; i++) + db.put(doubles[i]); } Gdx.app.log("BufferUtilsTest", "DoubleBuffer relative put: " + (System.nanoTime() - start) / 1000000000.0f); - + // absolute put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - db.clear(); - for(int i = 0; i < len; i++) db.put(i, doubles[i]); + for (int j = 0; j < NUM_MB; j++) { + db.clear(); + for (int i = 0; i < len; i++) + db.put(i, doubles[i]); } Gdx.app.log("BufferUtilsTest", "DoubleBuffer absolute put: " + (System.nanoTime() - start) / 1000000000.0f); - + // bulk put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - db.clear(); + for (int j = 0; j < NUM_MB; j++) { + db.clear(); db.put(doubles); } Gdx.app.log("BufferUtilsTest", "DoubleBuffer bulk put: " + (System.nanoTime() - start) / 1000000000.0f); - + // JNI put start = System.nanoTime(); - for(int j = 0; j < NUM_MB; j++) { - db.clear(); + for (int j = 0; j < NUM_MB; j++) { + db.clear(); BufferUtils.copy(doubles, 0, db, len); } Gdx.app.log("BufferUtilsTest", "DoubleBuffer bulk put: " + (System.nanoTime() - start) / 1000000000.0f); } - - private void checkInt(long val1, long val2) { - if(val1 != val2) throw new GdxRuntimeException("Error, val1 != val2"); + + private void checkInt (long val1, long val2) { + if (val1 != val2) throw new GdxRuntimeException("Error, val1 != val2"); } - - private void checkFloat(double val1, double val2) { - if(val1 != val2) throw new GdxRuntimeException("Error, val1 != val2"); + + private void checkFloat (double val1, double val2) { + if (val1 != val2) throw new GdxRuntimeException("Error, val1 != val2"); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/CompassTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/CompassTest.java index c73e060a335..fd1813661c0 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/CompassTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/CompassTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -24,26 +25,29 @@ public class CompassTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } BitmapFont font; SpriteBatch batch; - ImmediateModeRenderer10 renderer; - - @Override public void create() { + ImmediateModeRenderer10 renderer; + + @Override + public void create () { font = new BitmapFont(); batch = new SpriteBatch(); renderer = new ImmediateModeRenderer10(); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.drawMultiLine(batch, getOrientationString(), 20, Gdx.graphics.getHeight() - 10); batch.end(); - + Gdx.gl10.glMatrixMode(GL10.GL_PROJECTION); Gdx.gl10.glLoadIdentity(); float aspect = (float)Gdx.graphics.getHeight() / Gdx.graphics.getWidth(); @@ -52,21 +56,22 @@ public class CompassTest extends GdxTest { Gdx.gl10.glLoadIdentity(); Gdx.gl10.glRotatef(Gdx.input.getAzimuth() + 90, 0, 0, 1); renderer.begin(GL10.GL_TRIANGLES); - renderer.color( 1, 1, 1, 1); + renderer.color(1, 1, 1, 1); renderer.vertex(-0.3f, -0.5f, 0); - renderer.color( 1, 1, 1, 1); + renderer.color(1, 1, 1, 1); renderer.vertex(0.3f, -0.5f, 0); - renderer.color( 1, 1, 1, 1); + renderer.color(1, 1, 1, 1); renderer.vertex(0, 0.5f, 0); renderer.end(); } - - @Override public void resize(int width, int height) { + + @Override + public void resize (int width, int height) { batch.getProjectionMatrix().setToOrtho2D(0, 0, width, height); } - - private String getOrientationString() { - StringBuilder builder = new StringBuilder(); + + private String getOrientationString () { + StringBuilder builder = new StringBuilder(); builder.append("\nazimuth: "); builder.append((int)Gdx.input.getAzimuth()); builder.append("\npitch: "); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ComplexActionTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ComplexActionTest.java index 2b38cbe2321..018532f61d1 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ComplexActionTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ComplexActionTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -33,49 +34,45 @@ public class ComplexActionTest extends GdxTest { @Override - public boolean needsGL20() { + public boolean needsGL20 () { return false; } Stage stage; @Override - public void create() { - stage = new Stage(480,320, true); - - Action complexAction = Forever.$( - Sequence.$( - Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.4f, 1.4f, 2), FadeTo.$(0.7f, 2)), - Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.0f, 1.0f, 2), FadeTo.$(1.0f, 2)) - ) - ); - + public void create () { + stage = new Stage(480, 320, true); + + Action complexAction = Forever.$(Sequence.$(Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.4f, 1.4f, 2), FadeTo.$(0.7f, 2)), + Parallel.$(RotateBy.$(180, 2), ScaleTo.$(1.0f, 1.0f, 2), FadeTo.$(1.0f, 2)))); + Texture texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), false); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); - + final Image img1 = new Image("SampleActor1", texture); - + img1.width = img1.height = 100; img1.originX = 50; img1.originY = 50; img1.x = img1.y = 50; - + final Image img2 = new Image("SampleActor1", texture); - + img2.width = img1.height = 50; img2.originX = 50; img2.originY = 50; img2.x = img2.y = 150; - + stage.addActor(img1); stage.addActor(img2); - + img1.action(complexAction.copy()); img2.action(complexAction.copy()); } - + @Override - public void render() { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f)); stage.draw(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/CullTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/CullTest.java index 984c9de470f..5e7720c9cf1 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/CullTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/CullTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -22,7 +23,6 @@ import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; -import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; @@ -32,7 +32,8 @@ public class CullTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -41,41 +42,41 @@ public class CullTest extends GdxTest { SpriteBatch batch; BitmapFont font; Vector3[] positions = new Vector3[100]; - - @Override public void create() { + + @Override + public void create () { sphere = ObjLoader.loadObj(Gdx.files.internal("data/sphere.obj").read()); cam = new PerspectiveCamera(45, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); -// cam = new OrthographicCamera(100, 100); +// cam = new OrthographicCamera(100, 100); cam.far = 200; Random rand = new Random(); - for(int i = 0; i < positions.length; i++) { - positions[i] = new Vector3(rand.nextFloat() * 100 - rand.nextFloat() * 100, - rand.nextFloat() * 100 - rand.nextFloat() * 100, - rand.nextFloat() * -100 - 3); + for (int i = 0; i < positions.length; i++) { + positions[i] = new Vector3(rand.nextFloat() * 100 - rand.nextFloat() * 100, rand.nextFloat() * 100 - rand.nextFloat() + * 100, rand.nextFloat() * -100 - 3); } batch = new SpriteBatch(); font = new BitmapFont(); Gdx.graphics.setVSync(true); Gdx.app.log("CullTest", "" + Gdx.graphics.getBufferFormat().toString()); } - - @Override public void render() { + + @Override + public void render () { GL10 gl = Gdx.gl10; - + gl.glClearColor(0, 0, 0, 0); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glEnable(GL10.GL_DEPTH_TEST); - + cam.update(); cam.apply(gl); - + int visible = 0; - for(int i = 0; i < positions.length; i++) { - if(cam.frustum.sphereInFrustum(positions[i], 1)) { + for (int i = 0; i < positions.length; i++) { + if (cam.frustum.sphereInFrustum(positions[i], 1)) { gl.glColor4f(1, 1, 1, 1); visible++; - } - else { + } else { gl.glColor4f(1, 0, 0, 1); } gl.glPushMatrix(); @@ -83,12 +84,10 @@ public class CullTest extends GdxTest { sphere.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); } - - if(Gdx.input.isKeyPressed(Keys.A)) - cam.rotate(20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); - if(Gdx.input.isKeyPressed(Keys.D)) - cam.rotate(-20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); - + + if (Gdx.input.isKeyPressed(Keys.A)) cam.rotate(20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); + if (Gdx.input.isKeyPressed(Keys.D)) cam.rotate(-20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); + gl.glDisable(GL10.GL_DEPTH_TEST); batch.begin(); font.draw(batch, "visible: " + visible + "/100" + ", fps: " + Gdx.graphics.getFramesPerSecond(), 0, 20); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/DecalTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/DecalTest.java index b2d0609506c..f9e76126ce2 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/DecalTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/DecalTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import java.util.LinkedList; @@ -20,7 +21,7 @@ public class DecalTest extends Game { public static final int INITIAL_RENDERED = 100; private boolean willItBlend_that_is_the_question = true; private GroupStrategy strategy = new SimpleOrthoGroupStrategy(); - //private GroupStrategy strategy = new DefaultGroupStrategy(); + // private GroupStrategy strategy = new DefaultGroupStrategy(); Texture egg; Texture wheel; LinkedList toRender = new LinkedList(); @@ -34,7 +35,7 @@ public class DecalTest extends Game { float h; @Override - public void create() { + public void create () { Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); Gdx.gl10.glDepthFunc(GL10.GL_LESS); @@ -47,23 +48,22 @@ public void create() { w = Gdx.graphics.getWidth() / 0.8f; h = Gdx.graphics.getHeight() / 0.8f; - for(int i = 0; i < INITIAL_RENDERED; i++) { + for (int i = 0; i < INITIAL_RENDERED; i++) { toRender.add(makeDecal()); } batch = new DecalBatch(strategy); - Gdx.gl.glClearColor(1,1,0,1); + Gdx.gl.glClearColor(1, 1, 0, 1); } @Override - public void render() { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); - float elapsed = Gdx.graphics.getDeltaTime(); float scale = timePassed > 0.5 ? 1 - timePassed / 2 : 0.5f + timePassed / 2; - for(Decal decal : toRender) { + for (Decal decal : toRender) { decal.rotateZ(elapsed * 45); decal.setScale(scale); batch.add(decal); @@ -72,21 +72,20 @@ public void render() { timePassed += elapsed; frames++; - if(timePassed > 1.0f) { + if (timePassed > 1.0f) { System.out.println("DecalPerformanceTest2 fps: " + frames + " at spritecount: " + toRender.size()); fps.addValue(frames); - if(fps.hasEnoughData()) { - float factor = fps.getMean() / (float) TARGET_FPS; - int target = (int) (toRender.size() * factor); - if(fps.getMean() > TARGET_FPS) { + if (fps.hasEnoughData()) { + float factor = fps.getMean() / (float)TARGET_FPS; + int target = (int)(toRender.size() * factor); + if (fps.getMean() > TARGET_FPS) { int start = toRender.size(); - for(int i = start; toRender.size() < target; i++) { + for (int i = start; toRender.size() < target; i++) { toRender.add(makeDecal()); } fps.clear(); - } - else { - while(toRender.size() > target) { + } else { + while (toRender.size() > target) { toRender.removeLast(); } fps.clear(); @@ -98,7 +97,7 @@ public void render() { } @Override - public void resize(int width, int height) { + public void resize (int width, int height) { w = Gdx.graphics.getWidth() / 0.8f; h = Gdx.graphics.getHeight() / 0.8f; cam = new OrthographicCamera(width, height); @@ -110,17 +109,17 @@ public void resize(int width, int height) { cam.apply(Gdx.gl10); } - private Decal makeDecal() { + private Decal makeDecal () { Decal sprite = null; - switch(idx % 2) { - case 0: - sprite = Decal.newDecal(new TextureRegion(egg), willItBlend_that_is_the_question); - break; - case 1: - sprite = Decal.newDecal(new TextureRegion(wheel)); - break; + switch (idx % 2) { + case 0: + sprite = Decal.newDecal(new TextureRegion(egg), willItBlend_that_is_the_question); + break; + case 1: + sprite = Decal.newDecal(new TextureRegion(wheel)); + break; } - sprite.setPosition(-w / 2 + (float) Math.random() * w, h / 2 - (float) Math.random() * h, (float) -Math.random() * 10); + sprite.setPosition(-w / 2 + (float)Math.random() * w, h / 2 - (float)Math.random() * h, (float)-Math.random() * 10); idx++; return sprite; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/DeltaTimeTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/DeltaTimeTest.java index b3e89cc3cb4..dc43458b84f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/DeltaTimeTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/DeltaTimeTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -20,21 +21,24 @@ public class DeltaTimeTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } long lastFrameTime; - - @Override public void create() { + + @Override + public void create () { lastFrameTime = System.nanoTime(); } - - @Override public void render() { + + @Override + public void render () { long frameTime = System.nanoTime(); - float deltaTime = (frameTime - lastFrameTime) / 1000000000.0f; + float deltaTime = (frameTime - lastFrameTime) / 1000000000.0f; lastFrameTime = frameTime; - + Gdx.app.log("DeltaTimeTest", "delta: " + deltaTime + ", gdx delta: " + Gdx.graphics.getDeltaTime()); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ETC1Test.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ETC1Test.java index d3748892ee8..5021262ed3d 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ETC1Test.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ETC1Test.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -17,10 +18,10 @@ public class ETC1Test extends GdxTest { @Override - public boolean needsGL20() { + public boolean needsGL20 () { return true; } - + OrthographicCamera camera; OrthoCamController controller; Texture img1; @@ -28,12 +29,13 @@ public boolean needsGL20() { SpriteBatch batch; BitmapFont font; - @Override public void create() { + @Override + public void create () { font = new BitmapFont(); camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); controller = new OrthoCamController(camera); Gdx.input.setInputProcessor(controller); - + Pixmap pixmap = new Pixmap(32, 32, Format.RGB565); pixmap.setColor(1, 0, 0, 1); pixmap.fill(); @@ -43,31 +45,32 @@ public boolean needsGL20() { ETC1Data encodedImage = ETC1.encodeImagePKM(pixmap); pixmap.dispose(); pixmap = ETC1.decodeImage(encodedImage, Format.RGB565); - -// ETC1.encodeImagePKM(new Pixmap(Gdx.files.internal("data/environment.jpg"))).write(Gdx.files.absolute("test.pkm")); - + +// ETC1.encodeImagePKM(new Pixmap(Gdx.files.internal("data/environment.jpg"))).write(Gdx.files.absolute("test.pkm")); + encodedImage.dispose(); - + img1 = new Texture(pixmap); img2 = new Texture(new ETC1TextureData(Gdx.files.internal("data/test.pkm"))); - batch = new SpriteBatch(); + batch = new SpriteBatch(); pixmap.dispose(); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + camera.update(); - + batch.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(img1, 0, 0); batch.draw(img2, -100, 0); batch.end(); - - batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + + batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.begin(); - font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 0, 30); + font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 0, 30); batch.end(); } -} \ No newline at end of file +} diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java index 34243d370e2..aa4d9ae97e0 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/EdgeDetectionTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Arrays; @@ -24,8 +25,6 @@ import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.Pixmap.Format; -import com.badlogic.gdx.graphics.Texture.TextureWrap; -import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g3d.loaders.obj.ObjLoader; @@ -35,41 +34,39 @@ import com.badlogic.gdx.tests.utils.GdxTest; public class EdgeDetectionTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } - + FPSLogger logger; ShaderProgram shader; Mesh mesh; FrameBuffer fbo; - PerspectiveCamera cam; + PerspectiveCamera cam; Matrix4 matrix = new Matrix4(); float angle = 0; TextureRegion fboRegion; SpriteBatch batch; - ShaderProgram batchShader; - - float[] filter = { 0, 0.25f, 0, - 0.25f, -1f, 0.6f, - 0, 0.25f, 0, - }; - + ShaderProgram batchShader; + + float[] filter = {0, 0.25f, 0, 0.25f, -1f, 0.6f, 0, 0.25f, 0,}; + float[] offsets = new float[18]; - - public void create() { + + public void create () { ShaderProgram.pedantic = false; - shader = new ShaderProgram(Gdx.files.internal("data/default.vert").readString(), - Gdx.files.internal("data/depthtocolor.frag").readString()); - if(!shader.isCompiled()) { + shader = new ShaderProgram(Gdx.files.internal("data/default.vert").readString(), Gdx.files.internal( + "data/depthtocolor.frag").readString()); + if (!shader.isCompiled()) { Gdx.app.log("EdgeDetectionTest", "couldn't compile scene shader: " + shader.getLog()); } - batchShader = new ShaderProgram(Gdx.files.internal("data/batch.vert").readString(), - Gdx.files.internal("data/convolution.frag").readString()); - if(!batchShader.isCompiled()) { + batchShader = new ShaderProgram(Gdx.files.internal("data/batch.vert").readString(), Gdx.files.internal( + "data/convolution.frag").readString()); + if (!batchShader.isCompiled()) { Gdx.app.log("EdgeDetectionTest", "couldn't compile post-processing shader: " + batchShader.getLog()); } - + mesh = ObjLoader.loadObj(Gdx.files.internal("data/scene.obj").read()); fbo = new FrameBuffer(Format.RGB565, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); @@ -81,28 +78,28 @@ public void create() { fboRegion = new TextureRegion(fbo.getColorBufferTexture()); fboRegion.flip(false, true); logger = new FPSLogger(); - calculateOffsets(); + calculateOffsets(); } - - private void calculateOffsets() { + + private void calculateOffsets () { int idx = 0; - for(int y = -1; y <= 1; y++) { - for(int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { offsets[idx++] = x / (float)Gdx.graphics.getWidth(); offsets[idx++] = y / (float)Gdx.graphics.getHeight(); } } System.out.println(Arrays.toString(offsets)); } - - public void render() { + + public void render () { angle += 45 * Gdx.graphics.getDeltaTime(); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); - + cam.update(); matrix.setToRotation(0, 1, 0, angle); cam.combined.mul(matrix); - + fbo.begin(); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); @@ -112,13 +109,12 @@ public void render() { mesh.render(shader, GL10.GL_TRIANGLES); shader.end(); fbo.end(); - - + batch.begin(); batch.disableBlending(); batchShader.setUniformi("u_filterSize", filter.length); batchShader.setUniform1fv("u_filter", filter, 0, filter.length); - batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length); + batchShader.setUniform2fv("u_offsets", offsets, 0, offsets.length); batch.draw(fboRegion, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.end(); logger.log(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ExitTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ExitTest.java index dd043aabf48..89cf4a2d5cd 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ExitTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ExitTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -5,19 +6,23 @@ public class ExitTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public void render() { - if(Gdx.input.justTouched()) Gdx.app.exit(); + @Override + public void render () { + if (Gdx.input.justTouched()) Gdx.app.exit(); } - - @Override public void pause() { - Gdx.app.log("ExitTest", "paused"); + + @Override + public void pause () { + Gdx.app.log("ExitTest", "paused"); } - - @Override public void dispose() { - Gdx.app.log("ExitTest", "disposed"); + + @Override + public void dispose () { + Gdx.app.log("ExitTest", "disposed"); } } 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 be3ac276581..6db41f6ac40 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FFTTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FFTTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.FloatBuffer; diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FilesTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FilesTest.java index 25843d03814..83ee018b259 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FilesTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FilesTest.java @@ -37,7 +37,8 @@ public class FilesTest extends GdxTest { BitmapFont font; SpriteBatch batch; - @Override public void create () { + @Override + public void create () { font = new BitmapFont(); batch = new SpriteBatch(); @@ -338,14 +339,16 @@ private void fail () { throw new RuntimeException(); } - @Override public void render () { + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.drawMultiLine(batch, message, 20, Gdx.graphics.getHeight() - 20); batch.end(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } 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 3787bbfcc61..7c21dae2975 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FillrateTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FillrateTest.java @@ -13,16 +13,15 @@ * 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.InputProcessor; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; 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; import com.badlogic.gdx.tests.utils.GdxTest; @@ -37,7 +36,8 @@ public class FillrateTest extends GdxTest implements InputProcessor { float mean = 0; float frames = 0; - @Override public void create () { + @Override + public void create () { texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); @@ -74,7 +74,8 @@ public class FillrateTest extends GdxTest implements InputProcessor { Gdx.input.setInputProcessor(this); } - @Override public void render () { + @Override + public void render () { Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); if (mode == 3) { @@ -117,42 +118,51 @@ public class FillrateTest extends GdxTest implements InputProcessor { } } - @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) { return false; } - @Override public boolean keyTyped (char character) { + @Override + public boolean keyTyped (char character) { return false; } - @Override public boolean touchDown (int x, int y, int pointer, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { mode++; 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) { return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FilterPerformanceTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FilterPerformanceTest.java index 1bf0df0498d..51aaff881a7 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FilterPerformanceTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FilterPerformanceTest.java @@ -13,15 +13,14 @@ * 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.InputAdapter; import com.badlogic.gdx.graphics.GL10; 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.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; @@ -40,36 +39,35 @@ public class FilterPerformanceTest extends GdxTest { BitmapFont font; int mode = 0; String modeString = ""; - int[] filters = {GL10.GL_NEAREST, GL10.GL_LINEAR, - GL10.GL_NEAREST_MIPMAP_NEAREST, GL10.GL_LINEAR_MIPMAP_NEAREST, - GL10.GL_LINEAR_MIPMAP_LINEAR}; - String[] filterNames = { "nearest", "linear", "nearest mipmap nearest", "linear mipmap nearest", "linear mipmap linear" }; - + int[] filters = {GL10.GL_NEAREST, GL10.GL_LINEAR, GL10.GL_NEAREST_MIPMAP_NEAREST, GL10.GL_LINEAR_MIPMAP_NEAREST, + GL10.GL_LINEAR_MIPMAP_LINEAR}; + String[] filterNames = {"nearest", "linear", "nearest mipmap nearest", "linear mipmap nearest", "linear mipmap linear"}; + void setTextureFilter (int filter) { atlas.findRegion("map").getTexture().bind(); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, filters[filter]); texture.bind(); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, filters[filter]); } - - void setModeString() { - modeString = (mode%2==0?"Sprite":"Atlas") + " " + filterNames[mode/2]; + + void setModeString () { + modeString = (mode % 2 == 0 ? "Sprite" : "Atlas") + " " + filterNames[mode / 2]; } - + public void create () { batch = new SpriteBatch(); sceneMatrix = new Matrix4().setToOrtho2D(0, 0, 480, 320); - textMatrix = new Matrix4().setToOrtho2D(0, 0, 480, 320); + textMatrix = new Matrix4().setToOrtho2D(0, 0, 480, 320); atlas = new TextureAtlas(Gdx.files.internal("data/issue_pack"), Gdx.files.internal("data/")); texture = new Texture(Gdx.files.internal("data/resource1.jpg"), true); - texture.setFilter(TextureFilter.MipMap, TextureFilter.Nearest); + texture.setFilter(TextureFilter.MipMap, TextureFilter.Nearest); setTextureFilter(0); setModeString(); sprite = atlas.createSprite("map"); sprite2 = new Sprite(texture, 0, 0, 855, 480); - font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); + font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); Gdx.input.setInputProcessor(new InputAdapter() { public boolean touchDown (int x, int y, int pointer, int newParam) { @@ -84,24 +82,24 @@ public boolean touchDown (int x, int y, int pointer, int newParam) { public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + batch.setProjectionMatrix(sceneMatrix); - batch.begin(); + batch.begin(); renderSprite(); batch.end(); - + batch.setProjectionMatrix(textMatrix); - batch.begin(); + batch.begin(); font.draw(batch, modeString + " fps:" + Gdx.graphics.getFramesPerSecond(), 26, 65); batch.end(); } public void renderSprite () { batch.disableBlending(); - if(mode % 2 == 0) + if (mode % 2 == 0) sprite2.draw(batch); else - sprite.draw(batch); + sprite.draw(batch); batch.enableBlending(); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FlickScrollPaneTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FlickScrollPaneTest.java index 25458d27019..142cf2c5d87 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FlickScrollPaneTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FlickScrollPaneTest.java @@ -10,7 +10,6 @@ import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; -import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.badlogic.gdx.tests.utils.GdxTest; public class FlickScrollPaneTest extends GdxTest { 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 fcf5d0a5488..76ae023f8dc 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FloatTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FloatTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ByteBuffer; @@ -24,8 +25,6 @@ import com.badlogic.gdx.graphics.Pixmap; 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.tests.utils.GdxTest; public class FloatTest extends GdxTest { @@ -37,12 +36,14 @@ public class FloatTest extends GdxTest { 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); @@ -103,7 +104,7 @@ private void init () { pixmap.drawLine(256, 0, 0, 256); tex = new Texture(pixmap, false); pixmap.dispose(); - + pixmap = new Pixmap(256, 256, Format.RGBA8888); pixmap.setColor(1, 1, 1, 1); pixmap.fill(); @@ -113,15 +114,18 @@ private void init () { pixmap.dispose(); } - @Override public void create () { + @Override + public void create () { init(); } - @Override public void resume () { + @Override + public void resume () { init(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } 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 ee8505d7926..b4e55989898 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FrameBufferTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FrameBufferTest.java @@ -28,7 +28,6 @@ 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.graphics.Color; @@ -36,8 +35,6 @@ import com.badlogic.gdx.graphics.Mesh; 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.Usage; import com.badlogic.gdx.graphics.g2d.SpriteBatch; @@ -52,7 +49,8 @@ public class FrameBufferTest extends GdxTest { Texture texture; SpriteBatch spriteBatch; - @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); @@ -75,7 +73,8 @@ public class FrameBufferTest extends GdxTest { spriteBatch.end(); } - @Override public void create () { + @Override + public void create () { mesh = new Mesh(true, 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); @@ -109,7 +108,8 @@ private void createShader (Graphics graphics) { if (meshShader.isCompiled() == false) throw new IllegalStateException(meshShader.getLog()); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FramebufferToTextureTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FramebufferToTextureTest.java index b0029cda2e0..53ea32c0f76 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FramebufferToTextureTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FramebufferToTextureTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -25,12 +26,12 @@ import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g3d.loaders.ModelLoaderOld; -import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.tests.utils.GdxTest; public class FramebufferToTextureTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -42,9 +43,10 @@ public class FramebufferToTextureTest extends GdxTest { BitmapFont font; Color clearColor = new Color(0.2f, 0.2f, 0.2f, 1); float angle = 0; - - @Override public void create() { - mesh = ModelLoaderOld.loadObj(Gdx.files.internal("data/cube.obj").read()); + + @Override + public void create () { + mesh = ModelLoaderOld.loadObj(Gdx.files.internal("data/cube.obj").read()); texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), true); texture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); @@ -53,9 +55,10 @@ public class FramebufferToTextureTest extends GdxTest { cam.direction.set(-1, -1, -1); batch = new SpriteBatch(); font = new BitmapFont(); - } - - @Override public void render() { + } + + @Override + public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); @@ -63,32 +66,34 @@ public class FramebufferToTextureTest extends GdxTest { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); - + cam.update(); cam.apply(gl); - + angle += 45 * Gdx.graphics.getDeltaTime(); gl.glPushMatrix(); gl.glRotatef(angle, 0, 1, 0); texture.bind(); mesh.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); - - if(Gdx.input.justTouched() || fbTexture == null) { -// if(fbTexture != null) fbTexture.dispose(); -// fbTexture = Texture.getFrameBufferTexture(); -// clearColor.set(MathUtils.random(), MathUtils.random(), MathUtils.random(), 1); - } - + + if (Gdx.input.justTouched() || fbTexture == null) { +// if(fbTexture != null) fbTexture.dispose(); +// fbTexture = Texture.getFrameBufferTexture(); +// clearColor.set(MathUtils.random(), MathUtils.random(), MathUtils.random(), 1); + } + batch.begin(); - if(fbTexture != null) { - batch.draw(fbTexture, 0, Gdx.graphics.getHeight() - 100, 100, 100, 0, 0, fbTexture.getWidth(), fbTexture.getHeight(), false, true); + if (fbTexture != null) { + batch.draw(fbTexture, 0, Gdx.graphics.getHeight() - 100, 100, 100, 0, 0, fbTexture.getWidth(), fbTexture.getHeight(), + false, true); } font.draw(batch, "Touch screen to take a snapshot", 10, 40); batch.end(); } - - @Override public void pause() { + + @Override + public void pause () { fbTexture = null; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FrustumTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FrustumTest.java index fb99a105ba4..e0087cd4c97 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FrustumTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FrustumTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -5,9 +6,7 @@ import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.PerspectiveCamera; -import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.VertexAttribute; -import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.loaders.ModelLoaderOld; import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer10; @@ -18,7 +17,8 @@ import com.badlogic.gdx.tests.utils.PerspectiveCamController; public class FrustumTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -27,126 +27,125 @@ public class FrustumTest extends GdxTest { OrthographicCamera camera3; PerspectiveCamController controller; Mesh plane; - Mesh sphere; + Mesh sphere; ImmediateModeRenderer10 renderer; - - @Override public void create() { + + @Override + public void create () { camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.position.set(0, 2, 3).nor().mul(10); camera.lookAt(0, 0, 0); - + camera2 = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera2.position.set(-3, 2, 0); camera2.lookAt(0, 0, 0); camera2.near = 0.5f; camera2.far = 6; - + float aspect = Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight(); camera3 = new OrthographicCamera(2 * aspect, 2); camera3.position.set(3, 2, 0); camera3.lookAt(0, 0, 0); camera3.near = 0.5f; camera3.far = 6; - + controller = new PerspectiveCamController(camera); Gdx.input.setInputProcessor(controller); - + plane = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); - - plane.setVertices(new float[] { -10, -1, 10, - 10, -1, 10, - 10, -1, -10, - -10, -1, -10}); - plane.setIndices(new short[] { 3, 2, 1, 1, 0, 3 }); + + plane.setVertices(new float[] {-10, -1, 10, 10, -1, 10, 10, -1, -10, -10, -1, -10}); + plane.setIndices(new short[] {3, 2, 1, 1, 0, 3}); sphere = ModelLoaderOld.loadObj(Gdx.files.internal("data/sphere.obj").read()); renderer = new ImmediateModeRenderer10(); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); - + camera.update(); camera2.update(); camera3.update(); - camera.apply(Gdx.gl10); - + camera.apply(Gdx.gl10); + Gdx.gl10.glColor4f(1, 0, 0, 1); plane.render(GL10.GL_TRIANGLE_FAN); Gdx.gl10.glColor4f(0, 1, 0, 1); sphere.render(GL10.GL_TRIANGLES); - + renderFrustum(renderer, camera2.frustum); renderFrustum(renderer, camera3.frustum); } - - public void renderFrustum(ImmediateModeRenderer10 renderer, Frustum frustum) { + + public void renderFrustum (ImmediateModeRenderer10 renderer, Frustum frustum) { Vector3[] planePoints = frustum.planePoints; renderer.begin(GL10.GL_LINES); - + // near plane renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[0]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[1]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[1]); + renderer.vertex(planePoints[1]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[2]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[2]); + renderer.vertex(planePoints[2]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[3]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[3]); + renderer.vertex(planePoints[3]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[0]); - + // far plane renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[4]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[5]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[5]); + renderer.vertex(planePoints[5]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[6]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[6]); + renderer.vertex(planePoints[6]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[7]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[7]); + renderer.vertex(planePoints[7]); renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[4]); - + renderer.vertex(planePoints[4]); + // left, right, top bottom (sort of :p) renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[0]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[4]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[1]); + renderer.vertex(planePoints[1]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[5]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[2]); + renderer.vertex(planePoints[2]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[6]); - + renderer.color(0.1f, 0.8f, 0.1f, 1); - renderer.vertex(planePoints[3]); + renderer.vertex(planePoints[3]); renderer.color(0.1f, 0.8f, 0.1f, 1); renderer.vertex(planePoints[7]); - + renderer.end(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/FullscreenTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/FullscreenTest.java index 6af7106e636..a8b111fd230 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/FullscreenTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/FullscreenTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -13,52 +14,57 @@ public class FullscreenTest extends GdxTest { Mesh mesh; Texture texture; - - @Override public void create () { + + @Override + public void create () { texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); - mesh = new Mesh(true, 3, 0, new VertexAttribute(Usage.Position, 3, "a_pos"), - new VertexAttribute(Usage.TextureCoordinates, 2, "a_tex")); - mesh.setVertices(new float[] { -1, -1, 0, 0, 1, - 0, 1, 0, 0.5f, 0, - 1, -1, 0, 1, 1}); - + mesh = new Mesh(true, 3, 0, new VertexAttribute(Usage.Position, 3, "a_pos"), new VertexAttribute(Usage.TextureCoordinates, + 2, "a_tex")); + mesh.setVertices(new float[] {-1, -1, 0, 0, 1, 0, 1, 0, 0.5f, 0, 1, -1, 0, 1, 1}); + DisplayMode[] modes = Gdx.graphics.getDisplayModes(); - for(DisplayMode mode: modes) { + for (DisplayMode mode : modes) { System.out.println(mode); } Gdx.graphics.setDisplayMode(800, 600, true); Gdx.app.log("FullscreenTest", Gdx.graphics.getBufferFormat().toString()); } - @Override public void resume () { - + @Override + public void resume () { + } - @Override public void render () { + @Override + public void render () { Gdx.gl.glClearColor((float)Math.random(), 0, 0, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); texture.bind(); mesh.render(GL10.GL_TRIANGLES); - - if(Gdx.input.justTouched()) { + + if (Gdx.input.justTouched()) { Gdx.graphics.setDisplayMode(480, 320, false); - } + } } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { Gdx.app.log("FullscreenTest", "resized: " + width + ", " + height); } - @Override public void pause () { + @Override + public void pause () { Gdx.app.log("FullscreenTest", "paused"); } - @Override public void dispose () { + @Override + public void dispose () { Gdx.app.log("FullscreenTest", "disposed"); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; - } -} \ No newline at end of file + } +} diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Gdx2DTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Gdx2DTest.java index e1f565b9908..1f32d6cf117 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Gdx2DTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Gdx2DTest.java @@ -13,71 +13,68 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.ArrayList; import java.util.List; -import java.util.Random; import com.badlogic.gdx.Gdx; 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.Texture; -import com.badlogic.gdx.graphics.Texture.TextureFilter; -import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.g2d.Gdx2DPixmap; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; -public class Gdx2DTest extends GdxTest { +public class Gdx2DTest extends GdxTest { SpriteBatch batch; - List sprites; - - Texture textureFromPixmap(Gdx2DPixmap pixmap) { + List sprites; + + Texture textureFromPixmap (Gdx2DPixmap pixmap) { Texture texture = new Texture(pixmap.getWidth(), pixmap.getHeight(), Format.RGB565); texture.bind(); - Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), - pixmap.getWidth(), pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); + Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0, + pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels()); return texture; } - - void drawToPixmap(Gdx2DPixmap pixmap) { + + void drawToPixmap (Gdx2DPixmap pixmap) { pixmap.clear(Color.rgba8888(1, 0, 0, 0.1f)); pixmap.setPixel(16, 16, Color.rgba8888(0, 0, 1, 1)); int clearColor = 0; int pixelColor = 0; - switch(pixmap.getFormat()) { - case Gdx2DPixmap.GDX2D_FORMAT_ALPHA: - clearColor = Color.rgba8888(1, 1, 1, 0.1f); - pixelColor = Color.rgba8888(1, 1, 1, 1); - break; - case Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA: - clearColor = 0x36363619; //Color.rgba8888(1, 1, 1, 0.1f); - pixelColor = 0xffffff12; - break; - case Gdx2DPixmap.GDX2D_FORMAT_RGB565: - clearColor = Color.rgba8888(1, 0, 0, 1); - pixelColor = Color.rgba8888(0, 0, 1, 1); - break; - case Gdx2DPixmap.GDX2D_FORMAT_RGB888: - clearColor = Color.rgba8888(1, 0, 0, 1); - pixelColor = Color.rgba8888(0, 0, 1, 1); - break; - case Gdx2DPixmap.GDX2D_FORMAT_RGBA4444: - clearColor = 0xff000011; - pixelColor = Color.rgba8888(0, 0, 1, 1); - break; - case Gdx2DPixmap.GDX2D_FORMAT_RGBA8888: - clearColor = Color.rgba8888(1, 0, 0, 0.1f); - pixelColor = Color.rgba8888(0, 0, 1, 1); - - } - if(pixmap.getPixel(15, 16) != clearColor) throw new RuntimeException("error clear: " + pixmap.getFormatString()); - if(pixmap.getPixel(16, 16) != pixelColor) throw new RuntimeException("error pixel: " + pixmap.getFormatString()); - pixmap.drawLine(0,0,31,31,Color.rgba8888(1, 1, 1, 1)); + switch (pixmap.getFormat()) { + case Gdx2DPixmap.GDX2D_FORMAT_ALPHA: + clearColor = Color.rgba8888(1, 1, 1, 0.1f); + pixelColor = Color.rgba8888(1, 1, 1, 1); + break; + case Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA: + clearColor = 0x36363619; // Color.rgba8888(1, 1, 1, 0.1f); + pixelColor = 0xffffff12; + break; + case Gdx2DPixmap.GDX2D_FORMAT_RGB565: + clearColor = Color.rgba8888(1, 0, 0, 1); + pixelColor = Color.rgba8888(0, 0, 1, 1); + break; + case Gdx2DPixmap.GDX2D_FORMAT_RGB888: + clearColor = Color.rgba8888(1, 0, 0, 1); + pixelColor = Color.rgba8888(0, 0, 1, 1); + break; + case Gdx2DPixmap.GDX2D_FORMAT_RGBA4444: + clearColor = 0xff000011; + pixelColor = Color.rgba8888(0, 0, 1, 1); + break; + case Gdx2DPixmap.GDX2D_FORMAT_RGBA8888: + clearColor = Color.rgba8888(1, 0, 0, 0.1f); + pixelColor = Color.rgba8888(0, 0, 1, 1); + + } + if (pixmap.getPixel(15, 16) != clearColor) throw new RuntimeException("error clear: " + pixmap.getFormatString()); + if (pixmap.getPixel(16, 16) != pixelColor) throw new RuntimeException("error pixel: " + pixmap.getFormatString()); + pixmap.drawLine(0, 0, 31, 31, Color.rgba8888(1, 1, 1, 1)); pixmap.drawRect(10, 10, 5, 7, Color.rgba8888(1, 1, 0, 0.5f)); pixmap.fillRect(20, 10, 5, 7, Color.rgba8888(0, 1, 1, 0.5f)); pixmap.drawCircle(16, 16, 10, Color.rgba8888(1, 0, 1, 1)); @@ -85,76 +82,75 @@ void drawToPixmap(Gdx2DPixmap pixmap) { pixmap.drawLine(0, -1, 0, 0, Color.rgba8888(1, 1, 0, 1)); pixmap.drawLine(41, -10, 31, 0, Color.rgba8888(1, 1, 0, 1)); pixmap.drawLine(10, 41, 0, 31, Color.rgba8888(0, 1, 1, 1)); - pixmap.drawLine(41, 41, 31, 31, Color.rgba8888(0, 1, 1, 1)); - - pixmap.drawRect(-10, -10, 20, 20, Color.rgba8888(0, 1, 1, 1)); + pixmap.drawLine(41, 41, 31, 31, Color.rgba8888(0, 1, 1, 1)); + + pixmap.drawRect(-10, -10, 20, 20, Color.rgba8888(0, 1, 1, 1)); pixmap.drawRect(21, -10, 20, 20, Color.rgba8888(0, 1, 1, 1)); pixmap.drawRect(-10, 21, 20, 20, Color.rgba8888(0, 1, 1, 1)); pixmap.drawRect(21, 21, 20, 20, Color.rgba8888(0, 1, 1, 1)); - - pixmap.fillRect(-10, -10, 20, 20, Color.rgba8888(0, 1, 1, 0.5f)); + + pixmap.fillRect(-10, -10, 20, 20, Color.rgba8888(0, 1, 1, 0.5f)); pixmap.fillRect(21, -10, 20, 20, Color.rgba8888(0, 1, 1, 0.5f)); pixmap.fillRect(-10, 21, 20, 20, Color.rgba8888(0, 1, 1, 0.5f)); pixmap.fillRect(21, 21, 20, 20, Color.rgba8888(0, 1, 1, 0.5f)); } - - Gdx2DPixmap[] testPixmaps() { - int[] formats = { Gdx2DPixmap.GDX2D_FORMAT_ALPHA, - Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA, - Gdx2DPixmap.GDX2D_FORMAT_RGB565, - Gdx2DPixmap.GDX2D_FORMAT_RGB888, - Gdx2DPixmap.GDX2D_FORMAT_RGBA4444, - Gdx2DPixmap.GDX2D_FORMAT_RGBA8888 }; - + + Gdx2DPixmap[] testPixmaps () { + int[] formats = {Gdx2DPixmap.GDX2D_FORMAT_ALPHA, Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA, Gdx2DPixmap.GDX2D_FORMAT_RGB565, + Gdx2DPixmap.GDX2D_FORMAT_RGB888, Gdx2DPixmap.GDX2D_FORMAT_RGBA4444, Gdx2DPixmap.GDX2D_FORMAT_RGBA8888}; + Gdx2DPixmap[] pixmaps = new Gdx2DPixmap[formats.length]; - for(int i = 0; i < pixmaps.length; i++) { + for (int i = 0; i < pixmaps.length; i++) { Gdx2DPixmap pixmap = new Gdx2DPixmap(64, 32, formats[i]); drawToPixmap(pixmap); pixmaps[i] = pixmap; } return pixmaps; } - - @Override public void create () { + + @Override + public void create () { batch = new SpriteBatch(); - sprites = new ArrayList(); + sprites = new ArrayList(); Gdx2DPixmap[] pixmaps = testPixmaps(); - + Gdx2DPixmap composite = new Gdx2DPixmap(512, 256, Gdx2DPixmap.GDX2D_FORMAT_RGBA8888); composite.clear(0); Gdx2DPixmap.setBlend(Gdx2DPixmap.GDX2D_BLEND_NONE); - for(int i = 0; i < pixmaps.length; i++) { - Gdx2DPixmap.setScale(Gdx2DPixmap.GDX2D_SCALE_NEAREST); - composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 0, 64, 64); + for (int i = 0; i < pixmaps.length; i++) { + Gdx2DPixmap.setScale(Gdx2DPixmap.GDX2D_SCALE_NEAREST); + composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 0, 64, 64); composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 64, 16, 16); composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 0, 64, 64); composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 64, 16, 16); Gdx2DPixmap.setScale(Gdx2DPixmap.GDX2D_SCALE_LINEAR); - composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 100, 64, 64); + composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 100, 64, 64); composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 164, 16, 16); composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 100, 64, 64); composite.drawPixmap(pixmaps[i], 0, 0, 32, 32, i * 64, 164, 16, 16); Sprite sprite = new Sprite(textureFromPixmap(pixmaps[i])); sprite.setPosition(10 + i * 32, 10); sprites.add(sprite); - } - + } + Sprite sprite = new Sprite(textureFromPixmap(composite)); sprite.setPosition(10, 50); sprites.add(sprite); } - @Override public void render() { + @Override + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1.0f); - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); - for(int i = 0; i < sprites.size(); i++) { + for (int i = 0; i < sprites.size(); i++) { sprites.get(i).draw(batch); } batch.end(); } - - @Override public boolean needsGL20 () { + + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/GroupFadeTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/GroupFadeTest.java index 1cb559f6dc9..6113c1974d7 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/GroupFadeTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/GroupFadeTest.java @@ -13,6 +13,7 @@ * 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,28 +29,31 @@ public class GroupFadeTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - - Stage stage; - - @Override public void create() { + + Stage stage; + + @Override + public void create () { Texture texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); stage = new Stage(480, 320, true); - - for(int i = 0; i < 100; i++) { + + for (int i = 0; i < 100; i++) { Image img = new Image("img" + i, texture); img.x = (float)Math.random() * 480; img.y = (float)Math.random() * 320; img.color.a = (float)Math.random() * 0.5f + 0.5f; stage.addActor(img); } - + stage.getRoot().action(Forever.$(Sequence.$(FadeOut.$(3), FadeIn.$(3)))); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererAlphaTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererAlphaTest.java index ed334197e98..c147ad42454 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererAlphaTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererAlphaTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -25,66 +26,66 @@ import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer10; import com.badlogic.gdx.tests.utils.GdxTest; -public class ImmediateModeRendererAlphaTest extends GdxTest { - - ImmediateModeRenderer10 renderer; - - Texture background; - TextureRegion bgTR; - Sprite sprBg; - - SpriteBatch batcher; - - @Override - public void create() { - - this.background = new Texture(Gdx.files.internal("data/badlogic.jpg")); - - this.background.setFilter(TextureFilter.Linear, TextureFilter.Linear); - - this.bgTR = new TextureRegion(this.background, 0,0,256,256); - - this.sprBg = new Sprite(this.background,0,0,640,400); - - this.batcher = new SpriteBatch(); - - this.renderer = new ImmediateModeRenderer10(); - - } - - @Override - public void render() { - Gdx.gl.glClearColor(0.0f,0.0f,0.0f,1.0f); - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - - this.batcher.begin(); - this.batcher.draw(this.bgTR, 0.0f,0.0f); - this.batcher.end(); - - Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); - Gdx.gl.glEnable(GL10.GL_BLEND); - - renderer.begin(GL10.GL_LINE_STRIP); - - renderer.color(1.0f,0.0f,0.0f,0.5f); - renderer.vertex(20.0f,20.0f,0.0f); - renderer.color(1.0f,0.0f,0.0f,0.5f); - renderer.vertex(160.0f,20.0f,0.0f); - renderer.color(1.0f,0.0f,0.0f,0.5f); - renderer.vertex(160.0f,60.0f,0.0f); - renderer.color(1.0f,0.0f,0.0f,0.5f); - renderer.vertex(20.0f,60.0f,0.0f); - renderer.color(1.0f,0.0f,0.0f,0.5f); - renderer.vertex(20.0f,20.0f,0.0f); - - renderer.end(); - - Gdx.gl.glDisable(GL10.GL_BLEND); - - } - - @Override - public boolean needsGL20() { - return false; - } +public class ImmediateModeRendererAlphaTest extends GdxTest { + + ImmediateModeRenderer10 renderer; + + Texture background; + TextureRegion bgTR; + Sprite sprBg; + + SpriteBatch batcher; + + @Override + public void create () { + + this.background = new Texture(Gdx.files.internal("data/badlogic.jpg")); + + this.background.setFilter(TextureFilter.Linear, TextureFilter.Linear); + + this.bgTR = new TextureRegion(this.background, 0, 0, 256, 256); + + this.sprBg = new Sprite(this.background, 0, 0, 640, 400); + + this.batcher = new SpriteBatch(); + + this.renderer = new ImmediateModeRenderer10(); + + } + + @Override + public void render () { + Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + + this.batcher.begin(); + this.batcher.draw(this.bgTR, 0.0f, 0.0f); + this.batcher.end(); + + Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); + Gdx.gl.glEnable(GL10.GL_BLEND); + + renderer.begin(GL10.GL_LINE_STRIP); + + renderer.color(1.0f, 0.0f, 0.0f, 0.5f); + renderer.vertex(20.0f, 20.0f, 0.0f); + renderer.color(1.0f, 0.0f, 0.0f, 0.5f); + renderer.vertex(160.0f, 20.0f, 0.0f); + renderer.color(1.0f, 0.0f, 0.0f, 0.5f); + renderer.vertex(160.0f, 60.0f, 0.0f); + renderer.color(1.0f, 0.0f, 0.0f, 0.5f); + renderer.vertex(20.0f, 60.0f, 0.0f); + renderer.color(1.0f, 0.0f, 0.0f, 0.5f); + renderer.vertex(20.0f, 20.0f, 0.0f); + + renderer.end(); + + Gdx.gl.glDisable(GL10.GL_BLEND); + + } + + @Override + public boolean needsGL20 () { + return false; + } } 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 bcdc0d42bc1..ac4a813ecb9 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ImmediateModeRendererTest.java @@ -13,14 +13,12 @@ * 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.GL10; 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.glutils.ImmediateModeRenderer10; import com.badlogic.gdx.tests.utils.GdxTest; @@ -28,11 +26,13 @@ public class ImmediateModeRendererTest extends GdxTest { ImmediateModeRenderer10 renderer; Texture texture; - @Override public void dispose () { + @Override + public void dispose () { texture.dispose(); } - @Override public void render () { + @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(); @@ -49,12 +49,14 @@ public class ImmediateModeRendererTest extends GdxTest { renderer.end(); } - @Override public void create () { + @Override + public void create () { renderer = new ImmediateModeRenderer10(); texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectClassTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectClassTest.java index 152945d20db..855737d20ea 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectClassTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectClassTest.java @@ -13,16 +13,14 @@ * 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.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.GL11; 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; import com.badlogic.gdx.graphics.glutils.IndexBufferObject; @@ -34,17 +32,20 @@ public class IndexBufferObjectClassTest extends GdxTest { VertexBufferObject vbo; IndexBufferObject ibo; - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public void dispose () { + @Override + public void dispose () { texture.dispose(); vbo.dispose(); ibo.dispose(); } - @Override public void render () { + @Override + public void render () { GL11 gl = Gdx.gl11; gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); @@ -58,7 +59,8 @@ public class IndexBufferObjectClassTest extends GdxTest { vbo.unbind(); } - @Override public void create () { + @Override + public void create () { vbo = new VertexBufferObject(true, 3, new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_Position"), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_TexCoords"), new VertexAttribute( VertexAttributes.Usage.ColorPacked, 4, "a_Color")); @@ -72,7 +74,8 @@ public class IndexBufferObjectClassTest extends GdxTest { texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); } - @Override public void resume () { + @Override + public void resume () { vbo.invalidate(); ibo.invalidate(); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectShaderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectShaderTest.java index 7d150a99e4c..aa648f18e61 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectShaderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/IndexBufferObjectShaderTest.java @@ -13,22 +13,19 @@ * 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.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; -import com.badlogic.gdx.graphics.Texture.TextureFilter; -import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.glutils.IndexBufferObject; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.graphics.glutils.VertexBufferObject; import com.badlogic.gdx.tests.utils.GdxTest; -import com.badlogic.gdx.utils.BufferUtils; public class IndexBufferObjectShaderTest extends GdxTest { Texture texture; @@ -37,21 +34,21 @@ public class IndexBufferObjectShaderTest extends GdxTest { IndexBufferObject ibo; @Override - public boolean needsGL20() { + public boolean needsGL20 () { return true; } @Override - public void dispose() { + public void dispose () { texture.dispose(); shader.dispose(); ibo.dispose(); } @Override - public void render() { -// System.out.println( "render"); - + public void render () { +// System.out.println( "render"); + GL20 gl = Gdx.gl20; gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); gl.glClear(GL20.GL_COLOR_BUFFER_BIT); @@ -59,59 +56,44 @@ public void render() { gl.glEnable(GL20.GL_TEXTURE_2D); shader.begin(); shader.setUniformi("u_texture", 0); - texture.bind(); - vbo.bind(shader); + texture.bind(); + vbo.bind(shader); ibo.bind(); - gl.glDrawElements(GL20.GL_TRIANGLES, 3, GL20.GL_UNSIGNED_SHORT, 0); + gl.glDrawElements(GL20.GL_TRIANGLES, 3, GL20.GL_UNSIGNED_SHORT, 0); ibo.unbind(); vbo.unbind(shader); shader.end(); } @Override - public void create() { - 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;" - + "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 = a_position; \n" - + "} \n"; - String fragmentShader = "#ifdef GL_ES\n" - + "precision mediump float;\n" - + "#endif\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" - + "}"; + public void create () { + 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;" + "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 = a_position; \n" + "} \n"; + String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\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); - vbo = new VertexBufferObject(true, 3, - new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2,"a_texCoords"), - new VertexAttribute(VertexAttributes.Usage.ColorPacked, 4, "a_color")); - float[] vertices = new float[] { -1, -1, 0, 0,Color.toFloatBits(1f, 0f, 0f, 1f), - 0, 1, 0.5f, 1.0f, Color.toFloatBits(0f, 1f, 0f, 1f), - 1, -1, 1, 0, Color.toFloatBits(0f, 0f, 1f, 1f) }; - vbo.setVertices(vertices, 0, vertices.length); - - ibo = new IndexBufferObject(true, 3); - ibo.setIndices(new short[] { 0, 1, 2 }, 0, 3); + shader = new ShaderProgram(vertexShader, fragmentShader); + vbo = new VertexBufferObject(true, 3, new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"), + new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords"), new VertexAttribute( + VertexAttributes.Usage.ColorPacked, 4, "a_color")); + float[] vertices = new float[] {-1, -1, 0, 0, Color.toFloatBits(1f, 0f, 0f, 1f), 0, 1, 0.5f, 1.0f, + Color.toFloatBits(0f, 1f, 0f, 1f), 1, -1, 1, 0, Color.toFloatBits(0f, 0f, 1f, 1f)}; + vbo.setVertices(vertices, 0, vertices.length); - texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); + ibo = new IndexBufferObject(true, 3); + ibo.setIndices(new short[] {0, 1, 2}, 0, 3); + + texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); } - + @Override - public void resume() { + public void resume () { vbo.invalidate(); - ibo.invalidate(); + ibo.invalidate(); } } 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 edd1e33fb4f..1d469d0e99c 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/InputTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/InputTest.java @@ -13,92 +13,101 @@ * 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.InputProcessor; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.Input.Keys; +import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.input.RemoteInput; import com.badlogic.gdx.tests.utils.GdxTest; public class InputTest extends GdxTest implements InputProcessor { - @Override public void create () { + @Override + public void create () { Gdx.input = new RemoteInput(); Gdx.input.setInputProcessor(this); - } - - @Override public void render () { - if(Gdx.input.justTouched()) { - Gdx.app.log("Input Test", "just touched, button: " + (Gdx.input.isButtonPressed(Buttons.LEFT)?"left ":"") - + (Gdx.input.isButtonPressed(Buttons.MIDDLE)?"middle ":"") - + (Gdx.input.isButtonPressed(Buttons.RIGHT)?"right":"")); + } + + @Override + public void render () { + if (Gdx.input.justTouched()) { + Gdx.app.log("Input Test", "just touched, button: " + (Gdx.input.isButtonPressed(Buttons.LEFT) ? "left " : "") + + (Gdx.input.isButtonPressed(Buttons.MIDDLE) ? "middle " : "") + + (Gdx.input.isButtonPressed(Buttons.RIGHT) ? "right" : "")); } - - for(int i = 0; i < 10; i++) { - if(Gdx.input.getDeltaX(i) != 0 || Gdx.input.getDeltaY(i) != 0) { + + for (int i = 0; i < 10; i++) { + if (Gdx.input.getDeltaX(i) != 0 || Gdx.input.getDeltaY(i) != 0) { Gdx.app.log("Input Test", "delta[" + i + "]: " + Gdx.input.getDeltaX(i) + ", " + Gdx.input.getDeltaY(i)); } } -// Gdx.input.setCursorPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2); -// if(Gdx.input.isTouched()) { -// Gdx.app.log("Input Test", "is touched"); -// } +// Gdx.input.setCursorPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2); +// if(Gdx.input.isTouched()) { +// Gdx.app.log("Input Test", "is touched"); +// } } - @Override public boolean keyDown (int keycode) { + @Override + public boolean keyDown (int keycode) { Gdx.app.log("Input Test", "key down: " + keycode); - if(keycode == Keys.G) Gdx.input.setCursorCatched(!Gdx.input.isCursorCatched()); + if (keycode == Keys.G) Gdx.input.setCursorCatched(!Gdx.input.isCursorCatched()); return false; } - @Override public boolean keyTyped (char character) { + @Override + public boolean keyTyped (char character) { Gdx.app.log("Input Test", "key typed: '" + character + "'"); return false; } - @Override public boolean keyUp (int 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, int button) { - Gdx.app.log("Input Test", "touch down: " + x + ", " + y + ", button: " + getButtonString(button)); + + @Override + public boolean touchDown (int x, int y, int pointer, int button) { + Gdx.app.log("Input Test", "touch down: " + x + ", " + y + ", button: " + getButtonString(button)); return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { - Gdx.app.log("Input Test", "touch dragged: " + x + ", " + y + ", pointer: " + pointer); + @Override + public boolean touchDragged (int x, int y, int pointer) { + Gdx.app.log("Input Test", "touch dragged: " + x + ", " + y + ", pointer: " + pointer); return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { - Gdx.app.log("Input Test", "touch up: " + x + ", " + y + ", button: " + getButtonString(button)); + @Override + public boolean touchUp (int x, int y, int pointer, int button) { + Gdx.app.log("Input Test", "touch up: " + x + ", " + y + ", button: " + getButtonString(button)); return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { Gdx.app.log("Input Test", "touch moved: " + x + ", " + y); return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { Gdx.app.log("Input Test", "scrolled: " + amount); return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - - private String getButtonString(int button) { - if(button == Buttons.LEFT) - return "left"; - if(button == Buttons.RIGHT) - return "right"; - if(button == Buttons.MIDDLE) - return "middle"; + + private String getButtonString (int button) { + if (button == Buttons.LEFT) return "left"; + if (button == Buttons.RIGHT) return "right"; + if (button == Buttons.MIDDLE) return "middle"; return "left"; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/IntegerBitmapFontTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/IntegerBitmapFontTest.java index f2822302c9a..bc200816e15 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/IntegerBitmapFontTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/IntegerBitmapFontTest.java @@ -1,16 +1,18 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.g2d.BitmapFont; +import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.graphics.g2d.SpriteBatch; -import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.tests.utils.GdxTest; public class IntegerBitmapFontTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -20,8 +22,8 @@ public class IntegerBitmapFontTest extends GdxTest { BitmapFontCache singleLineCache; BitmapFontCache multiLineCache; SpriteBatch batch; - - public void create() { + + public void create () { font = new BitmapFont(); singleLineCache = new BitmapFontCache(font, true); multiLineCache = new BitmapFontCache(font, true); @@ -30,8 +32,8 @@ public void create() { batch = new SpriteBatch(); fillCaches(); } - - public void render() { + + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.setUseIntegerPositions(false); @@ -46,8 +48,8 @@ public void render() { drawTexts(); batch.end(); } - - private void fillCaches() { + + private void fillCaches () { String text = "This is a TEST\nxahsdhwekjhasd23§$%$%/%&"; singleLineCache.setColor(0, 0, 1, 1); singleLineCache.setText(text, 10.2f, 30.5f); @@ -58,10 +60,10 @@ private void fillCaches() { multiLineCacheNonInteger.setColor(0, 1, 0, 1); multiLineCacheNonInteger.setMultiLineText(text, 10.5f, 180.5f, 200, HAlignment.CENTER); } - - private void drawTexts() { + + private void drawTexts () { String text = "This is a TEST\nxahsdhwekjhasd23§$%$%/%&"; - font.draw(batch, text, 10.2f, 30.5f); + font.draw(batch, text, 10.2f, 30.5f); font.drawMultiLine(batch, text, 10.5f, 120.5f); font.drawMultiLine(batch, text, 10.5f, 180.5f, 200, HAlignment.CENTER); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/InverseKinematicsTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/InverseKinematicsTest.java index 6f8d22f06dc..44cb5729246 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/InverseKinematicsTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/InverseKinematicsTest.java @@ -1,17 +1,18 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer10; -import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.tests.utils.GdxTest; public class InverseKinematicsTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -19,94 +20,92 @@ static class Bone { final float len; final Vector3 position = new Vector3(); final Vector3 inertia = new Vector3(); - - public String name; - - public Bone(String name, float x, float y, float len) { + + public String name; + + public Bone (String name, float x, float y, float len) { this.name = name; this.position.set(x, y, 0); - this.len = len; - } - - public String toString() { + this.len = len; + } + + public String toString () { return "bone " + name + ": " + position + ", " + len; } } - + static final float GRAVITY = 0; OrthographicCamera camera; - ImmediateModeRenderer10 renderer; + ImmediateModeRenderer10 renderer; Bone[] bones; Vector3 globalCoords = new Vector3(); Vector3 endPoint = new Vector3(); Vector2 diff = new Vector2(); - - @Override public void create() { + + @Override + public void create () { float aspect = Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight(); camera = new OrthographicCamera(15 * aspect, 15); renderer = new ImmediateModeRenderer10(); - - bones = new Bone[] { new Bone("bone0", 0, 0, 0), - new Bone("bone1", 0, 2, 2), - new Bone("bone2", 0, 4, 2), - new Bone("bone3", 0, 6, 2), - new Bone("end", 0, 8, 2)}; - globalCoords.set(bones[0].position); + + bones = new Bone[] {new Bone("bone0", 0, 0, 0), new Bone("bone1", 0, 2, 2), new Bone("bone2", 0, 4, 2), + new Bone("bone3", 0, 6, 2), new Bone("end", 0, 8, 2)}; + globalCoords.set(bones[0].position); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + camera.update(); camera.apply(Gdx.gl10); - - if(Gdx.input.isTouched()) camera.unproject(globalCoords.set(Gdx.input.getX(), Gdx.input.getY(), 0)); + + if (Gdx.input.isTouched()) camera.unproject(globalCoords.set(Gdx.input.getX(), Gdx.input.getY(), 0)); solveFakeIK(globalCoords); renderBones(); } - - private void renderBones() { + + private void renderBones () { renderer.begin(GL10.GL_LINES); - for(int i = 0; i < bones.length - 1; i++) { + for (int i = 0; i < bones.length - 1; i++) { renderer.color(0, 1, 0, 1); renderer.vertex(bones[i].position); renderer.color(0, 1, 0, 1); - renderer.vertex(bones[i+1].position); + renderer.vertex(bones[i + 1].position); } renderer.end(); - - Gdx.gl10.glPointSize(5); - + + Gdx.gl10.glPointSize(5); + renderer.begin(GL10.GL_POINTS); - for(int i = 0; i < bones.length; i++) { + for (int i = 0; i < bones.length; i++) { renderer.color(1, 0, 0, 1); - renderer.vertex(bones[i].position); + renderer.vertex(bones[i].position); } renderer.end(); Gdx.gl10.glPointSize(1); - } - - - public void solveFakeIK(Vector3 target) { + } + + public void solveFakeIK (Vector3 target) { float gravity = Gdx.graphics.getDeltaTime() * GRAVITY; - + endPoint.set(target); bones[0].position.set(endPoint); - - for(int i = 0; i < bones.length - 1; i++) { + + for (int i = 0; i < bones.length - 1; i++) { Bone bone = bones[i]; - endPoint.set(bone.position); - - diff.set(endPoint.x, endPoint.y).sub(bones[i+1].position.x, bones[i+1].position.y); + endPoint.set(bone.position); + + diff.set(endPoint.x, endPoint.y).sub(bones[i + 1].position.x, bones[i + 1].position.y); diff.add(0, gravity); - diff.add(bones[i+1].inertia.x, bones[i+1].inertia.y); - diff.nor().mul(bones[i+1].len); - + diff.add(bones[i + 1].inertia.x, bones[i + 1].inertia.y); + diff.nor().mul(bones[i + 1].len); + float x = endPoint.x - diff.x; float y = endPoint.y - diff.y; float delta = Gdx.graphics.getDeltaTime(); - bones[i+1].inertia.add((bones[i+1].position.x - x) * delta, (bones[i+1].position.y - y) * delta, 0).mul(0.99f); - bones[i+1].position.set(x, y, 0); + bones[i + 1].inertia.add((bones[i + 1].position.x - x) * delta, (bones[i + 1].position.y - y) * delta, 0).mul(0.99f); + bones[i + 1].position.set(x, y, 0); } - } -} \ No newline at end of file + } +} diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/IsoCamTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/IsoCamTest.java index c85498e83db..5a4451c950a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/IsoCamTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/IsoCamTest.java @@ -13,11 +13,11 @@ * 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.InputAdapter; -import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; @@ -31,16 +31,17 @@ import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.tests.utils.GdxTest; -public class IsoCamTest extends GdxTest { +public class IsoCamTest extends GdxTest { private static final int TARGET_WIDTH = 480; private static final float UNIT_TO_PIXEL = TARGET_WIDTH * 0.15f; Texture texture; OrthographicCamera cam; - SpriteBatch batch; + SpriteBatch batch; final Sprite[][] sprites = new Sprite[10][10]; final Matrix4 matrix = new Matrix4(); - - @Override public void create() { + + @Override + public void create () { texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); float unitsOnX = (float)Math.sqrt(2) * TARGET_WIDTH / (UNIT_TO_PIXEL); float pixelsOnX = Gdx.graphics.getWidth() / unitsOnX; @@ -48,59 +49,60 @@ public class IsoCamTest extends GdxTest { cam = new OrthographicCamera(unitsOnX, unitsOnY, 25); cam.position.mul(30); cam.near = 1; - cam.far = 1000; + cam.far = 1000; matrix.setToRotation(new Vector3(1, 0, 0), 90); - - for(int z = 0; z < 10; z++) { - for(int x = 0; x < 10; x++) { + + for (int z = 0; z < 10; z++) { + for (int x = 0; x < 10; x++) { sprites[x][z] = new Sprite(texture); - sprites[x][z].setPosition(x,z); + sprites[x][z].setPosition(x, z); sprites[x][z].setSize(1, 1); } } - + batch = new SpriteBatch(); - + Gdx.input.setInputProcessor(new IsoCamController(cam)); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - cam.update(); - + cam.update(); + batch.setProjectionMatrix(cam.combined); batch.setTransformMatrix(matrix); batch.begin(); - for(int z = 0; z < 10; z++) { - for(int x = 0; x < 10; x++) { + for (int z = 0; z < 10; z++) { + for (int x = 0; x < 10; x++) { sprites[x][z].draw(batch); } } batch.end(); - + checkTileTouched(); } - + final Plane xzPlane = new Plane(new Vector3(0, 1, 0), 0); final Vector3 intersection = new Vector3(); Sprite lastSelectedTile = null; - - private void checkTileTouched() { - if(Gdx.input.justTouched()) { + + private void checkTileTouched () { + if (Gdx.input.justTouched()) { Ray pickRay = cam.getPickRay(Gdx.input.getX(), Gdx.input.getY()); Intersector.intersectRayPlane(pickRay, xzPlane, intersection); System.out.println(intersection); int x = (int)intersection.x; int z = (int)intersection.z; - if(x >= 0 && x < 10 && z >= 0 && z < 10) { - if(lastSelectedTile != null) lastSelectedTile.setColor(1, 1, 1, 1); + if (x >= 0 && x < 10 && z >= 0 && z < 10) { + if (lastSelectedTile != null) lastSelectedTile.setColor(1, 1, 1, 1); Sprite sprite = sprites[x][z]; sprite.setColor(1, 0, 0, 1); lastSelectedTile = sprite; } } } - + public class IsoCamController extends InputAdapter { final Plane xzPlane = new Plane(new Vector3(0, 1, 0), 0); final Vector3 intersection = new Vector3(); @@ -108,26 +110,28 @@ public class IsoCamController extends InputAdapter { final Vector3 last = new Vector3(-1, -1, -1); final Vector3 delta = new Vector3(); final Camera camera; - - public IsoCamController(Camera camera) { + + public IsoCamController (Camera camera) { this.camera = camera; } - - @Override public boolean touchDragged (int x, int y, int pointer) { + + @Override + public boolean touchDragged (int x, int y, int pointer) { Ray pickRay = camera.getPickRay(x, y); Intersector.intersectRayPlane(pickRay, xzPlane, curr); - - if(!(last.x == -1 && last.y == -1 && last.z == -1)) { + + if (!(last.x == -1 && last.y == -1 && last.z == -1)) { pickRay = camera.getPickRay(last.x, last.y); - Intersector.intersectRayPlane(pickRay, xzPlane, delta); + Intersector.intersectRayPlane(pickRay, xzPlane, delta); delta.sub(curr); camera.position.add(delta.x, 0, delta.z); } last.set(x, y, 0); return false; } - - @Override public boolean touchUp(int x, int y, int pointer, int button) { + + @Override + public boolean touchUp (int x, int y, int pointer, int button) { last.set(-1, -1, -1); return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/IsometricTileTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/IsometricTileTest.java index 76360e69eef..36390f26215 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/IsometricTileTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/IsometricTileTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -45,8 +46,9 @@ public class IsometricTileTest extends GdxTest { ImmediateModeRenderer10 renderer; long startTime = System.nanoTime(); - @Override public void create () { - cam = new OrthographicCamera(480, 320); + @Override + public void create () { + cam = new OrthographicCamera(480, 320); camController = new OrthoCamController(cam); Gdx.input.setInputProcessor(camController); @@ -75,11 +77,12 @@ public class IsometricTileTest extends GdxTest { } } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.gl10; gl.glClearColor(0.7f, 0.7f, 0.7f, 1); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - cam.update(); + cam.update(); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); @@ -114,7 +117,8 @@ public class IsometricTileTest extends GdxTest { renderer.end(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/KinematicBodyTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/KinematicBodyTest.java index 78466c0fb16..3e8f7fe921a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/KinematicBodyTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/KinematicBodyTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -30,7 +31,8 @@ public class KinematicBodyTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { 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 368efee5911..fceca5bff5d 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/LifeCycleTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/LifeCycleTest.java @@ -13,33 +13,35 @@ * 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.graphics.GL10; import com.badlogic.gdx.tests.utils.GdxTest; -/** - * A simple test to demonstrate the life cycle of an application. - * - * @author mzechner +/** A simple test to demonstrate the life cycle of an application. * - */ + * @author mzechner */ public class LifeCycleTest extends GdxTest { - @Override public void dispose () { + @Override + public void dispose () { Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app destroyed"); } - @Override public void pause () { + @Override + public void pause () { Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app paused"); } - @Override public void resume () { + @Override + public void resume () { Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app resumed"); } - @Override public void render () { + @Override + public void render () { Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT); try { Thread.sleep(100); @@ -48,16 +50,20 @@ public class LifeCycleTest extends GdxTest { } } - @Override public void create () { + @Override + public void create () { Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app created: " + Gdx.graphics.getWidth() + "x" - + Gdx.graphics.getHeight()); + + Gdx.graphics.getHeight()); } - @Override public void resize (int width, int height) { - Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app resized: " + width + "x" + height + ", Graphics says: "+ Gdx.graphics.getWidth() + "x" + Gdx.graphics.getHeight()); + @Override + public void resize (int width, int height) { + Gdx.app.log("Test", "Thread=" + Thread.currentThread().getId() + ", app resized: " + width + "x" + height + + ", Graphics says: " + Gdx.graphics.getWidth() + "x" + Gdx.graphics.getHeight()); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/LineDrawingTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/LineDrawingTest.java index 3f1e7d4f866..ffebd19cf87 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/LineDrawingTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/LineDrawingTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -6,13 +7,13 @@ import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; -import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.tests.utils.GdxTest; public class LineDrawingTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -21,42 +22,43 @@ public class LineDrawingTest extends GdxTest { Mesh lineMesh; float[] lineVertices; int vertexIndex = 0; - Vector3 unprojectedVertex = new Vector3(); - - @Override public void create() { + Vector3 unprojectedVertex = new Vector3(); + + @Override + public void create () { camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); lineMesh = new Mesh(false, MAX_LINES * 2, 0, new VertexAttribute(Usage.Position, 2, "a_pos")); lineVertices = new float[MAX_LINES * 2 * 2]; } - - @Override public void render() { + + @Override + public void render () { // clear screen Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 0.5f); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + // update the camera (not necessary as we don't change its properties) // and apply the projection and modelview matrix. camera.update(); camera.apply(Gdx.gl10); - - // render the lines so far, but only if we have at least 2 + + // render the lines so far, but only if we have at least 2 // vertices (== 4 floats, 2 floats per vertex, x/y position - if(vertexIndex >= 4) lineMesh.render(GL10.GL_LINE_STRIP); - - // if the screen was touched we add a new vertex to our + if (vertexIndex >= 4) lineMesh.render(GL10.GL_LINE_STRIP); + + // if the screen was touched we add a new vertex to our // mesh and hence a new line. But we only do that if the // last added vertex is further away than 10 units. - if(Gdx.input.isTouched()) { + if (Gdx.input.isTouched()) { unprojectedVertex.set(Gdx.input.getX(), Gdx.input.getY(), 0); camera.unproject(unprojectedVertex); - + // add the new vertex only if it's 1) the first vertex or 2) // it is farther away than 10 units from the last added vertex. - if(vertexIndex == 0 || - unprojectedVertex.dst(lineVertices[vertexIndex-2], lineVertices[vertexIndex - 1], 0) > 10) { + if (vertexIndex == 0 || unprojectedVertex.dst(lineVertices[vertexIndex - 2], lineVertices[vertexIndex - 1], 0) > 10) { lineVertices[vertexIndex++] = unprojectedVertex.x; - lineVertices[vertexIndex++] = unprojectedVertex.y; - lineMesh.setVertices(lineVertices, 0, vertexIndex); + lineVertices[vertexIndex++] = unprojectedVertex.y; + lineMesh.setVertices(lineVertices, 0, vertexIndex); } } else { // else we reset the vertexIndex to 0 so that no line is drawn any longer 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 6faff05941f..3ac0d98eac4 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MD5Test.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MD5Test.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -39,7 +40,8 @@ public class MD5Test extends GdxTest implements InputProcessor { SpriteBatch batch; BitmapFont font; - @Override public void create () { + @Override + public void create () { Gdx.app.log("MD5 Test", "created"); model = MD5Loader.loadModel(Gdx.files.internal("data/zfat.md5mesh").read(), false); anim = MD5Loader.loadAnimation(Gdx.files.internal("data/walk1.md5anim").read()); @@ -47,7 +49,7 @@ public class MD5Test extends GdxTest implements InputProcessor { skeleton.joints = new float[anim.frames[0].joints.length]; animInfo = new MD5AnimationInfo(anim.frames.length, anim.secondsPerFrame); renderer = new MD5Renderer(model, false, true); - renderer.setSkeleton(model.baseSkeleton); + renderer.setSkeleton(model.baseSkeleton); // long start = System.nanoTime(); // for( int i = 0; i < 100000; i++ ) @@ -56,9 +58,9 @@ public class MD5Test extends GdxTest implements InputProcessor { // 1000000000.0 ); camera = new PerspectiveCamera(60, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); - camera.position.set(0, 25, 100); + camera.position.set(0, 25, 100); camera.near = 1; - camera.far = 1000; + camera.far = 1000; batch = new SpriteBatch(); font = new BitmapFont(); @@ -69,7 +71,8 @@ public class MD5Test extends GdxTest implements InputProcessor { float angle = 0; - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); @@ -111,7 +114,8 @@ public class MD5Test extends GdxTest implements InputProcessor { batch.end(); } - @Override public void dispose () { + @Override + public void dispose () { batch.dispose(); renderer.dispose(); font.dispose(); @@ -123,40 +127,49 @@ public class MD5Test extends GdxTest implements InputProcessor { System.gc(); } - @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, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { renderer.setUseJni(!renderer.isJniUsed()); return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { 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 a36c80cc46a..705f36eb891 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ManagedTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ManagedTest.java @@ -13,15 +13,14 @@ * 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.GL10; import com.badlogic.gdx.graphics.Mesh; 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.Usage; import com.badlogic.gdx.tests.utils.GdxTest; @@ -30,17 +29,19 @@ public class ManagedTest extends GdxTest { Mesh mesh; Texture texture; - @Override public void create () { + @Override + public void create () { mesh = new Mesh(true, 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 = new Texture(Gdx.files.internal("data/badlogic.jpg"), true); - texture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); + texture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); } - @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); @@ -51,7 +52,8 @@ public class ManagedTest extends GdxTest { mesh.render(GL10.GL_TRIANGLE_FAN); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ManualBindTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ManualBindTest.java index da5b0f8c5f4..9e4a68dce63 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ManualBindTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ManualBindTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.FloatBuffer; @@ -33,11 +34,13 @@ public class ManualBindTest extends GdxTest { FloatBuffer vertices1; FloatBuffer vertices2; - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public void render () { + @Override + public void render () { GL11 gl = Gdx.gl11; gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); @@ -61,7 +64,8 @@ public class ManualBindTest extends GdxTest { gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } - @Override public void create () { + @Override + public void create () { GL11 gl = Gdx.graphics.getGL11(); IntBuffer handleBuf = BufferUtils.newIntBuffer(2); gl.glGenBuffers(2, handleBuf); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MatrixJNITest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MatrixJNITest.java index 3904107ac0f..f41394da54c 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MatrixJNITest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MatrixJNITest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -7,116 +8,118 @@ import com.badlogic.gdx.utils.GdxRuntimeException; public class MatrixJNITest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - - @Override public void create() { + + @Override + public void create () { Matrix4 mat1 = new Matrix4(); Matrix4 mat2 = new Matrix4(); Matrix4 mat3 = new Matrix4(); Vector3 vec = new Vector3(1, 2, 3); float[] fvec = {1, 2, 3}; - float[] fvecs = { 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0 }; - + float[] fvecs = {1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0}; + mat1.setToRotation(0, 1, 0, 45); mat2.setToRotation(1, 0, 0, 45); - + vec.mul(mat1); Matrix4.mulVec(mat1.val, fvec); Matrix4.mulVec(mat1.val, fvecs, 0, 3, 5); check(vec, fvec); check(vec, fvecs, 3, 5); - + vec.prj(mat1); Matrix4.prj(mat1.val, fvec); Matrix4.prj(mat1.val, fvecs, 0, 3, 5); check(vec, fvec); check(vec, fvecs, 3, 5); - + vec.rot(mat1); Matrix4.rot(mat1.val, fvec); Matrix4.rot(mat1.val, fvecs, 0, 3, 5); check(vec, fvec); check(vec, fvecs, 3, 5); - - if(mat1.det() != Matrix4.det(mat1.val)) throw new GdxRuntimeException("det doesn't work"); - + + if (mat1.det() != Matrix4.det(mat1.val)) throw new GdxRuntimeException("det doesn't work"); + mat2.set(mat1); mat1.inv(); Matrix4.inv(mat2.val); check(mat1, mat2); - + mat3.set(mat1); mat1.mul(mat2); Matrix4.mul(mat3.val, mat2.val); check(mat1, mat3); - + bench(); } - - private void bench() { + + private void bench () { Matrix4 mata = new Matrix4(); Matrix4 matb = new Matrix4(); - + long start = System.nanoTime(); - for(int i = 0; i < 1000000; i++) { + for (int i = 0; i < 1000000; i++) { mata.mul(matb); } Gdx.app.log("MatrixJNITest", "java matrix * matrix took: " + (System.nanoTime() - start) / 1000000000.0f); - + start = System.nanoTime(); - for(int i = 0; i < 1000000; i++) { + for (int i = 0; i < 1000000; i++) { Matrix4.mul(mata.val, matb.val); } Gdx.app.log("MatrixJNITest", "jni matrix * matrix took: " + (System.nanoTime() - start) / 1000000000.0f); - + Vector3 vec = new Vector3(); start = System.nanoTime(); - for(int i = 0; i < 500000; i++) { - vec.mul(mata); + for (int i = 0; i < 500000; i++) { + vec.mul(mata); } Gdx.app.log("MatrixJNITest", "java vecs * matrix took: " + (System.nanoTime() - start) / 1000000000.0f); - + float[] fvec = new float[3]; start = System.nanoTime(); - for(int i = 0; i < 500000; i++) { - Matrix4.mulVec(mata.val, fvec); + for (int i = 0; i < 500000; i++) { + Matrix4.mulVec(mata.val, fvec); } Gdx.app.log("MatrixJNITest", "jni vecs * matrix took: " + (System.nanoTime() - start) / 1000000000.0f); - + float[] fvecs = new float[3 * 500000]; - start = System.nanoTime(); - Matrix4.mulVec(mata.val, fvecs, 0, 500000, 3); + start = System.nanoTime(); + Matrix4.mulVec(mata.val, fvecs, 0, 500000, 3); Gdx.app.log("MatrixJNITest", "jni bulk vecs * matrix took: " + (System.nanoTime() - start) / 1000000000.0f); - + start = System.nanoTime(); - for(int i = 0; i < 1000000; i++) { + for (int i = 0; i < 1000000; i++) { mata.inv(); } Gdx.app.log("MatrixJNITest", "java inv(matrix): " + (System.nanoTime() - start) / 1000000000.0f); - + start = System.nanoTime(); - for(int i = 0; i < 1000000; i++) { + for (int i = 0; i < 1000000; i++) { Matrix4.inv(mata.val); } Gdx.app.log("MatrixJNITest", "jni inv(matrix): " + (System.nanoTime() - start) / 1000000000.0f); } - - private void check(Vector3 vec, float[] fvec) { - if(vec.x != fvec[0] || vec.y != fvec[1] || vec.z != fvec[2]) throw new GdxRuntimeException("vectors are not equal"); + + private void check (Vector3 vec, float[] fvec) { + if (vec.x != fvec[0] || vec.y != fvec[1] || vec.z != fvec[2]) throw new GdxRuntimeException("vectors are not equal"); } - - private void check(Vector3 vec, float[] fvec, int numVecs, int stride) { + + private void check (Vector3 vec, float[] fvec, int numVecs, int stride) { int offset = 0; - for(int i = 0; i < numVecs; i++) { - if(vec.x != fvec[0] || vec.y != fvec[1] || vec.z != fvec[2]) throw new GdxRuntimeException("vectors are not equal"); + for (int i = 0; i < numVecs; i++) { + if (vec.x != fvec[0] || vec.y != fvec[1] || vec.z != fvec[2]) throw new GdxRuntimeException("vectors are not equal"); } } - - private void check(Matrix4 mat1, Matrix4 mat2) { - for(int i = 0; i < 16; i++) { - if(mat1.val[i] != mat2.val[i]) throw new GdxRuntimeException("matrices not equal"); + + private void check (Matrix4 mat1, Matrix4 mat2) { + for (int i = 0; i < 16; i++) { + if (mat1.val[i] != mat2.val[i]) throw new GdxRuntimeException("matrices not equal"); } } } 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 2c8abb585f6..85ec7d5745d 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshMultitextureTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshMultitextureTest.java @@ -13,17 +13,14 @@ * 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.graphics.GL10; import com.badlogic.gdx.graphics.GL11; import com.badlogic.gdx.graphics.Mesh; -import com.badlogic.gdx.graphics.Pixmap; -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; import com.badlogic.gdx.tests.utils.GdxTest; @@ -33,42 +30,41 @@ public class MeshMultitextureTest extends GdxTest { Texture tex2; Mesh mesh; - @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.glClear(GL10.GL_COLOR_BUFFER_BIT); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glEnable(GL10.GL_TEXTURE_2D); tex1.bind(); - + gl.glActiveTexture(GL10.GL_TEXTURE1); gl.glEnable(GL10.GL_TEXTURE_2D); - tex2.bind(); + tex2.bind(); Gdx.gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL11.GL_COMBINE); Gdx.gl11.glTexEnvi(GL10.GL_TEXTURE_ENV, GL11.GL_COMBINE_RGB, GL11.GL_ADD); - + mesh.render(GL10.GL_TRIANGLES); } - @Override public void create () { - mesh = new Mesh(true, 4, 6, - new VertexAttribute(VertexAttributes.Usage.Position, 3,"a_Position"), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords1"), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords2")); + @Override + public void create () { + mesh = new Mesh(true, 4, 6, new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_Position"), new VertexAttribute( + VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords1"), new VertexAttribute( + VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords2")); - mesh.setVertices(new float[] { -0.5f, -0.5f, 0, 0, 1, 0, 1, - 0.5f, -0.5f, 0, 1, 1, 1, 1, - 0.5f, 0.5f, 0, 1, 0, 1, 0, - -0.5f, 0.5f, 0, 0, 0, 0, 0 - }); - mesh.setIndices(new short[] { 0, 1, 2, 2, 3, 0 }); + mesh.setVertices(new float[] {-0.5f, -0.5f, 0, 0, 1, 0, 1, 0.5f, -0.5f, 0, 1, 1, 1, 1, 0.5f, 0.5f, 0, 1, 0, 1, 0, -0.5f, + 0.5f, 0, 0, 0, 0, 0}); + mesh.setIndices(new short[] {0, 1, 2, 2, 3, 0}); tex1 = new Texture(Gdx.files.internal("data/planet_earth.png")); tex2 = new Texture(Gdx.files.internal("data/planet_heavyclouds.jpg")); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } 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 b16d3b8b40b..3726d485f3d 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshShaderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshShaderTest.java @@ -13,18 +13,14 @@ * 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.GL10; 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.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.Usage; import com.badlogic.gdx.graphics.g2d.SpriteBatch; @@ -42,27 +38,16 @@ public class MeshShaderTest extends GdxTest { Matrix4 matrix = new Matrix4(); @Override - public void create() { - 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(1, 1, 1, 1); \n" - + " v_texCoords = a_texCoords; \n" - + " gl_Position = u_worldView * a_position; \n" - + "} \n"; - String fragmentShader = "#ifdef GL_ES\n" - + "precision mediump float;\n" - + "#endif\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" - + "}"; + public void create () { + 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(1, 1, 1, 1); \n" + + " v_texCoords = a_texCoords; \n" + " gl_Position = u_worldView * a_position; \n" + + "} \n"; + String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\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) { @@ -70,25 +55,22 @@ public void create() { System.exit(0); } - mesh = new Mesh(true, 4, 6, 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, 1, 1, 1, 0, 1, - 0.5f, -0.5f, 0, 1, 1, 1, 1, 1, 1, - 0.5f, 0.5f, 0, 1, 1, 1, 1, 1, 0, - -0.5f, 0.5f, 0, 1, 1, 1, 1, 0, 0}); - mesh.setIndices(new short[] { 0, 1, 2, 2, 3, 0 }); + mesh = new Mesh(true, 4, 6, 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, 1, 1, 1, 0, 1, 0.5f, -0.5f, 0, 1, 1, 1, 1, 1, 1, 0.5f, 0.5f, 0, 1, 1, 1, + 1, 1, 0, -0.5f, 0.5f, 0, 1, 1, 1, 1, 0, 0}); + mesh.setIndices(new short[] {0, 1, 2, 2, 3, 0}); -// Pixmap pixmap = new Pixmap(2, 1, Format.RGBA8888); -// pixmap.drawPixel(0, 0, 0xffff0000); -// pixmap.drawPixel(1, 0, 0xff00ff00); -// pixmap.drawPixel(0, 1, 0xff0000ff); -// pixmap.drawPixel(0, 0, 0xffff00ff); -// pixmap.drawPixel(1, 0, 0xffffff00); -// texture = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); -// pixmap.dispose(); +// Pixmap pixmap = new Pixmap(2, 1, Format.RGBA8888); +// pixmap.drawPixel(0, 0, 0xffff0000); +// pixmap.drawPixel(1, 0, 0xff00ff00); +// pixmap.drawPixel(0, 1, 0xff0000ff); +// pixmap.drawPixel(0, 0, 0xffff00ff); +// pixmap.drawPixel(1, 0, 0xffffff00); +// texture = Gdx.graphics.newUnmanagedTexture(pixmap, TextureFilter.Nearest, TextureFilter.Nearest, TextureWrap.ClampToEdge, +// TextureWrap.ClampToEdge); +// pixmap.dispose(); texture = new Texture(Gdx.files.internal("data/bobrgb888-32x32.png")); spriteBatch = new SpriteBatch(); @@ -99,12 +81,11 @@ public void create() { float angle = 0; @Override - public void render() { + 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().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); @@ -123,7 +104,7 @@ public void render() { } @Override - public boolean needsGL20() { + public boolean needsGL20 () { return true; } 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 0f18fb8ce3f..1e31d8a9e7b 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MeshTest.java @@ -13,16 +13,15 @@ * 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.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; 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.Usage; import com.badlogic.gdx.tests.utils.GdxTest; @@ -31,7 +30,8 @@ public class MeshTest extends GdxTest { Mesh mesh; Texture texture; - @Override public void render () { + @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()); Gdx.graphics.getGL10().glEnable(GL10.GL_TEXTURE_2D); @@ -39,7 +39,8 @@ public class MeshTest extends GdxTest { mesh.render(GL10.GL_TRIANGLES, 3, 3); } - @Override public void create () { + @Override + public void create () { mesh = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 3, "a_position"), new VertexAttribute(Usage.ColorPacked, 4, "a_color"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoords")); @@ -52,7 +53,8 @@ public class MeshTest extends GdxTest { texture.setFilter(TextureFilter.MipMap, TextureFilter.Linear); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MipMapTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MipMapTest.java index e3e587d93dd..9ce4d46c48a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MipMapTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MipMapTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -17,16 +18,16 @@ import com.badlogic.gdx.scenes.scene2d.ui.ComboBox; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; -import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.PerspectiveCamController; import com.badlogic.gdx.utils.GdxRuntimeException; public class MipMapTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } - + PerspectiveCamera camera; PerspectiveCamController controller; Mesh mesh; @@ -39,81 +40,78 @@ public class MipMapTest extends GdxTest { ComboBox minFilter; ComboBox magFilter; CheckBox hwMipMap; - - @Override public void create() { + + @Override + public void create () { camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.position.set(0, 1.5f, 1.5f); camera.lookAt(0, 0, 0); camera.update(); - controller = new PerspectiveCamController(camera); - - mesh = new Mesh(true, 4, 4, new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), - new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE)); - mesh.setVertices(new float[] { - -1, 0, 1, 0, 1, - 1, 0, 1, 1, 1, - 1, 0, -1, 1, 0, - -1, 0, -1, 0, 0, - }); - mesh.setIndices(new short[] { 0, 1, 2, 3 } ); - - shader = new ShaderProgram(Gdx.files.internal("data/shaders/flattex-vert.glsl").readString(), - Gdx.files.internal("data/shaders/flattex-frag.glsl").readString()); - if(!shader.isCompiled()) throw new GdxRuntimeException("shader error: " + shader.getLog()); - + controller = new PerspectiveCamController(camera); + + mesh = new Mesh(true, 4, 4, new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute( + Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE)); + mesh.setVertices(new float[] {-1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, -1, 1, 0, -1, 0, -1, 0, 0,}); + mesh.setIndices(new short[] {0, 1, 2, 3}); + + shader = new ShaderProgram(Gdx.files.internal("data/shaders/flattex-vert.glsl").readString(), Gdx.files.internal( + "data/shaders/flattex-frag.glsl").readString()); + if (!shader.isCompiled()) throw new GdxRuntimeException("shader error: " + shader.getLog()); + textureHW = new Texture(Gdx.files.internal("data/badlogic.jpg"), Format.RGB565, true); MipMapGenerator.setUseHardwareMipMap(false); textureSW = new Texture(Gdx.files.internal("data/badlogic.jpg"), Format.RGB565, true); currTexture = textureHW; - + createUI(); - + multiplexer = new InputMultiplexer(); - Gdx.input.setInputProcessor(multiplexer); + Gdx.input.setInputProcessor(multiplexer); multiplexer.addProcessor(ui); multiplexer.addProcessor(controller); } - - private void createUI() { + + private void createUI () { Skin skin = new Skin(Gdx.files.internal("data/uiskin.xml"), Gdx.files.internal("data/uiskin.png")); - ui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); - + ui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); + String[] filters = new String[TextureFilter.values().length]; int idx = 0; - for(TextureFilter filter: TextureFilter.values()) { + for (TextureFilter filter : TextureFilter.values()) { filters[idx++] = filter.toString(); } hwMipMap = skin.newCheckBox("hardware", "Hardware Mips"); minFilter = skin.newComboBox("minfilter", filters, ui); - magFilter = skin.newComboBox("magfilter", new String[] { "Nearest", "Linear" }, ui); - + magFilter = skin.newComboBox("magfilter", new String[] {"Nearest", "Linear"}, ui); + Table table = new Table("container", (int)ui.width(), 30); table.y = ui.height() - 30; table.add(hwMipMap).spaceRight(5); table.add(skin.newLabel("lbl1", "Min Filter")).spaceRight(5); table.add(minFilter).spaceRight(5); table.add(skin.newLabel("lbl1", "Mag Filter")).spaceRight(5); - table.add(magFilter); + table.add(magFilter); - ui.addActor(table); + ui.addActor(table); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); Gdx.gl.glEnable(GL10.GL_TEXTURE_2D); - + camera.update(); - - currTexture = hwMipMap.isChecked()?textureHW:textureSW; - currTexture.bind(); + + currTexture = hwMipMap.isChecked() ? textureHW : textureSW; + currTexture.bind(); currTexture.setFilter(TextureFilter.valueOf(minFilter.getSelection()), TextureFilter.valueOf(magFilter.getSelection())); - + shader.begin(); shader.setUniformMatrix("u_projTrans", camera.combined); shader.setUniformi("s_texture", 0); mesh.render(shader, GL10.GL_TRIANGLE_FAN); shader.end(); - + ui.draw(); } } 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 b05f1091d1e..84126f9a983 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.FloatBuffer; @@ -27,7 +28,8 @@ public class Mpg123Test extends GdxTest { - @Override public void create () { + @Override + public void create () { // Thread thread = new Thread( new Runnable() { // // public void run( ) @@ -61,7 +63,8 @@ public class Mpg123Test extends GdxTest { // thread.start(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MultiTouchActorTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MultiTouchActorTest.java index 45f5fad6ff1..5551679c340 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MultiTouchActorTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MultiTouchActorTest.java @@ -1,91 +1,109 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.input.RemoteInput; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actors.Button; import com.badlogic.gdx.tests.utils.GdxTest; -import com.badlogic.gdx.utils.GdxRuntimeException; - + public class MultiTouchActorTest extends GdxTest implements InputProcessor { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - + class LogButton extends Button { public LogButton (String name, Texture texture) { super(name, texture); - } - - @Override public boolean touchUp (float x, float y, int pointer) { + } + + @Override + public boolean touchUp (float x, float y, int pointer) { boolean result = super.touchUp(x, y, pointer); - if(result) Gdx.app.log("MultiTouchActorTest", "button '" + name + "', touch up, pointer " + pointer); + if (result) Gdx.app.log("MultiTouchActorTest", "button '" + name + "', touch up, pointer " + pointer); return result; } - - @Override public boolean touchDown (float x, float y, int pointer) { + + @Override + public boolean touchDown (float x, float y, int pointer) { boolean result = super.touchDown(x, y, pointer); - if(result) Gdx.app.log("MultiTouchActorTest", "button '" + name + "', touch down, pointer " + pointer); + if (result) Gdx.app.log("MultiTouchActorTest", "button '" + name + "', touch down, pointer " + pointer); return result; } } - + Stage stage; Texture texture; private LogButton buttonB; - - public void create() { -// Gdx.input = new RemoteInput(); + + public void create () { +// Gdx.input = new RemoteInput(); Gdx.input.setInputProcessor(this); - + stage = new Stage(480, 320, true); texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); - + LogButton buttonA = new LogButton("A", texture); buttonB = new LogButton("B", texture); - + buttonA.width = buttonA.height = buttonB.width = buttonB.height = 100; buttonB.x = 480 - buttonB.width; - + stage.addActor(buttonA); stage.addActor(buttonB); } - - public void render() { + + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - stage.act(Gdx.graphics.getDeltaTime()); + stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); } - @Override public boolean touchDown (int x, int y, int pointer, int button) { + @Override + public boolean touchDown (int x, int y, int pointer, int button) { stage.touchDown(x, y, pointer, button); return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { stage.touchUp(x, y, pointer, button); return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { stage.touchDragged(x, y, pointer); return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { stage.touchMoved(x, y); return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { + return false; + } + + @Override + public boolean keyDown (int keycode) { + return false; + } + + @Override + public boolean keyUp (int keycode) { + return false; + } + + @Override + public boolean keyTyped (char character) { return false; } - - @Override public boolean keyDown (int keycode) { return false; } - @Override public boolean keyUp (int keycode) { return false; } - @Override public boolean keyTyped (char character) { return false; } } 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 1e81a107ced..395f84b3971 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MultitouchTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MultitouchTest.java @@ -13,11 +13,12 @@ * 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.InputProcessor; import com.badlogic.gdx.Input.Peripheral; +import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; @@ -31,7 +32,8 @@ public class MultitouchTest extends GdxTest implements InputProcessor { Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.WHITE}; - @Override public void render () { + @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.update(); @@ -54,56 +56,66 @@ public class MultitouchTest extends GdxTest implements InputProcessor { renderer.end(); -// if (System.nanoTime() - startTime > 1000000000l) { -// Gdx.app.log("MultiTouhTest", "fps:" + Gdx.graphics.getFramesPerSecond()); -// startTime = System.nanoTime(); -// } +// if (System.nanoTime() - startTime > 1000000000l) { +// Gdx.app.log("MultiTouhTest", "fps:" + Gdx.graphics.getFramesPerSecond()); +// startTime = System.nanoTime(); +// } } - @Override public void create () { + @Override + public void create () { Gdx.app.log("Multitouch", "multitouch supported: " + Gdx.input.isPeripheralAvailable(Peripheral.MultitouchScreen)); renderer = new ImmediateModeRenderer10(); - camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.position.set(Gdx.graphics.getWidth() / 2.0f, Gdx.graphics.getHeight() / 2.0f, 0); Gdx.input.setInputProcessor(this); } - @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, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { // Gdx.app.log("Multitouch", "down: " + pointer); return false; } - @Override public boolean touchDragged (int x, int y, int 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, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { // Gdx.app.log("Multitouch", "up: " + pointer); return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MusicTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MusicTest.java index bc269f34a2c..76963b4aa22 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MusicTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MusicTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -26,49 +27,56 @@ public class MusicTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - static final int NUM_STREAMS = 1; + static final int NUM_STREAMS = 1; Music[] music = new Music[NUM_STREAMS]; TextureRegion buttons; SpriteBatch batch; - BitmapFont font; - - @Override public void create() { - for(int i = 0; i < music.length; i++) { + BitmapFont font; + + @Override + public void create () { + for (int i = 0; i < music.length; i++) { music[i] = Gdx.audio.newMusic(Gdx.files.internal("data/cloudconnected.ogg")); -// music = Gdx.audio.newMusic(Gdx.files.internal("data/sell_buy_item.wav")); -// music[i] = Gdx.audio.newMusic(Gdx.files.internal("data/threeofaperfectpair.mp3")); +// music = Gdx.audio.newMusic(Gdx.files.internal("data/sell_buy_item.wav")); +// music[i] = Gdx.audio.newMusic(Gdx.files.internal("data/threeofaperfectpair.mp3")); } - + buttons = new TextureRegion(new Texture(Gdx.files.internal("data/playback.png"))); batch = new SpriteBatch(); font = new BitmapFont(); } - - @Override public void resize(int width, int height) { + + @Override + public void resize (int width, int height) { batch.getProjectionMatrix().setToOrtho2D(0, 0, width, height); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(buttons, 0, 0); - font.draw(batch, "\"Three of a perfect pair: " + music[0].getPosition(), 10, Gdx.graphics.getHeight() - 20); - batch.end(); - - if(Gdx.input.justTouched()) { - if(Gdx.input.getY() > Gdx.graphics.getHeight() - 64) { - if(Gdx.input.getX() < 64) { - for(int i = 0; i < music.length; i++) music[i].play(); + font.draw(batch, "\"Three of a perfect pair: " + music[0].getPosition(), 10, Gdx.graphics.getHeight() - 20); + batch.end(); + + if (Gdx.input.justTouched()) { + if (Gdx.input.getY() > Gdx.graphics.getHeight() - 64) { + if (Gdx.input.getX() < 64) { + for (int i = 0; i < music.length; i++) + music[i].play(); } - if(Gdx.input.getX() > 64 && Gdx.input.getX() < 128) { - for(int i = 0; i < music.length; i++) music[i].stop(); + if (Gdx.input.getX() > 64 && Gdx.input.getX() < 128) { + for (int i = 0; i < music.length; i++) + music[i].stop(); } - if(Gdx.input.getX() > 128 && Gdx.input.getX() < 192) { - for(int i = 0; i < music.length; i++) music[i].pause(); + if (Gdx.input.getX() > 128 && Gdx.input.getX() < 192) { + for (int i = 0; i < music.length; i++) + music[i].pause(); } } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/MyFirstTriangle.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/MyFirstTriangle.java index 633d256b8e0..97a7f735ad1 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/MyFirstTriangle.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/MyFirstTriangle.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -25,7 +26,8 @@ public class MyFirstTriangle extends GdxTest { private Mesh mesh; - @Override public void create () { + @Override + public void create () { if (mesh == null) { mesh = new Mesh(true, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position")); @@ -34,14 +36,18 @@ public class MyFirstTriangle extends GdxTest { } } - @Override public void dispose () { + @Override + public void dispose () { } - @Override public void pause () { + @Override + public void pause () { } int renderCount = 0; - @Override public void render () { + + @Override + public void render () { renderCount++; Gdx.app.log("RenderCountTest", String.valueOf(renderCount)); Gdx.gl10.glClear(GL10.GL_COLOR_BUFFER_BIT); @@ -50,16 +56,19 @@ public class MyFirstTriangle extends GdxTest { Thread.sleep(2000); } catch (InterruptedException e) { Gdx.app.log("RenderCountTest", e.toString()); - } + } } - @Override public void resize (int width, int height) { + @Override + public void resize (int width, int height) { } - @Override public void resume () { + @Override + public void resume () { } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { 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 dd72eab4847..a1e38ce904c 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ObjTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ObjTest.java @@ -13,18 +13,16 @@ * 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.InputProcessor; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; -import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.PerspectiveCamera; 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.g3d.loaders.ModelLoaderOld; import com.badlogic.gdx.tests.utils.GdxTest; @@ -39,7 +37,8 @@ public class ObjTest extends GdxTest implements InputProcessor { float touchStartX = 0; float touchStartY = 0; - @Override public void create () { + @Override + public void create () { mesh = ModelLoaderOld.loadObj(Gdx.files.internal("data/cube.obj").read()); Gdx.app.log("ObjTest", "obj bounds: " + mesh.calculateBoundingBox()); texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), true); @@ -51,7 +50,8 @@ public class ObjTest extends GdxTest implements InputProcessor { Gdx.input.setInputProcessor(this); } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); @@ -64,7 +64,7 @@ public class ObjTest extends GdxTest implements InputProcessor { cam.update(); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); -// Gdx.graphics.getGLU().gluPerspective(Gdx.gl10, 45, 1, 1, 100); +// Gdx.graphics.getGLU().gluPerspective(Gdx.gl10, 45, 1, 1, 100); gl.glLoadMatrixf(cam.projection.val, 0); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadMatrixf(cam.view.val, 0); @@ -79,25 +79,30 @@ public class ObjTest extends GdxTest implements InputProcessor { mesh.render(GL10.GL_TRIANGLES); } - @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, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { 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; @@ -105,19 +110,23 @@ public class ObjTest extends GdxTest implements InputProcessor { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/OldUITest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/OldUITest.java index 81e1c6bc8ee..084054c7985 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/OldUITest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/OldUITest.java @@ -13,17 +13,14 @@ * 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.InputProcessor; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Input.Peripheral; +import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.GL10; 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.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; @@ -31,7 +28,6 @@ import com.badlogic.gdx.scenes.scene2d.actions.Delay; import com.badlogic.gdx.scenes.scene2d.actions.FadeIn; import com.badlogic.gdx.scenes.scene2d.actions.FadeOut; -import com.badlogic.gdx.scenes.scene2d.actions.Forever; import com.badlogic.gdx.scenes.scene2d.actions.MoveBy; import com.badlogic.gdx.scenes.scene2d.actions.MoveTo; import com.badlogic.gdx.scenes.scene2d.actions.Parallel; @@ -41,9 +37,9 @@ import com.badlogic.gdx.scenes.scene2d.actions.ScaleTo; import com.badlogic.gdx.scenes.scene2d.actions.Sequence; import com.badlogic.gdx.scenes.scene2d.actors.Button; +import com.badlogic.gdx.scenes.scene2d.actors.Button.ClickListener; import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.scenes.scene2d.actors.LinearGroup; -import com.badlogic.gdx.scenes.scene2d.actors.Button.ClickListener; import com.badlogic.gdx.scenes.scene2d.actors.LinearGroup.LinearGroupLayout; import com.badlogic.gdx.tests.utils.GdxTest; @@ -54,7 +50,8 @@ public class OldUITest extends GdxTest implements InputProcessor { // Font font; - @Override public void create () { + @Override + public void create () { // Gdx.input.setCatchBackKey(true); // font = Gdx.graphics.newFont( "Droid Sans", 20, FontStyle.Plain ); @@ -91,7 +88,8 @@ public class OldUITest extends GdxTest implements InputProcessor { Sequence.$(ScaleTo.$(0.1f, 0.1f, 1.5f), ScaleTo.$(1.0f, 1.0f, 1.5f)))); button.clickListener = new ClickListener() { - @Override public void clicked (Button button) { + @Override + public void clicked (Button button) { if (Gdx.input.isPeripheralAvailable(Peripheral.OnscreenKeyboard)) Gdx.input.setOnscreenKeyboardVisible(true); } }; @@ -124,22 +122,26 @@ public class OldUITest extends GdxTest implements InputProcessor { Gdx.input.setInputProcessor(this); } - @Override public void render () { - GL10 gl = Gdx.graphics.getGL10(); - gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + @Override + public void render () { + GL10 gl = Gdx.graphics.getGL10(); + gl.glClear(GL10.GL_COLOR_BUFFER_BIT); ui.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30.0f)); ui.draw(); } - @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) { return false; } - @Override public boolean keyTyped (char character) { + @Override + public boolean keyTyped (char character) { // Label label = ((Label)ui.findActor( "label" )); // if( character == '\b' ) { // if( label.text.length() > "text input: ".length() ) @@ -150,14 +152,16 @@ public class OldUITest extends GdxTest implements InputProcessor { return false; } - @Override public boolean touchDown (int x, int y, int pointer, int button) { + @Override + public boolean touchDown (int x, int y, int pointer, int button) { ui.touchDown(x, y, pointer, button); return false; } Vector2 point = new Vector2(); - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { if (!ui.touchUp(x, y, pointer, button)) { Actor actor = ui.findActor("image1"); if (actor != null) { @@ -174,20 +178,24 @@ public class OldUITest extends GdxTest implements InputProcessor { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { ui.touchDragged(x, y, pointer); return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/OnscreenKeyboardTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/OnscreenKeyboardTest.java index da6e10a49cc..3ee780438a4 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/OnscreenKeyboardTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/OnscreenKeyboardTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -9,72 +10,81 @@ public class OnscreenKeyboardTest extends GdxTest implements InputProcessor { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } BitmapFont font; String text; SpriteBatch batch; - - public void create() { + + public void create () { batch = new SpriteBatch(); font = new BitmapFont(); text = ""; Gdx.input.setInputProcessor(this); Gdx.input.setOnscreenKeyboardVisible(true); } - - public void render() { + + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.draw(batch, "input: " + text, 0, Gdx.graphics.getHeight()); batch.end(); - - if(Gdx.input.justTouched()) Gdx.input.setOnscreenKeyboardVisible(true); + + if (Gdx.input.justTouched()) Gdx.input.setOnscreenKeyboardVisible(true); } - @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) { return false; } - @Override public boolean keyTyped (char character) { - if(character == '\b' && text.length() >= 1) { - text = text.substring(0, text.length()-1); - } else if(character == '\n' ) { + @Override + public boolean keyTyped (char character) { + if (character == '\b' && text.length() >= 1) { + text = text.substring(0, text.length() - 1); + } else if (character == '\n') { Gdx.input.setOnscreenKeyboardVisible(false); - } else { + } else { text += character; } return false; } - @Override public boolean touchDown (int x, int y, int pointer, int button) { + @Override + public boolean touchDown (int x, int y, int pointer, int button) { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { // 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 touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { // TODO Auto-generated method stub return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { // TODO Auto-generated method stub return false; - } + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java index 52ea6d26e75..fa655d67aa6 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -26,7 +27,8 @@ public class OrthoCamBorderTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -41,7 +43,7 @@ public void create () { mesh.setVertices(new float[] {0, 0, 1, 0, 0, 1, WIDTH, 0, 0, 1, 0, 1, WIDTH, HEIGHT, 0, 0, 1, 1, 0, HEIGHT, 1, 0, 1, 1}); mesh.setIndices(new short[] {0, 1, 2, 2, 3, 0}); - cam = new OrthographicCamera(WIDTH, HEIGHT); + cam = new OrthographicCamera(WIDTH, HEIGHT); cam.position.set(WIDTH / 2, HEIGHT / 2, 0); glViewport = calculateGLViewport(WIDTH, HEIGHT); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ParallaxTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ParallaxTest.java index 0849b2ac71c..a50c132af84 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ParallaxTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ParallaxTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -13,105 +14,108 @@ import com.badlogic.gdx.tests.utils.OrthoCamController; public class ParallaxTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } - + class ParallaxCamera extends OrthographicCamera { Matrix4 parallaxView = new Matrix4(); Matrix4 parallaxCombined = new Matrix4(); Vector3 tmp = new Vector3(); Vector3 tmp2 = new Vector3(); - - public ParallaxCamera(float viewportWidth, float viewportHeight) { + + public ParallaxCamera (float viewportWidth, float viewportHeight) { super(viewportWidth, viewportHeight); } - - public Matrix4 calculateParallaxMatrix(float parallaxX, float parallaxY) { - update(); + + public Matrix4 calculateParallaxMatrix (float parallaxX, float parallaxY) { + update(); tmp.set(position); tmp.x *= parallaxX; tmp.y *= parallaxY; - - parallaxView.setToLookAt(tmp, tmp2.set(tmp).add(direction), up); + + parallaxView.setToLookAt(tmp, tmp2.set(tmp).add(direction), up); parallaxCombined.set(projection); Matrix4.mul(parallaxCombined.val, parallaxView.val); return parallaxCombined; } } - + TextureRegion[] layers; ParallaxCamera camera; OrthoCamController controller; SpriteBatch batch; BitmapFont font; - - @Override public void create() { + + @Override + public void create () { Texture texture = new Texture(Gdx.files.internal("data/layers.png")); layers = new TextureRegion[3]; - layers[0] = new TextureRegion(texture, 0, 0, 542, 363); + layers[0] = new TextureRegion(texture, 0, 0, 542, 363); layers[1] = new TextureRegion(texture, 0, 363, 1024, 149); layers[2] = new TextureRegion(texture, 547, 0, 224, 51); - + camera = new ParallaxCamera(480, 320); controller = new OrthoCamController(camera); Gdx.input.setInputProcessor(controller); batch = new SpriteBatch(); font = new BitmapFont(); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClearColor(242 / 255.0f, 210 / 255.0f, 111 / 255.0f, 1); - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + // keep camera in foreground layer bounds boolean updateCamera = false; - if(camera.position.x < -1024 + camera.viewportWidth / 2) { + if (camera.position.x < -1024 + camera.viewportWidth / 2) { camera.position.x = -1024 + (int)(camera.viewportWidth / 2); updateCamera = true; } - - if(camera.position.x > 1024 - camera.viewportWidth / 2) { + + if (camera.position.x > 1024 - camera.viewportWidth / 2) { camera.position.x = 1024 - (int)(camera.viewportWidth / 2); updateCamera = true; } - - if(camera.position.y < 0) { + + if (camera.position.y < 0) { camera.position.y = 0; updateCamera = true; } // arbitrary height of scene - if(camera.position.y > 400 - camera.viewportHeight / 2) { + if (camera.position.y > 400 - camera.viewportHeight / 2) { camera.position.y = 400 - (int)(camera.viewportHeight / 2); updateCamera = true; - } - + } + // background layer, no parallax, centered around origin batch.setProjectionMatrix(camera.calculateParallaxMatrix(0, 0)); batch.disableBlending(); - batch.begin(); + batch.begin(); batch.draw(layers[0], -(int)(layers[0].getRegionWidth() / 2), -(int)(layers[0].getRegionHeight() / 2)); batch.end(); batch.enableBlending(); - + // midground layer, 0.5 parallax (move at half speed on x, full speed on y) // layer is 1024x320 - batch.setProjectionMatrix(camera.calculateParallaxMatrix(0.5f, 1)); - batch.begin(); + batch.setProjectionMatrix(camera.calculateParallaxMatrix(0.5f, 1)); + batch.begin(); batch.draw(layers[1], -512, -160); - batch.end(); - + batch.end(); + // foreground layer, 1.0 parallax (move at full speed) // layer is 2048x320 batch.setProjectionMatrix(camera.calculateParallaxMatrix(1f, 1)); batch.begin(); - for(int i = 0; i < 9; i++) { + for (int i = 0; i < 9; i++) { batch.draw(layers[2], i * layers[2].getRegionWidth() - 1024, -160); } - batch.end(); - + batch.end(); + // draw fps - batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.begin(); font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond(), 0, 30); batch.end(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ParticleEmitterTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ParticleEmitterTest.java index c9bc4692297..4a461fe6706 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ParticleEmitterTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ParticleEmitterTest.java @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.tests; -import java.util.ArrayList; +package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; @@ -36,7 +35,8 @@ public class ParticleEmitterTest extends GdxTest { float fpsCounter; InputProcessor inputProcessor; - @Override public void create () { + @Override + public void create () { spriteBatch = new SpriteBatch(); effect = new ParticleEffect(); @@ -90,11 +90,13 @@ else if (keycode == Input.Keys.SPACE) { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } }; diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/PickingTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/PickingTest.java index 7dee50bb0f2..0962002d3ca 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/PickingTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/PickingTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -34,7 +35,8 @@ public class PickingTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -44,52 +46,54 @@ public class PickingTest extends GdxTest { static int VP_WIDTH; static int VP_HEIGHT; Mesh sphere; - Camera cam; + Camera cam; Vector3[] positions = new Vector3[100]; ImmediateModeRenderer10 renderer; SpriteBatch batch; Texture logo; - - @Override public void create() { + + @Override + public void create () { VP_WIDTH = Gdx.graphics.getWidth() - 4 * BORDER; VP_HEIGHT = Gdx.graphics.getHeight() - 4 * BORDER; sphere = ObjLoader.loadObj(Gdx.files.internal("data/sphere.obj").read()); cam = new PerspectiveCamera(45, VP_WIDTH, VP_HEIGHT); -// cam = new OrthographicCamera(10, 10); +// cam = new OrthographicCamera(10, 10); cam.far = 200; batch = new SpriteBatch(); logo = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); Random rand = new Random(10); - for(int i = 0; i < positions.length; i++) { - positions[i] = new Vector3(rand.nextFloat() * 100 - rand.nextFloat() * 100, - rand.nextFloat() * 100 - rand.nextFloat() * 100, - rand.nextFloat() * 100 - rand.nextFloat() * 100); - } + for (int i = 0; i < positions.length; i++) { + positions[i] = new Vector3(rand.nextFloat() * 100 - rand.nextFloat() * 100, rand.nextFloat() * 100 - rand.nextFloat() + * 100, rand.nextFloat() * 100 - rand.nextFloat() * 100); + } positions[0].set(0, 0, -10); renderer = new ImmediateModeRenderer10(); } Vector3 intersection = new Vector3(); - @Override public void render() { + + @Override + public void render () { GL10 gl = Gdx.gl10; - + gl.glClearColor(0.2f, 0.2f, 0.2f, 1.0f); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glEnable(GL10.GL_DEPTH_TEST); - + cam.update(); cam.apply(gl); gl.glViewport(VP_X, VP_Y, VP_WIDTH, VP_HEIGHT); - + Ray pickRay = null; - if(Gdx.input.isTouched()) { + if (Gdx.input.isTouched()) { pickRay = cam.getPickRay(Gdx.input.getX(), Gdx.input.getY(), VP_X, VP_Y, VP_WIDTH, VP_HEIGHT); -// Gdx.app.log("PickingTest", "ray: " + pickRay); +// Gdx.app.log("PickingTest", "ray: " + pickRay); } - + boolean intersected = false; - for(int i = 0; i < positions.length; i++) { - if(pickRay != null && Intersector.intersectRaySphere(pickRay, positions[i], 1, intersection)) { + for (int i = 0; i < positions.length; i++) { + if (pickRay != null && Intersector.intersectRaySphere(pickRay, positions[i], 1, intersection)) { gl.glColor4f(1, 0, 0, 1); intersected = true; } else { @@ -100,15 +104,15 @@ public class PickingTest extends GdxTest { sphere.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); } - + Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.begin(); - if(intersected) { + if (intersected) { cam.project(intersection, VP_X, VP_Y, VP_WIDTH, VP_HEIGHT); - batch.draw(logo, intersection.x, intersection.y); + batch.draw(logo, intersection.x, intersection.y); } batch.end(); - + renderer.begin(GL10.GL_LINE_LOOP); renderer.color(1, 1, 1, 1); renderer.vertex(VP_X, VP_Y, 0); @@ -119,10 +123,8 @@ public class PickingTest extends GdxTest { renderer.color(1, 1, 1, 1); renderer.vertex(VP_X, VP_Y + VP_HEIGHT, 0); renderer.end(); - - if(Gdx.input.isKeyPressed(Keys.A)) - cam.rotate(20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); - if(Gdx.input.isKeyPressed(Keys.D)) - cam.rotate(-20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); - } + + if (Gdx.input.isKeyPressed(Keys.A)) cam.rotate(20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); + if (Gdx.input.isKeyPressed(Keys.D)) cam.rotate(-20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); + } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixelsPerInchTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixelsPerInchTest.java index 070c151eeb5..c3ddde245da 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixelsPerInchTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixelsPerInchTest.java @@ -13,14 +13,12 @@ * 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.GL10; 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.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; @@ -31,7 +29,8 @@ public class PixelsPerInchTest extends GdxTest { SpriteBatch batch; Texture texture; - @Override public void create () { + @Override + public void create () { font = new BitmapFont(); batch = new SpriteBatch(); texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); @@ -50,7 +49,8 @@ public void render () { batch.end(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapBlendingTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapBlendingTest.java index 98d9082e253..5e9a5be7162 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapBlendingTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapBlendingTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Files; @@ -21,8 +22,6 @@ import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Pixmap; 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.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Matrix4; @@ -36,7 +35,8 @@ public class PixmapBlendingTest extends GdxTest { InputProcessor inputProcessor; - @Override public void create () { + @Override + public void create () { if (spriteBatch != null) return; spriteBatch = new SpriteBatch(); @@ -54,13 +54,14 @@ public class PixmapBlendingTest extends GdxTest { logoSprite = new Sprite(new Texture(pixD)); logoSprite.flip(false, true); - + pixS1.dispose(); pixS2.dispose(); pixD.dispose(); } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glClearColor(0, 1, 0, 1); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapTest.java index 45e18a08b6f..1f953c36a56 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -25,7 +26,8 @@ public class PixmapTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -33,47 +35,47 @@ public class PixmapTest extends GdxTest { Texture texture; SpriteBatch batch; TextureRegion region; - - public void create() { - // Create an empty dynamic pixmap - pixmap = new Pixmap (800, 480, Pixmap.Format.RGBA8888); // Pixmap.Format.RGBA8888); - // Create a texture to contain the pixmap - texture = new Texture (1024, 1024, Pixmap.Format.RGBA8888); //Pixmap.Format.RGBA8888); - texture.setFilter (Texture.TextureFilter.Nearest, Texture.TextureFilter.Linear); - texture.setWrap (Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge); - - pixmap.setColor(1.0f, 0.0f, 0.0f, 1.0f); // Red - pixmap.drawLine(0, 0, 100, 100); - - pixmap.setColor(0.0f, 0.0f, 1.0f, 1.0f); // Blue - pixmap.drawLine(100, 100, 200, 0); - - pixmap.setColor(0.0f, 1.0f, 0.0f, 1.0f); // Green - pixmap.drawLine(100, 0, 100, 100); - - pixmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); // White - pixmap.drawCircle(400, 300, 100); - - // Blit the composited overlay to a texture - texture.draw (pixmap, 0,0); - region = new TextureRegion(texture, 0, 0, 800, 480); - batch = new SpriteBatch(); - - Pixmap pixmap = new Pixmap(512,1024,Pixmap.Format.RGBA8888); - for (int y = 0; y < pixmap.getHeight(); y++) { //1024 - for (int x = 0; x < pixmap.getWidth(); x++) { //512 - pixmap.getPixel(x, y); - } - } - pixmap.dispose(); + public void create () { + // Create an empty dynamic pixmap + pixmap = new Pixmap(800, 480, Pixmap.Format.RGBA8888); // Pixmap.Format.RGBA8888); + + // Create a texture to contain the pixmap + texture = new Texture(1024, 1024, Pixmap.Format.RGBA8888); // Pixmap.Format.RGBA8888); + texture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Linear); + texture.setWrap(Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge); + + pixmap.setColor(1.0f, 0.0f, 0.0f, 1.0f); // Red + pixmap.drawLine(0, 0, 100, 100); + + pixmap.setColor(0.0f, 0.0f, 1.0f, 1.0f); // Blue + pixmap.drawLine(100, 100, 200, 0); + + pixmap.setColor(0.0f, 1.0f, 0.0f, 1.0f); // Green + pixmap.drawLine(100, 0, 100, 100); + + pixmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); // White + pixmap.drawCircle(400, 300, 100); + + // Blit the composited overlay to a texture + texture.draw(pixmap, 0, 0); + region = new TextureRegion(texture, 0, 0, 800, 480); + batch = new SpriteBatch(); + + Pixmap pixmap = new Pixmap(512, 1024, Pixmap.Format.RGBA8888); + for (int y = 0; y < pixmap.getHeight(); y++) { // 1024 + for (int x = 0; x < pixmap.getWidth(); x++) { // 512 + pixmap.getPixel(x, y); + } + } + pixmap.dispose(); } - - public void render() { + + public void render () { Gdx.gl.glClearColor(0.6f, 0.6f, 0.6f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); - batch.draw (region, 0, 0); + batch.draw(region, 0, 0); batch.end(); } } 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 1aa98a94d91..44b52e13d6a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Pong.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Pong.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -25,12 +26,9 @@ import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.tests.utils.GdxTest; -/** - * A simple Pong remake showing how easy it is to quickly prototype a game with libgdx. - * - * @author mzechner +/** A simple Pong remake showing how easy it is to quickly prototype a game with libgdx. * - */ + * @author mzechner */ public class Pong extends GdxTest { /** the camera **/ private OrthographicCamera camera; @@ -64,18 +62,15 @@ public class Pong extends GdxTest { /** score string **/ private String score = ""; - /** - * Here we setup all the resources. A MeshRenderer for the paddles which we use for both, a MeshRenderer for the ball and a - * Text for rendering the score. - */ - @Override public void create () { + /** Here we setup all the resources. A MeshRenderer for the paddles which we use for both, a MeshRenderer for the ball and a + * Text for rendering the score. */ + @Override + public void create () { 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 */ private void setupGraphics () { // // We first construct the paddle mesh which consists of @@ -108,12 +103,10 @@ private void setupGraphics () { // 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(480, 320); + camera = new OrthographicCamera(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); @@ -121,7 +114,8 @@ private void setupGame () { ballDirection.set(-1, 0); } - @Override public void render () { + @Override + public void render () { // we update the game state so things move. updateGame(); @@ -165,9 +159,7 @@ private void setupGame () { 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. */ private void updateGame () { // the delta time so we can do frame independant time based movement float deltaTime = Gdx.graphics.getDeltaTime(); @@ -262,7 +254,8 @@ private void updateGame () { } } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/PreferencesTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/PreferencesTest.java index 82f9e65fcc8..947a44663ef 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/PreferencesTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/PreferencesTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -22,12 +23,13 @@ public class PreferencesTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { // TODO Auto-generated method stub return false; } - - public void create() { + + public void create () { Preferences prefs = Gdx.app.getPreferences(".test"); prefs.clear(); prefs.putBoolean("bool", true); @@ -35,11 +37,11 @@ public void create() { prefs.putLong("long", Long.MAX_VALUE); prefs.putFloat("float", 1.2345f); prefs.putString("string", "test!"); - - if(prefs.getBoolean("bool") != true) throw new GdxRuntimeException("bool failed"); - if(prefs.getInteger("int") != 1234) throw new GdxRuntimeException("int failed"); - if(prefs.getLong("long") != Long.MAX_VALUE) throw new GdxRuntimeException("long failed"); - if(prefs.getFloat("float") != 1.2345f) throw new GdxRuntimeException("float failed"); - if(!prefs.getString("string").equals("test!")) throw new GdxRuntimeException("string failed"); + + if (prefs.getBoolean("bool") != true) throw new GdxRuntimeException("bool failed"); + if (prefs.getInteger("int") != 1234) throw new GdxRuntimeException("int failed"); + if (prefs.getLong("long") != Long.MAX_VALUE) throw new GdxRuntimeException("long failed"); + if (prefs.getFloat("float") != 1.2345f) throw new GdxRuntimeException("float failed"); + if (!prefs.getString("string").equals("test!")) throw new GdxRuntimeException("string failed"); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectTest.java index fe1c0b146b4..2fb0a486cb7 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -33,7 +34,8 @@ public class ProjectTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -44,38 +46,38 @@ public class ProjectTest extends GdxTest { Vector3[] positions = new Vector3[100]; Vector3 tmp = new Vector3(); TextureRegion logo; - - @Override public void create() { + + @Override + public void create () { sphere = ObjLoader.loadObj(Gdx.files.internal("data/sphere.obj").read()); cam = new PerspectiveCamera(45, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.far = 200; Random rand = new Random(); - for(int i = 0; i < positions.length; i++) { - positions[i] = new Vector3(rand.nextFloat() * 100 - rand.nextFloat() * 100, - rand.nextFloat() * 100 - rand.nextFloat() * 100, - rand.nextFloat() * -100 - 3); + for (int i = 0; i < positions.length; i++) { + positions[i] = new Vector3(rand.nextFloat() * 100 - rand.nextFloat() * 100, rand.nextFloat() * 100 - rand.nextFloat() + * 100, rand.nextFloat() * -100 - 3); } batch = new SpriteBatch(); font = new BitmapFont(); - logo = new TextureRegion(new Texture(Gdx.files.internal("data/badlogicsmall.jpg"))); + logo = new TextureRegion(new Texture(Gdx.files.internal("data/badlogicsmall.jpg"))); } - - @Override public void render() { + + @Override + public void render () { GL10 gl = Gdx.gl10; - + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glEnable(GL10.GL_DEPTH_TEST); - + cam.update(); cam.apply(gl); - + int visible = 0; - for(int i = 0; i < positions.length; i++) { - if(cam.frustum.sphereInFrustum(positions[i], 1)) { + for (int i = 0; i < positions.length; i++) { + if (cam.frustum.sphereInFrustum(positions[i], 1)) { gl.glColor4f(1, 1, 1, 1); visible++; - } - else { + } else { gl.glColor4f(1, 0, 0, 1); } gl.glPushMatrix(); @@ -83,18 +85,16 @@ public class ProjectTest extends GdxTest { sphere.render(GL10.GL_TRIANGLES); gl.glPopMatrix(); } - - if(Gdx.input.isKeyPressed(Keys.A)) - cam.rotate(20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); - if(Gdx.input.isKeyPressed(Keys.D)) - cam.rotate(-20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); - + + if (Gdx.input.isKeyPressed(Keys.A)) cam.rotate(20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); + if (Gdx.input.isKeyPressed(Keys.D)) cam.rotate(-20 * Gdx.graphics.getDeltaTime(), 0, 1, 0); + gl.glDisable(GL10.GL_DEPTH_TEST); batch.begin(); - for(int i = 0; i < positions.length; i++) { - tmp.set(positions[i]); + for (int i = 0; i < positions.length; i++) { + tmp.set(positions[i]); cam.project(tmp); - if(tmp.z < 0) continue; + if (tmp.z < 0) continue; batch.draw(logo, tmp.x, tmp.y); } batch.end(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectiveTextureTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectiveTextureTest.java index 2333f5fbd15..de2718615f1 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectiveTextureTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ProjectiveTextureTest.java @@ -1,6 +1,5 @@ -package com.badlogic.gdx.tests; -import java.awt.Container; +package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; @@ -25,14 +24,14 @@ import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; -import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.PerspectiveCamController; import com.badlogic.gdx.utils.GdxRuntimeException; public class ProjectiveTextureTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } @@ -42,118 +41,121 @@ public class ProjectiveTextureTest extends GdxTest { Mesh plane; Mesh cube; Matrix4 planeTrans = new Matrix4(); - Matrix4 cubeTrans = new Matrix4(); + Matrix4 cubeTrans = new Matrix4(); Matrix4 modelNormal = new Matrix4(); ShaderProgram projTexShader; Stage ui; InputMultiplexer multiplexer = new InputMultiplexer(); PerspectiveCamController controller; ImmediateModeRenderer20 renderer; - + float angle = 0; - - @Override public void create() { + + @Override + public void create () { setupScene(); setupUI(); setupShaders(); - + multiplexer.addProcessor(ui); multiplexer.addProcessor(controller); Gdx.input.setInputProcessor(multiplexer); - + renderer = new ImmediateModeRenderer20(false, true, 0); } - - public void setupScene() { - plane = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), - new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); - plane.setVertices(new float[] { -10, -1, 10, 0, 1, 0, - 10, -1, 10, 0, 1, 0, - 10, -1, -10, 0, 1, 0, - -10, -1, -10, 0, 1, 0 }); - plane.setIndices(new short[] { 3, 2, 1, 1, 0, 3 }); - cube = ModelLoaderOld.loadObj(Gdx.files.internal("data/sphere.obj").read()); + + public void setupScene () { + plane = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE), new VertexAttribute( + Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); + plane.setVertices(new float[] {-10, -1, 10, 0, 1, 0, 10, -1, 10, 0, 1, 0, 10, -1, -10, 0, 1, 0, -10, -1, -10, 0, 1, 0}); + plane.setIndices(new short[] {3, 2, 1, 1, 0, 3}); + cube = ModelLoaderOld.loadObj(Gdx.files.internal("data/sphere.obj").read()); texture = new Texture(Gdx.files.internal("data/badlogic.jpg"), Format.RGB565, true); texture.setFilter(TextureFilter.MipMap, TextureFilter.Nearest); - + cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0, 5, 10); - cam.lookAt(0, 0, 0); + cam.lookAt(0, 0, 0); cam.update(); - controller = new PerspectiveCamController(cam); - + controller = new PerspectiveCamController(cam); + projector = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); projector.position.set(2, 3, 2); - projector.lookAt(0, 0, 0); - projector.normalizeUp(); + projector.lookAt(0, 0, 0); + projector.normalizeUp(); projector.update(); } - - public void setupUI() { + + public void setupUI () { ui = new Stage(480, 320, false); Skin skin = new Skin(Gdx.files.internal("data/uiskin.xml"), Gdx.files.internal("data/uiskin.png")); Button reload = skin.newButton("reload", "Reload Shaders"); - ComboBox camera = skin.newComboBox("camera", new String[] { "Camera", "Light" }, ui); + ComboBox camera = skin.newComboBox("camera", new String[] {"Camera", "Light"}, ui); Label fps = skin.newLabel("fps", "fps: "); - + Table table = new Table("container", (int)ui.width(), (int)ui.height()); table.add(reload).spaceRight(5); table.add(camera).spaceRight(5); table.add(fps); ui.addActor(table); - - reload.setClickListener(new ClickListener() { - @Override public void click (Button button) { - ShaderProgram prog = new ShaderProgram(Gdx.files.internal("data/shaders/projtex-vert.glsl").readString(), Gdx.files.internal("data/shaders/projtex-frag.glsl").readString()); - if(prog.isCompiled() == false) { + + reload.setClickListener(new ClickListener() { + @Override + public void click (Button button) { + ShaderProgram prog = new ShaderProgram(Gdx.files.internal("data/shaders/projtex-vert.glsl").readString(), Gdx.files + .internal("data/shaders/projtex-frag.glsl").readString()); + if (prog.isCompiled() == false) { Gdx.app.log("GLSL ERROR", "Couldn't reload shaders:\n" + prog.getLog()); } else { projTexShader.dispose(); projTexShader = prog; } } - }); + }); } - - public void setupShaders() { + + public void setupShaders () { ShaderProgram.pedantic = false; - projTexShader = new ShaderProgram(Gdx.files.internal("data/shaders/projtex-vert.glsl").readString(), Gdx.files.internal("data/shaders/projtex-frag.glsl").readString()); - if(!projTexShader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + projTexShader.getLog()); + projTexShader = new ShaderProgram(Gdx.files.internal("data/shaders/projtex-vert.glsl").readString(), Gdx.files.internal( + "data/shaders/projtex-frag.glsl").readString()); + if (!projTexShader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shader: " + projTexShader.getLog()); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); - + angle += Gdx.graphics.getDeltaTime() * 20.0f; - cubeTrans.setToRotation(Vector3.Y, angle); - + cubeTrans.setToRotation(Vector3.Y, angle); + cam.update(); projector.update(); - + texture.bind(); projTexShader.begin(); - - if(((ComboBox)ui.findActor("camera")).getSelectionIndex() == 0) { + + if (((ComboBox)ui.findActor("camera")).getSelectionIndex() == 0) { renderMesh(projTexShader, cam.combined, projector.combined, planeTrans, plane, Color.WHITE); renderMesh(projTexShader, cam.combined, projector.combined, cubeTrans, cube, Color.WHITE); } else { renderMesh(projTexShader, projector.combined, projector.combined, planeTrans, plane, Color.WHITE); renderMesh(projTexShader, projector.combined, projector.combined, cubeTrans, cube, Color.WHITE); } - - projTexShader.end(); - + + projTexShader.end(); + Label label = (Label)ui.findActor("fps"); label.setText("fps: " + Gdx.graphics.getFramesPerSecond()); ui.draw(); } - - Vector3 position = new Vector3(); - private void renderMesh(ShaderProgram shader, Matrix4 cam, Matrix4 projector, Matrix4 model, Mesh mesh, Color color) { + + Vector3 position = new Vector3(); + + private void renderMesh (ShaderProgram shader, Matrix4 cam, Matrix4 projector, Matrix4 model, Mesh mesh, Color color) { position.set(this.projector.position); modelNormal.set(model).toNormalMatrix(); - + shader.setUniformMatrix("u_camera", cam); shader.setUniformMatrix("u_projector", projector); shader.setUniformf("u_projectorPos", position.x, position.y, position.z); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/RemoteTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/RemoteTest.java index 34e140e3f2e..80a8cc49d8a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/RemoteTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/RemoteTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Arrays; @@ -27,43 +28,43 @@ import com.badlogic.gdx.input.RemoteInput; import com.badlogic.gdx.tests.utils.GdxTest; -public class RemoteTest extends GdxTest implements ApplicationListener, InputProcessor { +public class RemoteTest extends GdxTest implements ApplicationListener, InputProcessor { BitmapFont font; SpriteBatch batch; ImmediateModeRenderer10 renderer; String ips; - - @Override public void create () { - RemoteInput receiver = new RemoteInput(); - Gdx.input = receiver; - + + @Override + public void create () { + RemoteInput receiver = new RemoteInput(); + Gdx.input = receiver; + ips = Arrays.toString(receiver.getIPs()); - Gdx.input.setInputProcessor(this); + Gdx.input.setInputProcessor(this); batch = new SpriteBatch(); font = new BitmapFont(); renderer = new ImmediateModeRenderer10(); } - @Override public void resume () { - + @Override + public void resume () { + } - @Override public void render () { + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); - font.drawMultiLine(batch, "ip: " + ips + "\n" + - "accel:" + Gdx.input.getAccelerometerX() + "," + - Gdx.input.getAccelerometerY() + "," + - Gdx.input.getAccelerometerZ() + "\n" + - "compass: " + Gdx.input.getAzimuth() + "," + - Gdx.input.getPitch() + "," + - Gdx.input.getRoll() + "\n" + - "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 130); + font.drawMultiLine( + batch, + "ip: " + ips + "\n" + "accel:" + Gdx.input.getAccelerometerX() + "," + Gdx.input.getAccelerometerY() + "," + + Gdx.input.getAccelerometerZ() + "\n" + "compass: " + Gdx.input.getAzimuth() + "," + Gdx.input.getPitch() + "," + + Gdx.input.getRoll() + "\n" + "fps: " + Gdx.graphics.getFramesPerSecond(), 10, 130); batch.end(); - + renderer.begin(GL10.GL_TRIANGLES); - for(int i = 0; i < 10; i++) { - if(Gdx.input.isTouched(i)) { + for (int i = 0; i < 10; i++) { + if (Gdx.input.isTouched(i)) { renderer.color(1, 0, 0, 0); renderer.vertex(Gdx.input.getX(i) - 20, Gdx.graphics.getHeight() - Gdx.input.getY(i) - 20, 0); renderer.color(1, 0, 0, 0); @@ -74,48 +75,57 @@ public class RemoteTest extends GdxTest implements ApplicationListener, InputPro } renderer.end(); } - - @Override public boolean keyDown (int keycode) { + + @Override + public boolean keyDown (int keycode) { Gdx.app.log("Input Test", "key down: " + keycode); return false; } - @Override public boolean keyTyped (char character) { + @Override + public boolean keyTyped (char character) { Gdx.app.log("Input Test", "key typed: '" + character + "'"); return false; } - @Override public boolean keyUp (int 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, int button) { - Gdx.app.log("Input Test", "touch down: " + x + ", " + y + ", pointer: " + pointer); + + @Override + public boolean touchDown (int x, int y, int pointer, int button) { + Gdx.app.log("Input Test", "touch down: " + x + ", " + y + ", pointer: " + pointer); return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { - Gdx.app.log("Input Test", "touch dragged: " + x + ", " + y + ", pointer: " + pointer); + @Override + public boolean touchDragged (int x, int y, int pointer) { + Gdx.app.log("Input Test", "touch dragged: " + x + ", " + y + ", pointer: " + pointer); return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { - Gdx.app.log("Input Test", "touch up: " + x + ", " + y + ", pointer: " + pointer); + @Override + public boolean touchUp (int x, int y, int pointer, int button) { + Gdx.app.log("Input Test", "touch up: " + x + ", " + y + ", pointer: " + pointer); return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { Gdx.app.log("Input Test", "touch moved: " + x + ", " + y); return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { Gdx.app.log("Input Test", "scrolled: " + amount); return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/RotationTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/RotationTest.java index 96d6c2b6489..a23f9f45e20 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/RotationTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/RotationTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -24,24 +25,25 @@ public class RotationTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - + Texture texture; TextureRegion region; SpriteBatch batch; - - - - @Override public void create() { + + @Override + public void create () { texture = new Texture(Gdx.files.internal("data/black_marked_0.png")); region = new TextureRegion(texture); batch = new SpriteBatch(); batch.getTransformMatrix().setToTranslation(30.5f, 30.5f, 0); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(texture, 0, 0); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ScreenCaptureTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ScreenCaptureTest.java index b8b94a27bf2..5b98e85f8f5 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ScreenCaptureTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ScreenCaptureTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -33,114 +34,108 @@ public class ScreenCaptureTest extends GdxTest implements InputProcessor { private SpriteBatch spriteBatch; private TextureRegion screenCap; private Mesh triangle; - + private float rotation = 0; - - public void create() { + + public void create () { Gdx.input.setInputProcessor(this); - - camera = new OrthographicCamera(800, 480); - - triangle = new Mesh(true, 3, 3, - new VertexAttribute(Usage.Position, 3, "a_position")); - triangle.setVertices(new float[] { - -0.5f, -0.5f, 0, - 0.5f, -0.5f, 0, - 0, 0.5f, 0 - }); + + camera = new OrthographicCamera(800, 480); + + triangle = new Mesh(true, 3, 3, new VertexAttribute(Usage.Position, 3, "a_position")); + triangle.setVertices(new float[] {-0.5f, -0.5f, 0, 0.5f, -0.5f, 0, 0, 0.5f, 0}); triangle.setIndices(new short[] {0, 1, 2}); - + spriteBatch = new SpriteBatch(); } - - public void render() { + + public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); gl.glViewport(0, 0, 400, 480); - - gl.glMatrixMode( GL10.GL_PROJECTION ); - gl.glLoadMatrixf( camera.combined.val, 0 ); - gl.glMatrixMode( GL10.GL_MODELVIEW ); - gl.glLoadIdentity(); - - rotation += rotation >= 360 ? -360 + Gdx.graphics.getDeltaTime() * 45f : - Gdx.graphics.getDeltaTime() * 45f; - - gl.glPushMatrix(); - gl.glColor4f(1, 0, 0, 1); - gl.glRotatef(rotation, 1, 0, 0); - triangle.render(GL10.GL_TRIANGLES); - gl.glPopMatrix(); - gl.glPushMatrix(); - gl.glColor4f(0, 1, 0, 1); - gl.glRotatef(rotation, 0, 1, 0); - triangle.render(GL10.GL_TRIANGLES); - gl.glPopMatrix(); - gl.glPushMatrix(); - gl.glColor4f(0, 0, 1, 1); - gl.glRotatef(rotation, 0, 0, 1); - triangle.render(GL10.GL_TRIANGLES); - gl.glPopMatrix(); - - gl.glViewport(400, 0, 800, 480); - if (screenCap != null) { - spriteBatch.begin(); - spriteBatch.draw(screenCap, 0, 0); - spriteBatch.end(); - } + + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadMatrixf(camera.combined.val, 0); + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadIdentity(); + + rotation += rotation >= 360 ? -360 + Gdx.graphics.getDeltaTime() * 45f : Gdx.graphics.getDeltaTime() * 45f; + + gl.glPushMatrix(); + gl.glColor4f(1, 0, 0, 1); + gl.glRotatef(rotation, 1, 0, 0); + triangle.render(GL10.GL_TRIANGLES); + gl.glPopMatrix(); + gl.glPushMatrix(); + gl.glColor4f(0, 1, 0, 1); + gl.glRotatef(rotation, 0, 1, 0); + triangle.render(GL10.GL_TRIANGLES); + gl.glPopMatrix(); + gl.glPushMatrix(); + gl.glColor4f(0, 0, 1, 1); + gl.glRotatef(rotation, 0, 0, 1); + triangle.render(GL10.GL_TRIANGLES); + gl.glPopMatrix(); + + gl.glViewport(400, 0, 800, 480); + if (screenCap != null) { + spriteBatch.begin(); + spriteBatch.draw(screenCap, 0, 0); + spriteBatch.end(); + } } - - public void dispose() { + + public void dispose () { spriteBatch.dispose(); triangle.dispose(); if (screenCap != null) screenCap.getTexture().dispose(); } - + @Override - public boolean needsGL20() { + public boolean needsGL20 () { return false; } @Override - public boolean keyDown(int keycode) { + public boolean keyDown (int keycode) { return false; } @Override - public boolean keyUp(int keycode) { + public boolean keyUp (int keycode) { return false; } @Override - public boolean keyTyped(char character) { + public boolean keyTyped (char character) { return false; } @Override - public boolean touchDown(int x, int y, int pointer, int button) { + public boolean touchDown (int x, int y, int pointer, int button) { if (screenCap != null) screenCap.getTexture().dispose(); screenCap = null; return false; } @Override - public boolean touchUp(int x, int y, int pointer, int button) { + public boolean touchUp (int x, int y, int pointer, int button) { screenCap = ScreenUtils.getFrameBufferTexture(); return false; } @Override - public boolean touchDragged(int x, int y, int pointer) { + public boolean touchDragged (int x, int y, int pointer) { return false; } @Override - public boolean touchMoved(int x, int y) { + public boolean touchMoved (int x, int y) { return false; } @Override - public boolean scrolled(int amount) { + public boolean scrolled (int amount) { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ShaderMultitextureTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ShaderMultitextureTest.java index abd9af6bac4..8106914b7aa 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ShaderMultitextureTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ShaderMultitextureTest.java @@ -13,18 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; -import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.graphics.Color; 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.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.Usage; import com.badlogic.gdx.graphics.glutils.ShaderProgram; @@ -36,26 +33,18 @@ public class ShaderMultitextureTest extends GdxTest { Texture texture2; Mesh mesh; - @Override public void create () { - String vertexShader = "attribute vec4 a_position; \n" + - "attribute vec2 a_texCoord; \n" + - "varying vec2 v_texCoord; \n" + - "void main() \n" + - "{ \n" + - " gl_Position = a_position; \n" + - " v_texCoord = a_texCoord; \n" + - "} \n"; - - String fragmentShader = "#ifdef GL_ES\n" + - "precision mediump float;\n" + - "#endif\n" + - "varying vec2 v_texCoord; \n" + - "uniform sampler2D s_texture; \n" + - "uniform sampler2D s_texture2; \n" + - "void main() \n" + - "{ \n" + - " gl_FragColor = texture2D( s_texture, v_texCoord ) * texture2D( s_texture2, v_texCoord);\n" + - "} \n"; + @Override + public void create () { + String vertexShader = "attribute vec4 a_position; \n" + "attribute vec2 a_texCoord; \n" + + "varying vec2 v_texCoord; \n" + "void main() \n" + "{ \n" + + " gl_Position = a_position; \n" + " v_texCoord = a_texCoord; \n" + "} \n"; + + String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\n" + + "varying vec2 v_texCoord; \n" + "uniform sampler2D s_texture; \n" + + "uniform sampler2D s_texture2; \n" + "void main() \n" + + "{ \n" + + " gl_FragColor = texture2D( s_texture, v_texCoord ) * texture2D( s_texture2, v_texCoord);\n" + + "} \n"; shader = new ShaderProgram(vertexShader, fragmentShader); mesh = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 2, "a_position"), new VertexAttribute( Usage.TextureCoordinates, 2, "a_texCoord")); @@ -74,7 +63,7 @@ public class ShaderMultitextureTest extends GdxTest { createTexture(); } - private void createTexture () { + private void createTexture () { Pixmap pixmap = new Pixmap(256, 256, Format.RGBA8888); pixmap.setColor(1, 1, 1, 1); pixmap.fill(); @@ -90,7 +79,7 @@ private void createTexture () { pixmap.setColor(0, 0, 0, 1); pixmap.drawLine(128, 0, 128, 256); texture2 = new Texture(pixmap); - pixmap.dispose(); + pixmap.dispose(); } public void resume () { @@ -109,14 +98,15 @@ public void render () { shader.begin(); shader.setUniformi("s_texture", 0); - shader.setUniformi("s_texture2", 1); - + shader.setUniformi("s_texture2", 1); + mesh.render(shader, GL20.GL_TRIANGLES); shader.end(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/ShadowMappingTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/ShadowMappingTest.java index 448e8a27eff..23178380ad5 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/ShadowMappingTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/ShadowMappingTest.java @@ -1,6 +1,5 @@ -package com.badlogic.gdx.tests; -import java.util.Vector; +package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; @@ -13,101 +12,99 @@ import com.badlogic.gdx.graphics.g3d.loaders.ModelLoaderOld; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.graphics.glutils.ShaderProgram; -import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.ComboBox; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; -import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.LibgdxToolkit; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; -import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.PerspectiveCamController; import com.badlogic.gdx.utils.GdxRuntimeException; public class ShadowMappingTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } - + Stage ui; - - PerspectiveCamera cam; + + PerspectiveCamera cam; PerspectiveCamera lightCam; PerspectiveCamera currCam; Mesh plane; Mesh cube; ShaderProgram flatShader; - ShaderProgram shadowGenShader; + ShaderProgram shadowGenShader; ShaderProgram shadowMapShader; ShaderProgram currShader; - FrameBuffer shadowMap; + FrameBuffer shadowMap; InputMultiplexer multiplexer; PerspectiveCamController camController; - @Override public void create() { -// ShaderProgram.pedantic = false; - + @Override + public void create () { +// ShaderProgram.pedantic = false; + setupScene(); setupShadowMap(); setupUI(); - - camController = new PerspectiveCamController(cam); + + camController = new PerspectiveCamController(cam); multiplexer = new InputMultiplexer(); multiplexer.addProcessor(ui); multiplexer.addProcessor(camController); - + Gdx.input.setInputProcessor(multiplexer); } - - private void setupScene() { + + private void setupScene () { plane = new Mesh(true, 4, 4, new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); - plane.setVertices(new float[] { -10, -1, 10, - 10, -1, 10, - 10, -1, -10, - -10, -1, -10 }); - plane.setIndices(new short[] { 3, 2, 1, 0 }); + plane.setVertices(new float[] {-10, -1, 10, 10, -1, 10, 10, -1, -10, -10, -1, -10}); + plane.setIndices(new short[] {3, 2, 1, 0}); cube = ModelLoaderOld.loadObj(Gdx.files.internal("data/cube.obj").read()); - + cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(0, 0, 10); - cam.lookAt(0, 0, 0); + cam.lookAt(0, 0, 0); cam.update(); currCam = cam; - - flatShader = new ShaderProgram(Gdx.files.internal("data/shaders/flat-vert.glsl").readString(), - Gdx.files.internal("data/shaders/flat-frag.glsl").readString()); - if(!flatShader.isCompiled()) throw new GdxRuntimeException("Couldn't compile flat shader: " + flatShader.getLog()); + + flatShader = new ShaderProgram(Gdx.files.internal("data/shaders/flat-vert.glsl").readString(), Gdx.files.internal( + "data/shaders/flat-frag.glsl").readString()); + if (!flatShader.isCompiled()) throw new GdxRuntimeException("Couldn't compile flat shader: " + flatShader.getLog()); currShader = flatShader; } - - private void setupShadowMap() { - shadowMap = new FrameBuffer(Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true); + + private void setupShadowMap () { + shadowMap = new FrameBuffer(Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true); lightCam = new PerspectiveCamera(67, shadowMap.getWidth(), shadowMap.getHeight()); lightCam.position.set(-10, 10, 0); - lightCam.lookAt(0, 0, 0); + lightCam.lookAt(0, 0, 0); lightCam.update(); - - shadowGenShader = new ShaderProgram(Gdx.files.internal("data/shaders/shadowgen-vert.glsl").readString(), - Gdx.files.internal("data/shaders/shadowgen-frag.glsl").readString()); - if(!shadowGenShader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shadow gen shader: " + shadowGenShader.getLog()); - - shadowMapShader = new ShaderProgram(Gdx.files.internal("data/shaders/shadowmap-vert.glsl").readString(), - Gdx.files.internal("data/shaders/shadowmap-frag.glsl").readString()); - if(!shadowMapShader.isCompiled()) throw new GdxRuntimeException("Couldn't compile shadow map shader: " + shadowMapShader.getLog()); + + shadowGenShader = new ShaderProgram(Gdx.files.internal("data/shaders/shadowgen-vert.glsl").readString(), Gdx.files + .internal("data/shaders/shadowgen-frag.glsl").readString()); + if (!shadowGenShader.isCompiled()) + throw new GdxRuntimeException("Couldn't compile shadow gen shader: " + shadowGenShader.getLog()); + + shadowMapShader = new ShaderProgram(Gdx.files.internal("data/shaders/shadowmap-vert.glsl").readString(), Gdx.files + .internal("data/shaders/shadowmap-frag.glsl").readString()); + if (!shadowMapShader.isCompiled()) + throw new GdxRuntimeException("Couldn't compile shadow map shader: " + shadowMapShader.getLog()); } - - private void setupUI() { + + private void setupUI () { ui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); Skin skin = new Skin(Gdx.files.internal("data/uiskin.xml"), Gdx.files.internal("data/uiskin.png")); - + Label label = skin.newLabel("label", "Camera:"); - ComboBox cameraCombo = skin.newComboBox("cameraCombo", new String[] { "Scene", "Light"}, ui); + ComboBox cameraCombo = skin.newComboBox("cameraCombo", new String[] {"Scene", "Light"}, ui); Label label2 = skin.newLabel("label2", "Shader"); - ComboBox shaderCombo = skin.newComboBox("shaderCombo", new String[] { "flat", "shadow-gen", "shadow-map" }, ui); + ComboBox shaderCombo = skin.newComboBox("shaderCombo", new String[] {"flat", "shadow-gen", "shadow-map"}, ui); Label fpsLabel = skin.newLabel("fps", "fps:"); - + Table table = new Table("toolbar", Gdx.graphics.getWidth(), 100); table.defaults().spaceRight(5); table.add(label); @@ -115,80 +112,89 @@ private void setupUI() { table.add(label2); table.add(shaderCombo); table.add(fpsLabel); - table.y = ui.top() - 100; + table.y = ui.top() - 100; ui.addActor(table); - - cameraCombo.setSelectionListener(new ComboBox.SelectionListener() { - @Override public void selected (ComboBox comboBox, int selectionIndex, String selection) { - if(selectionIndex == 0) currCam = cam; - else currCam = lightCam; + + cameraCombo.setSelectionListener(new ComboBox.SelectionListener() { + @Override + public void selected (ComboBox comboBox, int selectionIndex, String selection) { + if (selectionIndex == 0) + currCam = cam; + else + currCam = lightCam; camController.cam = currCam; } }); - - shaderCombo.setSelectionListener(new ComboBox.SelectionListener() { - @Override public void selected (ComboBox comboBox, int selectionIndex, String selection) { - if(selectionIndex == 0) currShader = flatShader; - else if(selectionIndex == 1) currShader = shadowGenShader; - else currShader = shadowMapShader; + + shaderCombo.setSelectionListener(new ComboBox.SelectionListener() { + @Override + public void selected (ComboBox comboBox, int selectionIndex, String selection) { + if (selectionIndex == 0) + currShader = flatShader; + else if (selectionIndex == 1) + currShader = shadowGenShader; + else + currShader = shadowMapShader; } }); } - - @Override public void render() { - Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT | (Gdx.graphics.getBufferFormat().coverageSampling?GL20.GL_COVERAGE_BUFFER_BIT_NV:0)); - Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); - - if(currShader == flatShader) { - currShader.begin(); + + @Override + public void render () { + Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT + | (Gdx.graphics.getBufferFormat().coverageSampling ? GL20.GL_COVERAGE_BUFFER_BIT_NV : 0)); + Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); + + if (currShader == flatShader) { + currShader.begin(); currShader.setUniformMatrix("u_projTrans", currCam.combined); - - currShader.setUniformf("u_color", 1, 0, 0, 1); + + currShader.setUniformf("u_color", 1, 0, 0, 1); plane.render(currShader, GL20.GL_TRIANGLE_FAN); - - currShader.setUniformf("u_color", 0, 1, 0, 1); + + currShader.setUniformf("u_color", 0, 1, 0, 1); cube.render(currShader, GL20.GL_TRIANGLES); - + currShader.end(); - } else if(currShader == shadowGenShader) { - currShader.begin(); + } else if (currShader == shadowGenShader) { + currShader.begin(); currShader.setUniformMatrix("u_projTrans", currCam.combined); - - plane.render(currShader, GL20.GL_TRIANGLE_FAN); + + plane.render(currShader, GL20.GL_TRIANGLE_FAN); cube.render(currShader, GL20.GL_TRIANGLES); - + currShader.end(); - } else if(currShader == shadowMapShader) { + } else if (currShader == shadowMapShader) { shadowMap.begin(); - Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); + Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL20.GL_CULL_FACE); Gdx.gl.glCullFace(GL20.GL_FRONT); shadowGenShader.begin(); - shadowGenShader.setUniformMatrix("u_projTrans", lightCam.combined); - plane.render(shadowGenShader, GL20.GL_TRIANGLE_FAN); - cube.render(shadowGenShader, GL20.GL_TRIANGLES); + shadowGenShader.setUniformMatrix("u_projTrans", lightCam.combined); + plane.render(shadowGenShader, GL20.GL_TRIANGLE_FAN); + cube.render(shadowGenShader, GL20.GL_TRIANGLES); shadowGenShader.end(); shadowMap.end(); Gdx.gl.glDisable(GL20.GL_CULL_FACE); - + shadowMapShader.begin(); shadowMap.getColorBufferTexture().bind(); shadowMapShader.setUniformi("s_shadowMap", 0); - shadowMapShader.setUniformMatrix("u_projTrans", cam.combined); + shadowMapShader.setUniformMatrix("u_projTrans", cam.combined); shadowMapShader.setUniformMatrix("u_lightProjTrans", lightCam.combined); shadowMapShader.setUniformf("u_color", 1, 0, 0, 1); plane.render(shadowMapShader, GL20.GL_TRIANGLE_FAN); shadowMapShader.setUniformf("u_color", 0, 1, 0, 1); cube.render(shadowMapShader, GL20.GL_TRIANGLES); shadowMapShader.end(); - + ui.getSpriteBatch().begin(); ui.getSpriteBatch().draw(shadowMap.getColorBufferTexture(), 0, 0, 100, 100); ui.getSpriteBatch().end(); } - + Label fps = (Label)ui.findActor("fps"); fps.setText("fps: " + Gdx.graphics.getFramesPerSecond()); ui.draw(); - } -} \ No newline at end of file + } +} diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleAnimationTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleAnimationTest.java index 194d892aefe..ba177b6ec43 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleAnimationTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleAnimationTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -27,99 +28,104 @@ public class SimpleAnimationTest extends GdxTest implements InputProcessor { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - private Animation currentWalk; - private float currentFrameTime; - private Vector2 position; - - private Texture tex; - - private Animation downWalk; - private Animation leftWalk; - private Animation rightWalk; - private Animation upWalk; - - private SpriteBatch spriteBatch; - - private static final float ANIMATION_SPEED = 0.2f; - - @Override - public void create() - { - Gdx.input.setInputProcessor(this); - tex = new Texture(Gdx.files.internal("data/animation.png")); - TextureRegion[][] regions = TextureRegion.split(tex, 32, 48); - TextureRegion[] downWalkReg = regions[0]; - TextureRegion[] leftWalkReg = regions[1]; - TextureRegion[] rightWalkReg = regions[2]; - TextureRegion[] upWalkReg = regions[3]; - downWalk = new Animation(ANIMATION_SPEED, downWalkReg); - leftWalk = new Animation(ANIMATION_SPEED, leftWalkReg); - rightWalk = new Animation(ANIMATION_SPEED, rightWalkReg); - upWalk = new Animation(ANIMATION_SPEED, upWalkReg); - - currentWalk = leftWalk; - currentFrameTime = 0.0f; - - spriteBatch = new SpriteBatch(); - position = new Vector2(); - } - - @Override - public void render() - { - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - currentFrameTime += Gdx.graphics.getDeltaTime(); - - spriteBatch.begin(); - TextureRegion frame = currentWalk.getKeyFrame(currentFrameTime, true); - spriteBatch.draw(frame, position.x, position.y); - spriteBatch.end(); - } - - - @Override - public boolean touchDown(int x, int y, int pointer, int button) { - position.x = x; - position.y = y; - //System.out.println(position); - return true; - } - - @Override public boolean keyDown (int keycode) { + private Animation currentWalk; + private float currentFrameTime; + private Vector2 position; + + private Texture tex; + + private Animation downWalk; + private Animation leftWalk; + private Animation rightWalk; + private Animation upWalk; + + private SpriteBatch spriteBatch; + + private static final float ANIMATION_SPEED = 0.2f; + + @Override + public void create () { + Gdx.input.setInputProcessor(this); + tex = new Texture(Gdx.files.internal("data/animation.png")); + TextureRegion[][] regions = TextureRegion.split(tex, 32, 48); + TextureRegion[] downWalkReg = regions[0]; + TextureRegion[] leftWalkReg = regions[1]; + TextureRegion[] rightWalkReg = regions[2]; + TextureRegion[] upWalkReg = regions[3]; + downWalk = new Animation(ANIMATION_SPEED, downWalkReg); + leftWalk = new Animation(ANIMATION_SPEED, leftWalkReg); + rightWalk = new Animation(ANIMATION_SPEED, rightWalkReg); + upWalk = new Animation(ANIMATION_SPEED, upWalkReg); + + currentWalk = leftWalk; + currentFrameTime = 0.0f; + + spriteBatch = new SpriteBatch(); + position = new Vector2(); + } + + @Override + public void render () { + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + currentFrameTime += Gdx.graphics.getDeltaTime(); + + spriteBatch.begin(); + TextureRegion frame = currentWalk.getKeyFrame(currentFrameTime, true); + spriteBatch.draw(frame, position.x, position.y); + spriteBatch.end(); + } + + @Override + public boolean touchDown (int x, int y, int pointer, int button) { + position.x = x; + position.y = y; + // System.out.println(position); + return true; + } + + @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 touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { // 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 touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { // TODO Auto-generated method stub return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { // TODO Auto-generated method stub return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleDecalTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleDecalTest.java index a15cce2eb11..726fa4fedd1 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleDecalTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleDecalTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -21,58 +22,57 @@ public class SimpleDecalTest extends GdxTest { PerspectiveCamera camera; PerspectiveCamController controller; FPSLogger logger = new FPSLogger(); - - public void create() { + + public void create () { float width = Gdx.graphics.getWidth(); float height = Gdx.graphics.getHeight(); - + camera = new PerspectiveCamera(45, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.near = 1; camera.far = 300; camera.position.set(0, 0, 5); controller = new PerspectiveCamController(camera); - + Gdx.input.setInputProcessor(controller); batch = new DecalBatch(new CameraGroupStrategy(camera)); - - TextureRegion[] textures = { new TextureRegion(new Texture(Gdx.files.internal("data/egg.png"))), - new TextureRegion(new Texture(Gdx.files.internal("data/wheel.png"))), - new TextureRegion(new Texture(Gdx.files.internal("data/badlogic.jpg"))) - }; - - + + TextureRegion[] textures = {new TextureRegion(new Texture(Gdx.files.internal("data/egg.png"))), + new TextureRegion(new Texture(Gdx.files.internal("data/wheel.png"))), + new TextureRegion(new Texture(Gdx.files.internal("data/badlogic.jpg")))}; + Decal decal = Decal.newDecal(1, 1, textures[1]); decal.setPosition(0, 0, 0); decals.add(decal); - + decal = Decal.newDecal(1, 1, textures[0], true); decal.setPosition(0.5f, 0.5f, 1); decals.add(decal); - + decal = Decal.newDecal(1, 1, textures[0], true); decal.setPosition(1, 1, -1); decals.add(decal); - + decal = Decal.newDecal(1, 1, textures[2]); decal.setPosition(1.5f, 1.5f, -2); decals.add(decal); - + decal = Decal.newDecal(1, 1, textures[1]); decal.setPosition(2, 2, -1.5f); decals.add(decal); } - + Vector3 dir = new Vector3(); private boolean billboard = true; - public void render() { + + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl.glEnable(GL10.GL_DEPTH_TEST); - - camera.update(); - for(int i = 0; i < decals.size; i++) { + + camera.update(); + for (int i = 0; i < decals.size; i++) { Decal decal = decals.get(i); - if(billboard ) { -// dir.set(camera.position).sub(decal.getPosition()).nor(); + if (billboard) { +// dir.set(camera.position).sub(decal.getPosition()).nor(); dir.set(-camera.direction.x, -camera.direction.y, -camera.direction.z); decal.setRotation(dir, Vector3.Y); } @@ -81,7 +81,7 @@ public void render() { batch.flush(); logger.log(); } - + @Override public boolean needsGL20 () { return true; diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleStageCullingTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleStageCullingTest.java index ade1cf9ac3b..ee8de1780d2 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleStageCullingTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleStageCullingTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.List; @@ -30,128 +31,115 @@ import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.OrthoCamController; - -/** - * This is a simple demonstration of how to perform VERY basic - * culling on hierarchies of stage actors that do not scale or rotate. It - * is not a general solution as it assumes that actors and groups are only - * translated (moved, change their x/y coordinates). +/** This is a simple demonstration of how to perform VERY basic culling on hierarchies of stage actors that do not scale or rotate. + * It is not a general solution as it assumes that actors and groups are only translated (moved, change their x/y coordinates). * - * @author mzechner - * - */ + * @author mzechner */ public class SimpleStageCullingTest extends GdxTest { - - /** - * We need to extend a base actor class so we can - * add the culling in the render method. We also - * add a method to get the stage coordinates of the - * actor so we can cull it against the camera's - * view volume. + + /** We need to extend a base actor class so we can add the culling in the render method. We also add a method to get the stage + * coordinates of the actor so we can cull it against the camera's view volume. * - * @author mzechner - * - */ + * @author mzechner */ private class CullableActor extends Image { /** the camera to test against **/ final OrthographicCamera camera; /** whether we are visible or not, used for counting visible actors **/ - boolean visible = false; - - public CullableActor(String name, Texture texture, OrthographicCamera camera) { + boolean visible = false; + + public CullableActor (String name, Texture texture, OrthographicCamera camera) { super(name, texture); - this.camera = camera; - } - - public void draw(SpriteBatch batch, float parentAlpha) { + this.camera = camera; + } + + public void draw (SpriteBatch batch, float parentAlpha) { // if this actor is not within the view of the camera we don't draw it. - if(isCulled()) return; - + if (isCulled()) return; + // otherwise we draw via the super class method super.draw(batch, parentAlpha); } - + /** static helper Rectangles **/ - Rectangle actorRect = new Rectangle(); + Rectangle actorRect = new Rectangle(); Rectangle camRect = new Rectangle(); - - private boolean isCulled() { + + private boolean isCulled () { // we start by setting the stage coordinates to this // actors coordinates which are relative to its parent // Group. float stageX = x; float stageY = y; - + // now we go up the hierarchy and add all the parents' - // coordinates to this actors coordinates. Note that + // coordinates to this actors coordinates. Note that // this assumes that neither this actor nor any of its // parents are rotated or scaled! Actor parent = this.parent; - while(parent != null) { + while (parent != null) { stageX += parent.x; stageY += parent.y; parent = parent.parent; } - + // now we check if the rectangle of this actor in screen // coordinates is in the rectangle spanned by the camera's // view. This assumes that the camera has no zoom and is // not rotated! actorRect.set(stageX, stageY, width, height); - camRect.set(camera.position.x - camera.viewportWidth / 2.0f, - camera.position.y - camera.viewportHeight / 2.0f, - camera.viewportWidth, camera.viewportHeight); - visible = camRect.overlaps(actorRect); + camRect.set(camera.position.x - camera.viewportWidth / 2.0f, camera.position.y - camera.viewportHeight / 2.0f, + camera.viewportWidth, camera.viewportHeight); + visible = camRect.overlaps(actorRect); return !visible; - } + } } - + OrthoCamController camController; - Stage stage; + Stage stage; SpriteBatch batch; BitmapFont font; - + @Override - public void create() { + public void create () { // create a stage and a camera controller so we can pan the view. - stage = new Stage(480, 320, false); + stage = new Stage(480, 320, false); camController = new OrthoCamController((OrthographicCamera)stage.getCamera()); // we know it's an ortho cam at this point! Gdx.input.setInputProcessor(camController); - + // load a dummy texture Texture texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); - + // populate the stage with some actors and groups. - for(int i = 0; i < 5000; i++) { + for (int i = 0; i < 5000; i++) { Actor img = new CullableActor("img" + i, texture, (OrthographicCamera)stage.getCamera()); img.x = (float)Math.random() * 480 * 10; img.y = (float)Math.random() * 320 * 10; stage.addActor(img); } - + // we also want to output the number of visible actors, so we need a SpriteBatch and a BitmapFont batch = new SpriteBatch(); font = new BitmapFont(); } - - public void render() { + + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.draw(); - + // check how many actors are visible. List actors = stage.getActors(); int numVisible = 0; - for(int i = 0; i < actors.size(); i++) { - numVisible += ((CullableActor)actors.get(i)).visible?1:0; + for (int i = 0; i < actors.size(); i++) { + numVisible += ((CullableActor)actors.get(i)).visible ? 1 : 0; } - + batch.begin(); font.draw(batch, "Visible: " + numVisible + ", fps: " + Gdx.graphics.getFramesPerSecond(), 20, 30); batch.end(); } - + @Override - public boolean needsGL20() { + public boolean needsGL20 () { return false; } } 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 37df0728f1d..d1b51a9ecc3 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SimpleTest.java @@ -13,6 +13,7 @@ * 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,64 +24,78 @@ public class SimpleTest extends GdxTest implements InputProcessor { float r = 1, g = 0, b = 0; - @Override public void create () { + @Override + public void create () { Gdx.app.log("Simple Test", "Thread=" + Thread.currentThread().getId() + ", surface created"); Gdx.input.setInputProcessor(this); } - @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); } - @Override public void dispose () { + @Override + public void dispose () { Gdx.app.log("Simple Test", "Thread=" + Thread.currentThread().getId() + ", application destroyed"); } - @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, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { r = (float)Math.random(); g = (float)Math.random(); b = (float)Math.random(); return false; } - @Override public void pause () { + @Override + public void pause () { } - @Override public void resume () { + @Override + public void resume () { } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } 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 0841d49190c..741641e2c95 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SoundTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SoundTest.java @@ -13,6 +13,7 @@ * 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; @@ -34,14 +35,16 @@ public class SoundTest extends GdxTest implements InputProcessor { BitmapFont font; SpriteBatch batch; - @Override public void render () { + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.draw(batch, "Position: " + music.getPosition(), 30, 146); batch.end(); } - @Override public void create () { + @Override + public void create () { // sound = Gdx.audio.newSound(Gdx.files.getFileHandle("data/shotgun.wav", FileType.Internal)); sound = Gdx.audio.newSound(Gdx.files.getFileHandle("data/sell_buy_item.wav", FileType.Internal)); @@ -56,11 +59,13 @@ public class SoundTest extends GdxTest implements InputProcessor { font = new BitmapFont(Gdx.files.internal("data/verdana39.fnt"), Gdx.files.internal("data/verdana39.png"), false); } - @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) { if (character == '+') volume += 0.1f; if (character == '-') volume -= 0.1f; music.setVolume(volume); @@ -68,7 +73,8 @@ public class SoundTest extends GdxTest implements InputProcessor { return false; } - @Override public boolean keyUp (int keycode) { + @Override + public boolean keyUp (int keycode) { if (keycode != Input.Keys.SPACE) return false; if (music.isPlaying()) music.pause(); @@ -77,7 +83,8 @@ public class SoundTest extends GdxTest implements InputProcessor { return false; } - @Override public boolean touchDown (int x, int y, int pointer, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { sound.play(1f); if (music.isPlaying()) music.stop(); @@ -86,23 +93,28 @@ public class SoundTest extends GdxTest implements InputProcessor { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SplineTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SplineTest.java index a09b91ed502..afde2e3307b 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SplineTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SplineTest.java @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ -package com.badlogic.gdx.tests; -import java.util.ArrayList; -import java.util.List; +package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer10; import com.badlogic.gdx.math.CatmullRomSpline; -import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.tests.utils.GdxTest; public class SplineTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -38,9 +36,9 @@ public class SplineTest extends GdxTest { ImmediateModeRenderer10 renderer; CatmullRomSpline spline; Vector3[] path; - - @Override public void create () { + @Override + public void create () { cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0); renderer = new ImmediateModeRenderer10(); @@ -48,36 +46,37 @@ public class SplineTest extends GdxTest { float x = 0; float y = Gdx.graphics.getHeight() / 2; spline.add(new Vector3(x - 50, y, 0)); - for(int i = 0; i < CONTROL_POINTS; i++) { + for (int i = 0; i < CONTROL_POINTS; i++) { spline.add(new Vector3(x, y, 0)); x += Gdx.graphics.getWidth() / (CONTROL_POINTS - 2); } spline.add(new Vector3(Gdx.graphics.getWidth() + 50, y, 0)); path = new Vector3[(CONTROL_POINTS - 2) * 7 - 1]; - for(int i = 0; i < path.length; i++) + for (int i = 0; i < path.length; i++) path[i] = new Vector3(); - spline.getPath(path, 5); - } - - @Override public void render () { - Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); + spline.getPath(path, 5); + } + + @Override + public void render () { + Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); cam.update(); Gdx.gl10.glMatrixMode(GL10.GL_PROJECTION); Gdx.gl10.glLoadMatrixf(cam.projection.val, 0); Gdx.gl10.glMatrixMode(GL10.GL_MODELVIEW); Gdx.gl10.glLoadMatrixf(cam.view.val, 0); - + renderer.begin(GL10.GL_TRIANGLES); - for(int i = 0; i < path.length - 1; i++) { + for (int i = 0; i < path.length - 1; i++) { Vector3 point1 = path[i]; - Vector3 point2 = path[i+1]; + Vector3 point2 = path[i + 1]; renderer.color(1, 1, 1, 1); renderer.vertex(point1.x, point1.y, 0); renderer.color(1, 1, 1, 1); renderer.vertex(point1.x, 0, 0); renderer.color(1, 1, 1, 1); renderer.vertex(point2.x, point2.y, 0); - + renderer.color(1, 1, 1, 1); renderer.vertex(point2.x, point2.y, 0); renderer.color(1, 1, 1, 1); @@ -86,40 +85,41 @@ public class SplineTest extends GdxTest { renderer.vertex(point2.x, 0, 0); } renderer.end(); - + Gdx.gl10.glPointSize(4); renderer.begin(GL10.GL_POINTS); - for(int i = 0; i < spline.getControlPoints().size(); i++) { + for (int i = 0; i < spline.getControlPoints().size(); i++) { Vector3 point = spline.getControlPoints().get(i); renderer.color(1, 0, 0, 1); renderer.vertex(point.x, point.y, 0); } renderer.end(); Gdx.gl10.glPointSize(1); - + processInput(); } - + Vector3 point = new Vector3(); - private void processInput() { -// if(Gdx.input.isTouched()) { -// Vector3 nearest = null; -// float nearestDist = Float.MAX_VALUE; -// point.set(cam.getScreenToWorldX(Gdx.input.getX()), -// cam.getScreenToWorldY(Gdx.input.getY()), -// 0); -// -// for(int i = 0; i < spline.getControlPoints().size(); i++) { -// Vector3 controlPoint = spline.getControlPoints().get(i); -// float dist = Math.abs(point.x - controlPoint.x); -// if(dist < nearestDist) { -// nearest = controlPoint; -// nearestDist = dist; -// } -// } -// -// nearest.y += (point.y - nearest.y) * Gdx.graphics.getDeltaTime(); -// spline.getPath(path, 5); -// } + + private void processInput () { +// if(Gdx.input.isTouched()) { +// Vector3 nearest = null; +// float nearestDist = Float.MAX_VALUE; +// point.set(cam.getScreenToWorldX(Gdx.input.getX()), +// cam.getScreenToWorldY(Gdx.input.getY()), +// 0); +// +// for(int i = 0; i < spline.getControlPoints().size(); i++) { +// Vector3 controlPoint = spline.getControlPoints().get(i); +// float dist = Math.abs(point.x - controlPoint.x); +// if(dist < nearestDist) { +// nearest = controlPoint; +// nearestDist = dist; +// } +// } +// +// nearest.y += (point.y - nearest.y) * Gdx.graphics.getDeltaTime(); +// spline.getPath(path, 5); +// } } } 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 c3b89ef1988..ef0d0434ea6 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchRotationTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchRotationTest.java @@ -13,18 +13,16 @@ * 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.graphics.GL10; 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.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; @@ -37,7 +35,8 @@ public class SpriteBatchRotationTest extends GdxTest { float vScale = 1; IntBuffer pixelBuffer; - @Override public void render () { + @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(), false, false); @@ -85,7 +84,8 @@ public class SpriteBatchRotationTest extends GdxTest { } - @Override public void create () { + @Override + public void create () { spriteBatch = new SpriteBatch(); texture = new Texture(Gdx.files.internal("data/test.png")); // font = Gdx.graphics.newFont("Arial", 12, FontStyle.Plain); @@ -95,7 +95,8 @@ public class SpriteBatchRotationTest extends GdxTest { } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } 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 6525ec640a5..0c7630d633e 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchShaderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchShaderTest.java @@ -13,18 +13,16 @@ * 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.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; 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.TextureFilter; -import com.badlogic.gdx.graphics.Texture.TextureWrap; +import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; @@ -36,7 +34,7 @@ public class SpriteBatchShaderTest extends GdxTest { Texture texture; Texture texture2; -// Font font; +// Font font; SpriteBatch spriteBatch; int coords[] = new int[SPRITES * 2]; int coords2[] = new int[SPRITES * 2]; @@ -46,7 +44,8 @@ public class SpriteBatchShaderTest extends GdxTest { Mesh mesh; float vertices[] = new float[SPRITES * 6 * (2 + 2 + 4)]; - @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); @@ -74,9 +73,9 @@ public class SpriteBatchShaderTest extends GdxTest { 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, "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(); @@ -92,7 +91,8 @@ public class SpriteBatchShaderTest extends GdxTest { frames++; } - @Override public void create () { + @Override + public void create () { spriteBatch = new SpriteBatch(); Pixmap pixmap = new Pixmap(Gdx.files.internal("data/badlogicsmall.jpg")); // pixmap.setColor( 0, 0, 0, 0 ); @@ -110,7 +110,7 @@ public class SpriteBatchShaderTest extends GdxTest { texture2 = new Texture(pixmap); pixmap.dispose(); -// if (font == null) font = Gdx.graphics.newFont("Arial", 32, FontStyle.Plain); +// 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()); @@ -120,7 +120,8 @@ public class SpriteBatchShaderTest extends GdxTest { } } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } 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 da4364e72be..d7147ea2eb2 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteBatchTest.java @@ -13,9 +13,9 @@ * 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.InputProcessor; import com.badlogic.gdx.graphics.GL10; @@ -23,7 +23,6 @@ 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.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; @@ -47,7 +46,8 @@ public class SpriteBatchTest extends GdxTest implements InputProcessor { float SCALE_SPEED = -1; int renderMethod = 0; - @Override public void render () { + @Override + public void render () { if (renderMethod == 0) renderNormal(); ; if (renderMethod == 1) renderSprites(); @@ -88,7 +88,7 @@ private void renderNormal () { 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, false, false); - draw2 = (System.nanoTime() - start) / 1000000000.0f; + draw2 = (System.nanoTime() - start) / 1000000000.0f; start = System.nanoTime(); // spriteBatch.drawText(font, "Question?", 100, 300, Color.RED); @@ -108,7 +108,7 @@ private void renderNormal () { startTime = System.nanoTime(); } frames++; - + } private void renderSprites () { @@ -173,7 +173,8 @@ private void renderSprites () { frames++; } - @Override public void create () { + @Override + public void create () { spriteBatch = new SpriteBatch(1000); Pixmap pixmap = new Pixmap(Gdx.files.internal("data/badlogicsmall.jpg")); @@ -207,8 +208,8 @@ private void renderSprites () { 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)); - + int y = (int)(Math.random() * (Gdx.graphics.getHeight() - 32)); + if (i >= SPRITES) sprites3[i] = new Sprite(texture2, 32, 32); else @@ -220,40 +221,49 @@ private void renderSprites () { Gdx.input.setInputProcessor(this); } - @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, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { renderMethod = (renderMethod + 1) % 2; return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheOffsetTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheOffsetTest.java index 372fa1e0882..08173c63b1f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheOffsetTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheOffsetTest.java @@ -13,6 +13,7 @@ * 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,9 +24,6 @@ import com.badlogic.gdx.graphics.g2d.SpriteCache; import com.badlogic.gdx.tests.utils.GdxTest; -import static com.badlogic.gdx.graphics.Texture.TextureFilter.*; -import static com.badlogic.gdx.graphics.Texture.TextureWrap.*; - public class SpriteCacheOffsetTest extends GdxTest implements InputProcessor { private int tileMapWidth = 10; private int tileMapHeight = 5; @@ -84,11 +82,13 @@ public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheTest.java index 6478d4e4fea..f92fbbcaf2f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpriteCacheTest.java @@ -13,9 +13,9 @@ * 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.Input; import com.badlogic.gdx.InputProcessor; @@ -24,7 +24,6 @@ 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.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteCache; import com.badlogic.gdx.math.MathUtils; @@ -46,13 +45,14 @@ public class SpriteCacheTest extends GdxTest implements InputProcessor { private float[] sprites2; - @Override public void render () { + @Override + public void render () { if (renderMethod == 0) renderNormal(); ; if (renderMethod == 1) renderSprites(); } - private void renderNormal () { + private void renderNormal () { Gdx.gl.glClearColor(0.7f, 0.7f, 0.7f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); @@ -113,7 +113,8 @@ private void renderSprites () { frames++; } - @Override public void create () { + @Override + public void create () { spriteCache = new SpriteCache(1000, true); Pixmap pixmap = new Pixmap(Gdx.files.internal("data/badlogicsmall.jpg")); @@ -187,7 +188,8 @@ private void renderSprites () { Gdx.input.setInputProcessor(this); } - @Override public boolean keyDown (int keycode) { + @Override + public boolean keyDown (int keycode) { if (keycode != Input.Keys.SPACE) return false; float scale = MathUtils.random(0.75f, 1.25f); float angle = MathUtils.random(1, 360); @@ -200,36 +202,44 @@ private void renderSprites () { 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, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { renderMethod = (renderMethod + 1) % 2; return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanceTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanceTest.java index 9a9bd2d842a..fe1d947858c 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanceTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanceTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -20,7 +21,6 @@ import com.badlogic.gdx.graphics.Mesh; 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.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.SpriteCache; @@ -220,7 +220,8 @@ void renderSpriteCacheBlendDisabled () { cache.end(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanteTest2.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanteTest2.java index 60b351ffd71..542d2dcaf91 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanteTest2.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/SpritePerformanteTest2.java @@ -13,14 +13,13 @@ * 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.graphics.GL10; 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.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.tests.utils.GdxTest; @@ -29,54 +28,56 @@ public class SpritePerformanteTest2 extends GdxTest { static final int SPRITES = 50000; Texture image; Texture image2; - Sprite[] sprites; + Sprite[] sprites; SpriteBatch batch; float timePassed = 0; int frames = 0; - - @Override public void create() { + + @Override + public void create () { image = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); - image.setFilter(TextureFilter.Linear, TextureFilter.Linear); + image.setFilter(TextureFilter.Linear, TextureFilter.Linear); image2 = new Texture(Gdx.files.internal("data/bobargb8888-32x32.png")); image2.setFilter(TextureFilter.Linear, TextureFilter.Linear); - + sprites = new Sprite[SPRITES]; - for(int i = 0; i < SPRITES; i++) { - Sprite sprite = new Sprite(i < SPRITES / 2?image:image2); + for (int i = 0; i < SPRITES; i++) { + Sprite sprite = new Sprite(i < SPRITES / 2 ? image : image2); sprite.setPosition((float)Math.random() * 800, (float)Math.random() * 600); sprites[i] = sprite; } - - batch = new SpriteBatch(); + + batch = new SpriteBatch(); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + float elapsed = Gdx.graphics.getDeltaTime(); - float scale = timePassed>0.5?1-timePassed / 2:0.5f + timePassed / 2; - + float scale = timePassed > 0.5 ? 1 - timePassed / 2 : 0.5f + timePassed / 2; + batch.begin(); batch.disableBlending(); - for(int i = 0; i < SPRITES; i++) { - if(i == SPRITES / 2) - batch.enableBlending(); - sprites[i].setRotation(sprites[i].getRotation() + elapsed * 45); + for (int i = 0; i < SPRITES; i++) { + if (i == SPRITES / 2) batch.enableBlending(); + sprites[i].setRotation(sprites[i].getRotation() + elapsed * 45); sprites[i].setScale(scale, scale); - sprites[i].draw(batch); + sprites[i].draw(batch); } - batch.end(); - + batch.end(); + timePassed += elapsed; frames++; - if(timePassed > 1.0f) { + if (timePassed > 1.0f) { Gdx.app.log("SpritePerformanceTest2", "fps: " + frames); timePassed = 0; frames = 0; } } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/StagePerformanceTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/StagePerformanceTest.java index a454bb3dfea..fcd2bb72d30 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/StagePerformanceTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/StagePerformanceTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.List; @@ -29,12 +30,12 @@ import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actors.FastImage; -import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.tests.utils.GdxTest; public class StagePerformanceTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } @@ -44,27 +45,30 @@ public class StagePerformanceTest extends GdxTest { BitmapFont font; Sprite[] sprites; boolean useStage = true; - - @Override public void create() { + + @Override + public void create () { batch = new SpriteBatch(); font = new BitmapFont(); stage = new Stage(24, 12, true); - regions = new TextureRegion[8*8]; - sprites = new Sprite[24*12]; - - Texture tex = new Texture(Gdx.files.internal("data/badlogic.jpg")); - for(int y = 0; y < 8; y++) { - for(int x = 0; x < 8; x++) { - regions[x + y*8] = new TextureRegion(tex, x * 32, y * 32, 32, 32); - } + regions = new TextureRegion[8 * 8]; + sprites = new Sprite[24 * 12]; + + Texture tex = new Texture(Gdx.files.internal("data/badlogic.jpg")); + for (int y = 0; y < 8; y++) { + for (int x = 0; x < 8; x++) { + regions[x + y * 8] = new TextureRegion(tex, x * 32, y * 32, 32, 32); + } } - + Random rand = new Random(); - for(int y = 0, i = 0; y < 12; y++) { - for(int x = 0; x < 24; x++) { + for (int y = 0, i = 0; y < 12; y++) { + for (int x = 0; x < 24; x++) { FastImage img = new FastImage("img" + i, regions[rand.nextInt(8 * 8)]); - img.x = x; img.y = y; - img.width = 1; img.height = 1; + img.x = x; + img.y = y; + img.width = 1; + img.height = 1; stage.addActor(img); sprites[i] = new Sprite(regions[rand.nextInt(8 * 8)]); sprites[i].setPosition(x, y); @@ -73,40 +77,41 @@ public class StagePerformanceTest extends GdxTest { } } } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - - if(useStage) { + + if (useStage) { stage.act(Gdx.graphics.getDeltaTime()); stage.getSpriteBatch().disableBlending(); Group root = stage.getRoot(); List actors = root.getActors(); -// for(int i = 0; i < actors.size(); i++) { -// actors.get(i).rotation += 45 * Gdx.graphics.getDeltaTime(); -// } - stage.draw(); - } else { +// for(int i = 0; i < actors.size(); i++) { +// actors.get(i).rotation += 45 * Gdx.graphics.getDeltaTime(); +// } + stage.draw(); + } else { batch.getProjectionMatrix().setToOrtho2D(0, 0, 24, 12); batch.getTransformMatrix().idt(); batch.disableBlending(); batch.begin(); - for(int i = 0; i < sprites.length; i++) { -// sprites[i].rotate(45 * Gdx.graphics.getDeltaTime()); + for (int i = 0; i < sprites.length; i++) { +// sprites[i].rotate(45 * Gdx.graphics.getDeltaTime()); sprites[i].draw(batch); - } + } batch.end(); } - + batch.getProjectionMatrix().setToOrtho2D(0, 0, 480, 320); batch.enableBlending(); batch.begin(); font.setColor(0, 0, 1, 1); font.setScale(2); - font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond() + (useStage?", stage": "sprite"), 10, 40); + font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond() + (useStage ? ", stage" : "sprite"), 10, 40); batch.end(); - - if(Gdx.input.justTouched()) { + + if (Gdx.input.justTouched()) { useStage = !useStage; } } 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 abce11c4e43..581b1bcc0ef 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/StageTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/StageTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.ArrayList; @@ -53,7 +54,8 @@ public class StageTest extends GdxTest implements InputProcessor { float scale = 1; float vScale = 1; - @Override public void create () { + @Override + public void create () { texture = new Texture(Gdx.files.internal("data/badlogicsmall.jpg")); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); font = new BitmapFont(); @@ -73,7 +75,7 @@ public class StageTest extends GdxTest implements InputProcessor { } uiTexture = new Texture(Gdx.files.internal("data/ui.png")); - uiTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear); + uiTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear); ui = new Stage(480, 320, false); Image blend = new Image("blend button", new TextureRegion(uiTexture, 0, 0, 64, 32)); blend.y = ui.height() - 32; @@ -88,10 +90,11 @@ public class StageTest extends GdxTest implements InputProcessor { ui.addActor(rotate); ui.addActor(scale); - Label fps = new Label("fps", font, "fps: 0"); - fps.x = 10; fps.y = 30; - fps.color.set(0, 1, 0, 1); - ui.addActor(fps); + Label fps = new Label("fps", font, "fps: 0"); + fps.x = 10; + fps.y = 30; + fps.color.set(0, 1, 0, 1); + ui.addActor(fps); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); renderer = new ImmediateModeRenderer10(); @@ -112,7 +115,8 @@ private void fillGroup (Group group, Texture texture) { } } - @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); @@ -175,14 +179,13 @@ private void fillGroup (Group group, Texture texture) { renderer.end(); Gdx.graphics.getGL10().glPointSize(4); - ((Label)ui.findActor("fps")).setText("fps: " + - Gdx.graphics.getFramesPerSecond() + ", actors " + images.size() + - ", groups " - + stage.getGroups().size()); + ((Label)ui.findActor("fps")).setText("fps: " + Gdx.graphics.getFramesPerSecond() + ", actors " + images.size() + + ", groups " + stage.getGroups().size()); ui.draw(); } - @Override public boolean touchDown (int x, int y, int pointer, int button) { + @Override + public boolean touchDown (int x, int y, int pointer, int button) { boolean touched = ui.touchDown(x, y, pointer, button); if (touched) { Actor hitActor = ui.getLastTouchedChild(); @@ -197,35 +200,43 @@ private void fillGroup (Group group, Texture texture) { return touched; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @Override + public boolean touchDragged (int x, int y, int pointer) { return false; } - @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) { return false; } - @Override public boolean keyTyped (char character) { + @Override + public boolean keyTyped (char character) { return false; } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { 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 82736ccd688..8f1f57302ea 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TerrainTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TerrainTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -41,7 +42,8 @@ public class TerrainTest extends GdxTest { boolean intersected = false; long lastTime = System.nanoTime(); - @Override public void create () { + @Override + public void create () { renderer = new ImmediateModeRenderer10(); chunk = new TerrainChunk(32, 32, 4); @@ -59,12 +61,13 @@ public class TerrainTest extends GdxTest { camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.position.set(0, 5, 5); - camera.direction.set(0, 0, 0).sub(camera.position).nor(); + camera.direction.set(0, 0, 0).sub(camera.position).nor(); camera.near = 0.5f; - camera.far = 300; + camera.far = 300; } - @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); @@ -183,7 +186,8 @@ private void buildIndices () { } } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextInputDialogTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextInputDialogTest.java index 30d46a2dff1..3c367b99cd5 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextInputDialogTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextInputDialogTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -26,38 +27,37 @@ public class TextInputDialogTest extends GdxTest { String message; SpriteBatch batch; BitmapFont font; - - public void create() { + + public void create () { message = "Touch screen for dialog"; batch = new SpriteBatch(); font = new BitmapFont(); } - - public void render() { + + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.draw(batch, message, 10, 40); batch.end(); - - if(Gdx.input.justTouched()) { + + if (Gdx.input.justTouched()) { Gdx.input.getTextInput(new TextInputListener() { @Override - public void input(String text) { + public void input (String text) { message = "message: " + text + ", touch screen for new dialog"; } - + @Override - public void canceled() { + public void canceled () { message = "cancled by user"; } }, "enter something funny", "funny"); } } - + @Override - public boolean needsGL20() { + public boolean needsGL20 () { return false; } - - + } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureAtlasTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureAtlasTest.java index fb909e85f38..708ed301af4 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureAtlasTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureAtlasTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -31,7 +32,7 @@ public class TextureAtlasTest extends GdxTest { BitmapFont font; public void create () { - batch = new SpriteBatch(); + batch = new SpriteBatch(); atlas = new TextureAtlas(Gdx.files.internal("data/pack")); badlogic = atlas.createSprite("badlogicslice"); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDataTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDataTest.java index 0bbe4cfed4c..927c62822d9 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDataTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDataTest.java @@ -13,24 +13,22 @@ * 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.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; -import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FileTextureData; -import com.badlogic.gdx.graphics.glutils.PixmapTextureData; import com.badlogic.gdx.tests.utils.GdxTest; public class TextureDataTest extends GdxTest { private SpriteBatch spriteBatch; private Texture texture; - + public void create () { spriteBatch = new SpriteBatch(); -// texture = new Texture(new PixmapTextureData(new Pixmap(Gdx.files.internal("data/t8890.png")), null, false, true)); +// texture = new Texture(new PixmapTextureData(new Pixmap(Gdx.files.internal("data/t8890.png")), null, false, true)); texture = new Texture(new FileTextureData(Gdx.files.internal("data/t8890.png"), null, null, false)); } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDownloadTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDownloadTest.java index 4655e1f804d..3b7ba1f3db8 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDownloadTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureDownloadTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.io.IOException; @@ -32,7 +33,7 @@ public class TextureDownloadTest extends GdxTest { @Override - public boolean needsGL20() { + public boolean needsGL20 () { return false; } @@ -41,26 +42,26 @@ public boolean needsGL20() { SpriteBatch batch; public static class URLHandle extends FileHandle { - final URL url; - - public URLHandle(String url) { + final URL url; + + public URLHandle (String url) { try { this.url = new URL(url); - } catch(Exception e) { + } catch (Exception e) { throw new GdxRuntimeException("Couldn't create URLHandle for '" + url + "'", e); } } - + @Override - public FileHandle child(String name) { + public FileHandle child (String name) { return null; } @Override - public FileHandle parent() { + public FileHandle parent () { return null; - } - + } + public InputStream read () { try { return url.openStream(); @@ -69,11 +70,12 @@ public InputStream read () { } } } - - @Override public void create() { + + @Override + public void create () { // POT image, mananged potTexture = new Texture(new URLHandle("http://libgdx.badlogicgames.com/bob.png")); - + // non-POT image, not managed! Pixmap pixmap = new Pixmap(new URLHandle("http://libgdx.badlogicgames.com/libgdx.png")); int width = MathUtils.nextPowerOfTwo(pixmap.getWidth()); @@ -83,11 +85,12 @@ public InputStream read () { nonPotTexture = new TextureRegion(new Texture(potPixmap), 0, 0, pixmap.getWidth(), pixmap.getHeight()); pixmap.dispose(); potPixmap.dispose(); - + batch = new SpriteBatch(); } - - @Override public void render() { + + @Override + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureFormatTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureFormatTest.java index f55a70adde7..d8c4ea082d3 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureFormatTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureFormatTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -25,16 +26,17 @@ public class TextureFormatTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } Texture[] nonMipMapped = new Texture[6]; - Texture[] mipMapped = new Texture[6]; + Texture[] mipMapped = new Texture[6]; SpriteBatch batch; - + @Override - public void create() { + public void create () { FileHandle file = Gdx.files.internal("data/bobargb8888-32x32.png"); nonMipMapped[0] = new Texture(file, Format.Alpha, false); nonMipMapped[1] = new Texture(file, Format.LuminanceAlpha, false); @@ -42,26 +44,26 @@ public void create() { nonMipMapped[3] = new Texture(file, Format.RGB565, false); nonMipMapped[4] = new Texture(file, Format.RGBA8888, false); nonMipMapped[5] = new Texture(file, Format.RGBA4444, false); - + mipMapped[0] = new Texture(file, Format.Alpha, true); mipMapped[1] = new Texture(file, Format.LuminanceAlpha, true); mipMapped[2] = new Texture(file, Format.RGB888, true); mipMapped[3] = new Texture(file, Format.RGB565, true); mipMapped[4] = new Texture(file, Format.RGBA8888, true); mipMapped[5] = new Texture(file, Format.RGBA4444, true); - + batch = new SpriteBatch(); } - + @Override - public void render() { + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); - for(int i = 0; i < 6; i++) { + for (int i = 0; i < 6; i++) { batch.draw(nonMipMapped[i], i * 32, 0); } - for(int i = 0; i < 6; i++) { + for (int i = 0; i < 6; i++) { batch.draw(mipMapped[i], i * 32, 32); } batch.end(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TexturePackerAtlasTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TexturePackerAtlasTest.java index 509013bf3a7..1d76a3a4681 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TexturePackerAtlasTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TexturePackerAtlasTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; public class TexturePackerAtlasTest { 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 8bc1980de4a..8c64bd44c12 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureRenderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TextureRenderTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.ArrayList; @@ -37,8 +38,9 @@ public class TextureRenderTest extends GdxTest { private ArrayList rects = new ArrayList(); Color color = new Color(Color.GREEN); - @Override public void create () { - camera = new OrthographicCamera(480, 320); + @Override + public void create () { + camera = new OrthographicCamera(480, 320); camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0); Pixmap pixmap = new Pixmap(Gdx.files.internal("data/badlogic.jpg")); @@ -104,7 +106,8 @@ public class TextureRenderTest extends GdxTest { } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); @@ -161,7 +164,8 @@ private static class SimpleRect { } } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TileTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TileTest.java index 17da6536da9..88d98d0b2a1 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TileTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TileTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -39,8 +40,9 @@ public class TileTest extends GdxTest { OrthoCamController camController; long startTime = System.nanoTime(); - @Override public void create () { - cam = new OrthographicCamera(480, 320); + @Override + public void create () { + cam = new OrthographicCamera(480, 320); cam.position.set(WIDTH * 32 / 2, HEIGHT * 32 / 2, 0); camController = new OrthoCamController(cam); Gdx.input.setInputProcessor(camController); @@ -64,7 +66,8 @@ public class TileTest extends GdxTest { } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.gl10; gl.glClear(GL10.GL_COLOR_BUFFER_BIT); cam.update(); @@ -87,7 +90,8 @@ public class TileTest extends GdxTest { } } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapTest.java index fdecc43e58b..b1b9594dc44 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapTest.java @@ -16,8 +16,6 @@ package com.badlogic.gdx.tests; -import java.util.StringTokenizer; - import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; @@ -26,25 +24,22 @@ import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.tiled.TileAtlas; +import com.badlogic.gdx.graphics.g2d.tiled.TileMapRenderer; import com.badlogic.gdx.graphics.g2d.tiled.TiledLoader; import com.badlogic.gdx.graphics.g2d.tiled.TiledMap; -import com.badlogic.gdx.graphics.g2d.tiled.TileMapRenderer; import com.badlogic.gdx.graphics.g2d.tiled.TiledObject; import com.badlogic.gdx.graphics.g2d.tiled.TiledObjectGroup; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.OrthoCamController; -import com.badlogic.gdx.utils.IntArray; -/** - * @author David Fraska - * */ +/** @author David Fraska */ public class TiledMapTest extends GdxTest { private static final boolean automove = true; - private static final int[] layersList = {2,3}; + private static final int[] layersList = {2, 3}; SpriteBatch spriteBatch; BitmapFont font; @@ -61,17 +56,18 @@ public class TiledMapTest extends GdxTest { long startTime = System.nanoTime(); Vector3 tmp = new Vector3(); - @Override public void render () { + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + if (automove) { updateCameraPosition(); } - + cam.zoom = 0.9f; cam.update(); - //tileMapRenderer.getProjectionMatrix().set(cam.combined); //Not required when using tileMapRenderer.render(cam) - tileMapRenderer.render(cam);//, layersList); + // tileMapRenderer.getProjectionMatrix().set(cam.combined); //Not required when using tileMapRenderer.render(cam) + tileMapRenderer.render(cam);// , layersList); spriteBatch.begin(); font.draw(spriteBatch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 20, 20); @@ -79,7 +75,7 @@ public class TiledMapTest extends GdxTest { 40); font.draw(spriteBatch, "InitialRow, LastRow: " + tileMapRenderer.getInitialRow() + "," + tileMapRenderer.getLastRow(), 20, 60); - + tmp.set(0, 0, 0); cam.unproject(tmp); font.draw(spriteBatch, "Location: " + tmp.x + "," + tmp.y, 20, 80); @@ -87,7 +83,7 @@ public class TiledMapTest extends GdxTest { } private void updateCameraPosition () { - cam.position.add(camDirection.tmp().mul(Gdx.graphics.getDeltaTime()).mul(5*tileMapRenderer.getUnitsPerTileX())); + cam.position.add(camDirection.tmp().mul(Gdx.graphics.getDeltaTime()).mul(5 * tileMapRenderer.getUnitsPerTileX())); if (cam.position.x < 0) { cam.position.x = 0; @@ -107,7 +103,8 @@ private void updateCameraPosition () { } } - @Override public void create () { + @Override + public void create () { int i; long startTime, endTime; font = new BitmapFont(); @@ -145,17 +142,18 @@ private void updateCameraPosition () { } } - float aspectRatio = (float) Gdx.graphics.getWidth() / (float) Gdx.graphics.getHeight(); + float aspectRatio = (float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight(); cam = new OrthographicCamera(100f * aspectRatio, 100f); - - cam.position.set(tileMapRenderer.getMapWidthUnits()/2, tileMapRenderer.getMapHeightUnits() / 2, 0); + + cam.position.set(tileMapRenderer.getMapWidthUnits() / 2, tileMapRenderer.getMapHeightUnits() / 2, 0); camController = new OrthoCamController(cam); Gdx.input.setInputProcessor(camController); maxCamPosition.set(tileMapRenderer.getMapWidthUnits(), tileMapRenderer.getMapHeightUnits()); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/TransformationTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/TransformationTest.java index 6a9df9146e1..32f9cc8353b 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/TransformationTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/TransformationTest.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests; import java.util.HashMap; @@ -24,13 +25,13 @@ public class TransformationTest extends InputAdapter implements ApplicationListe float timePassed = 0; @Override - public void create() { + public void create () { image = new Texture(Gdx.files.internal("data/sys.png")); image.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); image.setWrap(Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge); - float w = 100;//Gdx.graphics.getWidth()/2; - float h = 80;//Gdx.graphics.getHeight()/2; + float w = 100;// Gdx.graphics.getWidth()/2; + float h = 80;// Gdx.graphics.getHeight()/2; sprite = Decal.newDecal(20, 20, new TextureRegion(image), false); @@ -56,18 +57,18 @@ public void create() { } @Override - public void render() { + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl11.glLoadIdentity(); Gdx.gl11.glScalef(0.02f, 0.02f, 1); - + Action a = keyActions.get(key); - if(a != null) { + if (a != null) { a.perform(sprite); } float elapsed = Gdx.graphics.getDeltaTime(); - float translate = timePassed > 0.5 ? (float)Math.random() - timePassed / 2 : (float)Math.random()/2 + timePassed / 2; + float translate = timePassed > 0.5 ? (float)Math.random() - timePassed / 2 : (float)Math.random() / 2 + timePassed / 2; translate *= (-0.5 + Math.random()); cam.update(); @@ -78,125 +79,130 @@ public void render() { batch.flush(); timePassed += elapsed; - if(timePassed > 1.0f) { + if (timePassed > 1.0f) { timePassed = 0; } } @Override - public boolean keyDown(int keycode) { + public boolean keyDown (int keycode) { key = keycode; return true; } @Override - public boolean keyUp(int keycode) { + public boolean keyUp (int keycode) { key = -1; return true; } @Override - public void resize(int width, int height) { + public void resize (int width, int height) { cam = new PerspectiveCamera(45, width, height); - //cam = new OrthographicCamera(width, height); + // cam = new OrthographicCamera(width, height); cam.near = 0.1f; cam.far = 1000f; cam.position.set(0, 0, 100); cam.direction.set(0, 0, -1); } - - @Override - public void resume() { + public void resume () { } @Override - public void pause() { + public void pause () { } @Override - public void dispose() { + public void dispose () { } private abstract class Action { float dir; - protected Action(float dir) { + protected Action (float dir) { this.dir = dir; } - public abstract void perform(Decal d); + public abstract void perform (Decal d); } + private class RotateZ extends Action { - public RotateZ(float dir) { + public RotateZ (float dir) { super(dir); } @Override - public void perform(Decal d) { + public void perform (Decal d) { d.rotateZ(Gdx.graphics.getDeltaTime() * dir); } } + private class RotateY extends Action { - public RotateY(float dir) { + public RotateY (float dir) { super(dir); } @Override - public void perform(Decal d) { + public void perform (Decal d) { d.rotateY(Gdx.graphics.getDeltaTime() * dir); } } + private class RotateX extends Action { - public RotateX(float dir) { + public RotateX (float dir) { super(dir); } @Override - public void perform(Decal d) { + public void perform (Decal d) { d.rotateX(Gdx.graphics.getDeltaTime() * dir); } } + private class TransX extends Action { - public TransX(float dir) { + public TransX (float dir) { super(dir); } @Override - public void perform(Decal d) { + public void perform (Decal d) { d.translateX(Gdx.graphics.getDeltaTime() * dir); } } + private class TransY extends Action { - public TransY(float dir) { + public TransY (float dir) { super(dir); } @Override - public void perform(Decal d) { + public void perform (Decal d) { d.translateY(Gdx.graphics.getDeltaTime() * dir); } } + private class TransZ extends Action { - public TransZ(float dir) { + public TransZ (float dir) { super(dir); } @Override - public void perform(Decal d) { + public void perform (Decal d) { d.translateZ(Gdx.graphics.getDeltaTime() * dir); } } + private class Scale extends Action { - public Scale(float dir) { + public Scale (float dir) { super(dir); } @Override - public void perform(Decal d) { + public void perform (Decal d) { d.setScale(Gdx.graphics.getDeltaTime() * dir + d.getScaleX(), Gdx.graphics.getDeltaTime() * dir + d.getScaleY()); } } -} \ No newline at end of file +} 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 42596808104..da61a296ffb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/UITest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/UITest.java @@ -1,11 +1,12 @@ + package com.badlogic.gdx.tests; + import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; -import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actors.Image; @@ -30,103 +31,104 @@ import com.badlogic.gdx.tests.utils.GdxTest; public class UITest extends GdxTest { - - - String[] listEntries = { "This is a list entry", "And another one", "The meaning of life", "Is hard to come by", - "This is a list entry", "And another one", "The meaning of life", "Is hard to come by", - "This is a list entry", "And another one", "The meaning of life", "Is hard to come by", - "This is a list entry", "And another one", "The meaning of life", "Is hard to come by", - "This is a list entry", "And another one", "The meaning of life", "Is hard to come by" - }; - - Skin skin; + + String[] listEntries = {"This is a list entry", "And another one", "The meaning of life", "Is hard to come by", + "This is a list entry", "And another one", "The meaning of life", "Is hard to come by", "This is a list entry", + "And another one", "The meaning of life", "Is hard to come by", "This is a list entry", "And another one", + "The meaning of life", "Is hard to come by", "This is a list entry", "And another one", "The meaning of life", + "Is hard to come by"}; + + Skin skin; Stage ui; SpriteBatch batch; Actor root; - + @Override - public void create() { - batch = new SpriteBatch(); + public void create () { + batch = new SpriteBatch(); skin = new Skin(Gdx.files.internal("data/uiskin.xml"), Gdx.files.internal("data/uiskin.png")); skin.getTexture().setFilter(TextureFilter.Nearest, TextureFilter.Nearest); TextureRegion image = new TextureRegion(new Texture(Gdx.files.internal("data/badlogicsmall.jpg"))); TextureRegion image2 = new TextureRegion(new Texture(Gdx.files.internal("data/badlogic.jpg"))); - ui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); + ui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false); Gdx.input.setInputProcessor(ui); - - Window window = skin.newWindow("window", ui, "Dialog", 320, 240); - window.x = window.y = 0; - - final Button button = skin.newButton("button-sl", "Single"); + + Window window = skin.newWindow("window", ui, "Dialog", 320, 240); + window.x = window.y = 0; + + final Button button = skin.newButton("button-sl", "Single"); final ToggleButton buttonMulti = skin.newToggleButton("button-ml-tgl", "Multi\nLine\nToggle"); final ImageButton imgButton = skin.newImageButton("button-img", image); final ImageToggleButton imgToggleButton = skin.newImageToggleButton("button-img-tgl", image); final CheckBox checkBox = skin.newCheckBox("checkbox", "Check me"); final Slider slider = skin.newSlider("slider", 100, 0, 10, 1); - final TextField textfield = skin.newTextField("textfield", 100); + final TextField textfield = skin.newTextField("textfield", 100); final ComboBox combobox = skin.newComboBox("combo", new String[] {"Android", "Windows", "Linux", "OSX"}, ui); final Image imageActor = new Image("image", image2); - final ScrollPane scrollPane = skin.newScrollPane("scroll", ui, imageActor, 100, 100); + final ScrollPane scrollPane = skin.newScrollPane("scroll", ui, imageActor, 100, 100); final List list = skin.newList("list", listEntries); final ScrollPane scrollPane2 = skin.newScrollPane("scroll2", ui, list, 100, 100); final SplitPane splitPane = skin.newSplitPane("split", ui, scrollPane, scrollPane2, false, 0, 0, "default-horizontal"); final Label label = skin.newLabel("label", "fps:"); - + imgButton.setImageSize(16, 20); imgToggleButton.setImageSize(10, 10); - + TableLayout layout = window.getTableLayout(); layout.defaults().spaceBottom(10); layout.row().fill().expandX(); layout.add(button); - layout.add(buttonMulti); + layout.add(buttonMulti); layout.add(imgButton); layout.add(imgToggleButton); layout.row(); layout.add(checkBox); layout.add(slider).fillX().colspan(3); - layout.row(); - layout.add(combobox); + layout.row(); + layout.add(combobox); layout.add(textfield).expandX().fillX().colspan(3); layout.row(); layout.add(splitPane).fill().expand().colspan(4); layout.row(); layout.add(label).fill().expand(); - - textfield.setTextFieldListener(new TextFieldListener() { - @Override public void keyTyped (TextField textField, char key) { - if(key == '\n') textField.getOnscreenKeyboard().show(false); + + textfield.setTextFieldListener(new TextFieldListener() { + @Override + public void keyTyped (TextField textField, char key) { + if (key == '\n') textField.getOnscreenKeyboard().show(false); } }); - + slider.setValueChangedListener(new ValueChangedListener() { - - @Override public void changed (Slider slider, float value) { + + @Override + public void changed (Slider slider, float value) { Gdx.app.log("UITest", "slider: " + value); } }); - + ui.addActor(window); } @Override - public void render() { + public void render () { Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); - + ((Label)ui.findActor("label")).setText("fps: " + Gdx.graphics.getFramesPerSecond()); - + ui.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f)); ui.draw(); Table.drawDebug(ui); } - + @Override - public void resize(int width, int height) { - ui.setViewport(width, height, false); + public void resize (int width, int height) { + ui.setViewport(width, height, false); } - - @Override public boolean needsGL20 () { + + @Override + public boolean needsGL20 () { return false; } -} \ No newline at end of file +} diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VBOVATest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VBOVATest.java index da1b4c7c5e7..c0e20a1d954 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VBOVATest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VBOVATest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; @@ -45,7 +46,8 @@ public class VBOVATest extends GdxTest { int frames = 0; boolean isStatic = false; - @Override public void create () { + @Override + public void create () { int viewport[] = new int[4]; Gdx.gl10.glGetIntegerv(GL11.GL_VIEWPORT, viewport, 0); Gdx.gl10.glGetIntegerv(GL11.GL_VIEWPORT, viewport, 0); @@ -84,7 +86,8 @@ public class VBOVATest extends GdxTest { startTime = System.nanoTime(); } - @Override public void render () { + @Override + public void render () { Gdx.gl11.glClear(GL11.GL_COLOR_BUFFER_BIT); switch (mode) { @@ -118,7 +121,7 @@ public class VBOVATest extends GdxTest { } if (mode == 5) { vaibo.setIndices(indices, 0, indices.length); - } + } if (mode <= 2) { Gdx.gl11.glDrawArrays(GL11.GL_TRIANGLES, 0, TRIANGLES * 3); @@ -150,14 +153,16 @@ public class VBOVATest extends GdxTest { frames++; } - @Override public void resume () { + @Override + public void resume () { vbo.invalidate(); vbosd.invalidate(); ibo.invalidate(); ibosd.invalidate(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayClassTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayClassTest.java index 3a10684fd52..1f0a5fa47d9 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayClassTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayClassTest.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ShortBuffer; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; 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; import com.badlogic.gdx.graphics.glutils.VertexArray; @@ -35,16 +33,19 @@ public class VertexArrayClassTest extends GdxTest { VertexArray va; ShortBuffer indices; - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public void dispose () { + @Override + public void dispose () { texture.dispose(); va.dispose(); } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.gl10; gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); @@ -62,7 +63,8 @@ public class VertexArrayClassTest extends GdxTest { va.unbind(); } - @Override public void create () { + @Override + public void create () { va = new VertexArray(3, new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_Position"), new VertexAttribute( VertexAttributes.Usage.TextureCoordinates, 2, "a_TexCoords"), new VertexAttribute(VertexAttributes.Usage.ColorPacked, 4, "a_Color")); 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 d3c8cfa4c80..f0088b70754 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexArrayTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ByteBuffer; @@ -29,7 +30,8 @@ public class VertexArrayTest extends GdxTest { ShortBuffer indices; final int BYTES_PER_VERTEX = (3 + 4) * 4; - @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); @@ -46,7 +48,8 @@ public class VertexArrayTest extends GdxTest { gl.glDrawElements(GL10.GL_TRIANGLES, 3, GL10.GL_UNSIGNED_SHORT, indices); } - @Override public void create () { + @Override + public void create () { ByteBuffer buffer = ByteBuffer.allocateDirect(BYTES_PER_VERTEX * 3); buffer.order(ByteOrder.nativeOrder()); vertices = buffer.asFloatBuffer(); @@ -66,7 +69,8 @@ public class VertexArrayTest extends GdxTest { indices.flip(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectClassTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectClassTest.java index c96a72e55a4..ccf811a34cd 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectClassTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectClassTest.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ShortBuffer; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; 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; import com.badlogic.gdx.graphics.glutils.VertexBufferObject; @@ -35,16 +33,19 @@ public class VertexBufferObjectClassTest extends GdxTest { VertexBufferObject vbo; ShortBuffer indices; - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public void dispose () { + @Override + public void dispose () { texture.dispose(); vbo.dispose(); } - @Override public void render () { + @Override + public void render () { GL10 gl = Gdx.gl10; gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); @@ -62,7 +63,8 @@ public class VertexBufferObjectClassTest extends GdxTest { vbo.unbind(); } - @Override public void create () { + @Override + public void create () { vbo = new VertexBufferObject(true, 3, new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_Position"), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_TexCoords"), new VertexAttribute( VertexAttributes.Usage.ColorPacked, 4, "a_Color")); @@ -76,7 +78,8 @@ public class VertexBufferObjectClassTest extends GdxTest { texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); } - @Override public void resume () { + @Override + public void resume () { vbo.invalidate(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectShaderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectShaderTest.java index 516da81536b..c12d8aa462a 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectShaderTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectShaderTest.java @@ -13,19 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ShortBuffer; import com.badlogic.gdx.Gdx; -import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; -import com.badlogic.gdx.graphics.Texture.TextureFilter; -import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.graphics.glutils.VertexBufferObject; import com.badlogic.gdx.tests.utils.GdxTest; @@ -38,19 +36,19 @@ public class VertexBufferObjectShaderTest extends GdxTest { ShortBuffer indices; @Override - public boolean needsGL20() { + public boolean needsGL20 () { return true; } @Override - public void dispose() { + public void dispose () { texture.dispose(); vbo.dispose(); shader.dispose(); } @Override - public void render() { + public void render () { GL20 gl = Gdx.gl20; gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); gl.glClear(GL20.GL_COLOR_BUFFER_BIT); @@ -58,55 +56,40 @@ public void render() { gl.glEnable(GL20.GL_TEXTURE_2D); shader.begin(); shader.setUniformi("u_texture", 0); - texture.bind(); + texture.bind(); vbo.bind(shader); - gl.glDrawElements(GL20.GL_TRIANGLES, 3, GL20.GL_UNSIGNED_SHORT, indices); + gl.glDrawElements(GL20.GL_TRIANGLES, 3, GL20.GL_UNSIGNED_SHORT, indices); vbo.unbind(shader); shader.end(); } @Override - public void create() { - 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;" - + "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 = a_position; \n" - + "} \n"; - String fragmentShader = "#ifdef GL_ES\n" - + "precision mediump float;\n" - + "#endif\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" - + "}"; + public void create () { + 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;" + "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 = a_position; \n" + "} \n"; + String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\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); - vbo = new VertexBufferObject(true, 3, - new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"), - new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2,"a_texCoords"), - new VertexAttribute(VertexAttributes.Usage.ColorPacked, 4, "a_color")); - float[] vertices = new float[] { -1, -1, 0, 0,Color.toFloatBits(1f, 0f, 0f, 1f), - 0, 1, 0.5f, 1.0f, Color.toFloatBits(0f, 1f, 0f, 1f), - 1, -1, 1, 0, Color.toFloatBits(0f, 0f, 1f, 1f) }; - vbo.setVertices(vertices, 0, vertices.length); - indices = BufferUtils.newShortBuffer(3); - indices.put(new short[] { 0, 1, 2 }); - indices.flip(); + shader = new ShaderProgram(vertexShader, fragmentShader); + vbo = new VertexBufferObject(true, 3, new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"), + new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoords"), new VertexAttribute( + VertexAttributes.Usage.ColorPacked, 4, "a_color")); + float[] vertices = new float[] {-1, -1, 0, 0, Color.toFloatBits(1f, 0f, 0f, 1f), 0, 1, 0.5f, 1.0f, + Color.toFloatBits(0f, 1f, 0f, 1f), 1, -1, 1, 0, Color.toFloatBits(0f, 0f, 1f, 1f)}; + vbo.setVertices(vertices, 0, vertices.length); + indices = BufferUtils.newShortBuffer(3); + indices.put(new short[] {0, 1, 2}); + indices.flip(); - texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); + texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); } - + @Override - public void resume() { + public void resume () { vbo.invalidate(); } 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 e201241b116..48fc30c1c14 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VertexBufferObjectTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.FloatBuffer; @@ -27,7 +28,8 @@ public class VertexBufferObjectTest extends GdxTest { int vboHandle; int vboIndexHandle; - @Override public void render () { + @Override + public void render () { GL11 gl = Gdx.graphics.getGL11(); gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); @@ -45,7 +47,8 @@ public class VertexBufferObjectTest extends GdxTest { gl.glDrawElements(GL11.GL_TRIANGLES, 3, GL11.GL_UNSIGNED_SHORT, 0); } - @Override public void create () { + @Override + public void create () { 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}); @@ -92,7 +95,8 @@ public void resume () { gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/VibratorTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/VibratorTest.java index c7a0e1ab09b..512fdd977dd 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VibratorTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VibratorTest.java @@ -13,6 +13,7 @@ * 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,27 +24,27 @@ public class VibratorTest extends GdxTest { - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } SpriteBatch batch; BitmapFont font; - + @Override - public void create() { + public void create () { batch = new SpriteBatch(); font = new BitmapFont(); } - - @Override - public void render() { + + @Override + public void render () { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.begin(); font.draw(batch, "Touch screen to vibrate", 100, 100); batch.end(); - - if(Gdx.input.justTouched()) - Gdx.input.vibrate(100); + + if (Gdx.input.justTouched()) Gdx.input.vibrate(100); } } 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 dbbb0e1cba8..63cb6a4dea2 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/VorbisTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/VorbisTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.nio.ShortBuffer; @@ -25,7 +26,8 @@ public class VorbisTest extends GdxTest { - @Override public void create () { + @Override + public void create () { VorbisDecoder decoder = null; if (Gdx.app.getType() == ApplicationType.Android) decoder = new VorbisDecoder("/sdcard/audio/schism.ogg"); @@ -45,7 +47,8 @@ public class VorbisTest extends GdxTest { decoder.dispose(); } - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return false; } 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 74540f0edec..b149ab5c4ee 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/WaterRipples.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/WaterRipples.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests; import java.util.Random; @@ -57,7 +58,8 @@ public class WaterRipples extends GdxTest implements InputProcessor { float[][] intp; float[] vertices; - @Override public void create () { + @Override + public void create () { camera = new PerspectiveCamera(90, Gdx.graphics.getWidth(), Gdx.graphics.getWidth()); camera.position.set((WIDTH) / 2.0f, (HEIGHT) / 2.0f, WIDTH / 2.0f); @@ -161,7 +163,8 @@ private void touchWater (Vector3 point) { 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); @@ -203,45 +206,54 @@ private void touchWater (Vector3 point) { batch.end(); } - @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) { return false; } - @Override public boolean keyTyped (char character) { + @Override + public boolean keyTyped (char character) { return false; } - @Override public boolean touchDown (int x, int y, int pointer, int newParam) { + @Override + public boolean touchDown (int x, int y, int pointer, int newParam) { // 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, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { return false; } - @Override public boolean touchDragged (int x, int y, int pointer) { + @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 needsGL20 () { + @Override + public boolean needsGL20 () { return false; } - @Override public boolean touchMoved (int x, int y) { + @Override + public boolean touchMoved (int x, int y) { return false; } - @Override public boolean scrolled (int amount) { + @Override + public boolean scrolled (int amount) { return false; } 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 d325a8ae585..96b54c104c8 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 @@ -42,7 +42,8 @@ public class ApplyForce extends Box2DTest { Body m_body; - @Override protected void createWorld (World world) { + @Override + protected void createWorld (World world) { world.setGravity(new Vector2(0, 0)); float k_restitution = 0.4f; @@ -179,7 +180,7 @@ public void 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 fe4fe515bde..d93e62944d0 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 @@ -44,7 +44,8 @@ public class BodyTypes extends Box2DTest { Body m_platform; float m_speed; - @Override protected void createWorld (World world) { + @Override + protected void createWorld (World world) { Body ground; { @@ -130,7 +131,8 @@ public class BodyTypes extends Box2DTest { private final Vector2 tmp = new Vector2(); - @Override public boolean keyDown (int keyCode) { + @Override + public boolean keyDown (int keyCode) { if (keyCode == Keys.D) m_platform.setType(BodyType.DynamicBody); if (keyCode == Keys.S) m_platform.setType(BodyType.StaticBody); if (keyCode == Keys.K) { @@ -142,7 +144,8 @@ public class BodyTypes extends Box2DTest { return false; } - @Override public void render () { + @Override + public void render () { if (m_platform.getType() == BodyType.KinematicBody) { Vector2 p = m_platform.getTransform().getPosition(); Vector2 v = m_platform.getLinearVelocity(); @@ -157,8 +160,8 @@ public class BodyTypes extends Box2DTest { 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 a1e29027fed..e2acbff6afd 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 @@ -47,19 +47,16 @@ 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 - * - */ + * @author badlogicgames@gmail.com */ public abstract class Box2DTest implements ApplicationListener, InputProcessor { /** the camera **/ protected OrthographicCamera camera; /** the renderer **/ protected Box2DDebugRenderer renderer; - + SpriteBatch batch; BitmapFont font; @@ -80,7 +77,8 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { /** temp vector **/ protected Vector2 tmp = new Vector2(); - @Override public void render () { + @Override + public void render () { // update the world with a fixed time step long startTime = System.nanoTime(); world.step(Gdx.app.getGraphics().getDeltaTime(), 3, 3); @@ -96,13 +94,14 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { // render the world using the debug renderer renderer.render(world); float renderTime = (System.nanoTime() - startTime) / 1000000000.0f; - + batch.begin(); font.draw(batch, "fps:" + Gdx.graphics.getFramesPerSecond() + ", update: " + updateTime + ", render: " + renderTime, 0, 20); batch.end(); } - @Override public void create () { + @Override + public void create () { // 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 @@ -110,7 +109,7 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { // 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(48, 32); + camera = new OrthographicCamera(48, 32); camera.position.set(0, 15, 0); // create the debug renderer @@ -126,12 +125,13 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { // call abstract method to populate the world createWorld(world); - + batch = new SpriteBatch(); font = new BitmapFont(); } - @Override public void dispose () { + @Override + public void dispose () { renderer.dispose(); world.dispose(); @@ -141,22 +141,26 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { hitBody = null; } - @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; } /** we instantiate this vector and the callback here so we don't irritate the GC **/ Vector3 testPoint = new Vector3(); QueryCallback callback = new QueryCallback() { - @Override public boolean reportFixture (Fixture fixture) { + @Override + public boolean reportFixture (Fixture fixture) { // if the hit point is inside the fixture of the body // we report it if (fixture.testPoint(testPoint.x, testPoint.y)) { @@ -166,8 +170,9 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { return true; } }; - - @Override public boolean touchDown (int x, int y, int pointer, int button) { + + @Override + public boolean touchDown (int x, int y, int pointer, int button) { // translate the mouse coordinates to world coordinates camera.unproject(testPoint.set(x, y, 0)); // ask the world which bodies are within the given @@ -198,9 +203,10 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { } /** another temporary vector **/ - Vector2 target = new Vector2(); + Vector2 target = new Vector2(); - @Override public boolean touchDragged (int x, int y, int pointer) { + @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 @@ -211,7 +217,8 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { return false; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { // if a mouse joint exists we simply destroy it if (mouseJoint != null) { world.destroyJoint(mouseJoint); @@ -219,24 +226,26 @@ public abstract class Box2DTest implements ApplicationListener, InputProcessor { } return false; } - - @Override public boolean touchMoved(int x, int y) { + + @Override + public boolean touchMoved (int x, int y) { return false; } - - @Override public boolean scrolled(int amount) { + + @Override + public boolean scrolled (int amount) { return false; } - - public void pause() { - + + public void pause () { + } - - public void resume() { - + + public void resume () { + } - - public void resize(int width, int height) { - + + public void resize (int width, int height) { + } } 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 a144b2dc9c2..9fcee9c309a 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 @@ -41,7 +41,8 @@ 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(); 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 a857f29e117..0a16b7f571e 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 @@ -42,7 +42,8 @@ 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(); 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 2b6f9f2d10b..fb783602061 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 @@ -39,7 +39,8 @@ public class Chain extends Box2DTest { - @Override protected void createWorld (World world) { + @Override + protected void createWorld (World world) { Body ground; { 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 8f0e878bdd7..31c5a3bd0aa 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 @@ -39,7 +39,8 @@ 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); 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 a1c94775c7c..a8e08d4abc1 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 @@ -51,7 +51,8 @@ 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)); 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 a24c7149249..46fddd316c1 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 @@ -40,7 +40,8 @@ public class ContinuousTest extends Box2DTest { Body m_body; float m_angularVelocity; - @Override protected void createWorld (World world) { + @Override + protected void createWorld (World world) { { BodyDef bd = new BodyDef(); bd.position.set(0, 0); 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 8462f8fe838..eeaadf245fe 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 @@ -38,7 +38,8 @@ 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)); 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 508e976b443..8d5d818ce31 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 @@ -50,7 +50,8 @@ enum State { 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); @@ -90,7 +91,8 @@ enum State { world.setContactFilter(new ContactFilter() { - @Override public boolean shouldCollide (Fixture fixtureA, Fixture fixtureB) { + @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) 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 436823b40ac..0fd2ecc6462 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 @@ -41,7 +41,8 @@ public class Prismatic extends Box2DTest { PrismaticJoint m_joint; - @Override protected void createWorld (World world) { + @Override + protected void createWorld (World world) { Body ground; { @@ -97,10 +98,10 @@ public void 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 9bd57fcaa3c..209cf6e082a 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 @@ -36,7 +36,8 @@ import com.badlogic.gdx.physics.box2d.World; public class Pyramid extends Box2DTest { - @Override protected void createWorld (World world) { + @Override + protected void createWorld (World world) { { BodyDef bd = new BodyDef(); Body ground = world.createBody(bd); 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 188b17bdfd1..625a6879f3e 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 @@ -36,7 +36,8 @@ import com.badlogic.gdx.physics.box2d.World; public class SimpleTest extends Box2DTest { - @Override protected void createWorld (World world) { + @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 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 052032d8865..cd63bc7fdf7 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 @@ -39,7 +39,8 @@ 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); 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 4ac3430e216..86b6f2bcf9d 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 @@ -38,7 +38,8 @@ import com.badlogic.gdx.physics.box2d.World; public class VaryingRestitution extends Box2DTest { - @Override protected void createWorld (World world) { + @Override + protected void createWorld (World world) { { BodyDef bd = new BodyDef(); Body ground = world.createBody(bd); 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 aa899c1f557..fc7b8077579 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 @@ -46,7 +46,8 @@ public class VerticalStack extends Box2DTest { 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(); Body ground = world.createBody(bd); @@ -93,7 +94,8 @@ public class VerticalStack extends Box2DTest { m_bullet = null; } - @Override public boolean keyDown (int keyCode) { + @Override + public boolean keyDown (int keyCode) { if (keyCode == Input.Keys.COMMA) { if (m_bullet != null) { world.destroyBody(m_bullet); @@ -129,8 +131,8 @@ public void 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(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/HelloTriangle.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/HelloTriangle.java index b70fbc8c8c1..4ef071f8e0b 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/HelloTriangle.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/HelloTriangle.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.gles2; import com.badlogic.gdx.Gdx; @@ -27,37 +28,27 @@ public class HelloTriangle extends GdxTest { ShaderProgram shader; Mesh mesh; - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } @Override - public void create() { - String vertexShader = - "attribute vec4 vPosition; \n" + - "void main() \n" + - "{ \n" + - " gl_Position = vPosition; \n" + - "} \n"; - String fragmentShader = - "#ifdef GL_ES\n" - + "precision mediump float;\n" - + "#endif\n" + - "void main() \n" + - "{ \n" + - " gl_FragColor = vec4 ( 1.0, 1.0, 1.0, 1.0 );\n" + - "}"; - + public void create () { + String vertexShader = "attribute vec4 vPosition; \n" + "void main() \n" + + "{ \n" + " gl_Position = vPosition; \n" + "} \n"; + String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\n" + + "void main() \n" + "{ \n" + + " gl_FragColor = vec4 ( 1.0, 1.0, 1.0, 1.0 );\n" + "}"; + shader = new ShaderProgram(vertexShader, fragmentShader); mesh = new Mesh(true, 3, 0, new VertexAttribute(Usage.Position, 3, "vPosition")); - float[] vertices = { 0.0f, 0.5f, 0.0f, - -0.5f, -0.5f, 0.0f, - 0.5f, -0.5f, 0.0f }; + float[] vertices = {0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f}; mesh.setVertices(vertices); - } - + } + @Override - public void render() { + public void render () { Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT); shader.begin(); diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/MipMap2D.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/MipMap2D.java index 2cc76b3d054..50193153e52 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/MipMap2D.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/MipMap2D.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.gles2; import com.badlogic.gdx.Gdx; @@ -22,7 +23,6 @@ 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.Usage; import com.badlogic.gdx.graphics.glutils.ShaderProgram; @@ -32,57 +32,46 @@ public class MipMap2D extends GdxTest { ShaderProgram shader; Texture texture; Mesh mesh; - - @Override public boolean needsGL20 () { + + @Override + public boolean needsGL20 () { return true; } - @Override public void create() { - String vertexShader = - "uniform float u_offset; \n" + - "attribute vec4 a_position; \n" + - "attribute vec2 a_texCoord; \n" + - "varying vec2 v_texCoord; \n" + - "void main() \n" + - "{ \n" + - " gl_Position = a_position; \n" + - " gl_Position.x += u_offset;\n" + - " v_texCoord = a_texCoord; \n" + - "} \n"; - String fragmentShader = - "#ifdef GL_ES\n" - + "precision mediump float;\n" - + "#endif\n" + - "varying vec2 v_texCoord; \n" + - "uniform sampler2D s_texture; \n" + - "void main() \n" + - "{ \n" + - " gl_FragColor = texture2D( s_texture, v_texCoord );\n" + - "} \n"; + @Override + public void create () { + String vertexShader = "uniform float u_offset; \n" + "attribute vec4 a_position; \n" + + "attribute vec2 a_texCoord; \n" + "varying vec2 v_texCoord; \n" + "void main() \n" + + "{ \n" + " gl_Position = a_position; \n" + " gl_Position.x += u_offset;\n" + + " v_texCoord = a_texCoord; \n" + "} \n"; + String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\n" + + "varying vec2 v_texCoord; \n" + "uniform sampler2D s_texture; \n" + + "void main() \n" + "{ \n" + + " gl_FragColor = texture2D( s_texture, v_texCoord );\n" + "} \n"; shader = new ShaderProgram(vertexShader, fragmentShader); - mesh = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 4, "a_position"), - new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoord")); - float[] vertices = {-0.5f, 0.5f, 0.0f, 1.5f, // Position 0 - 0.0f, 0.0f, // TexCoord 0 - -0.5f, -0.5f, 0.0f, 0.75f, // Position 1 - 0.0f, 1.0f, // TexCoord 1 - 0.5f, -0.5f, 0.0f, 0.75f, // Position 2 - 1.0f, 1.0f, // TexCoord 2 - 0.5f, 0.5f, 0.0f, 1.5f, // Position 3 - 1.0f, 0.0f // TexCoord 3 - }; - short[] indices = { 0, 1, 2, 0, 2, 3 }; - mesh.setVertices(vertices); - mesh.setIndices(indices); - createTexture(); + mesh = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 4, "a_position"), new VertexAttribute( + Usage.TextureCoordinates, 2, "a_texCoord")); + float[] vertices = {-0.5f, 0.5f, 0.0f, 1.5f, // Position 0 + 0.0f, 0.0f, // TexCoord 0 + -0.5f, -0.5f, 0.0f, 0.75f, // Position 1 + 0.0f, 1.0f, // TexCoord 1 + 0.5f, -0.5f, 0.0f, 0.75f, // Position 2 + 1.0f, 1.0f, // TexCoord 2 + 0.5f, 0.5f, 0.0f, 1.5f, // Position 3 + 1.0f, 0.0f // TexCoord 3 + }; + short[] indices = {0, 1, 2, 0, 2, 3}; + mesh.setVertices(vertices); + mesh.setIndices(indices); + createTexture(); } - - private void createTexture() { + + private void createTexture () { Pixmap pixmap = new Pixmap(256, 256, Format.RGB565); boolean useRed = true; - for(int y = 0; y < 256; y+= 8) { - for(int x = 0; x < 256; x+= 8) { - pixmap.setColor(useRed?1:0, 0, useRed?0:1, 1); + for (int y = 0; y < 256; y += 8) { + for (int x = 0; x < 256; x += 8) { + pixmap.setColor(useRed ? 1 : 0, 0, useRed ? 0 : 1, 1); pixmap.fillRectangle(x, y, 8, 8); useRed = !useRed; } @@ -91,28 +80,28 @@ private void createTexture() { texture = new Texture(pixmap, true); texture.setFilter(TextureFilter.MipMapLinearLinear, TextureFilter.Linear); } - - public void resume() { + + public void resume () { createTexture(); } - - public void render() { + + public void render () { Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT); - - Gdx.gl20.glActiveTexture( GL20.GL_TEXTURE0); + + Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE0); texture.bind(); - shader.begin(); - shader.setUniformf( "s_texture", 0); - - Gdx.gl20.glTexParameteri( GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MIN_FILTER, GL20.GL_NEAREST); - shader.setUniformf( "u_offset", -0.6f); + shader.begin(); + shader.setUniformf("s_texture", 0); + + Gdx.gl20.glTexParameteri(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MIN_FILTER, GL20.GL_NEAREST); + shader.setUniformf("u_offset", -0.6f); mesh.render(shader, GL20.GL_TRIANGLES); - - Gdx.gl20.glTexParameteri( GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MIN_FILTER, GL20.GL_LINEAR_MIPMAP_LINEAR); - shader.setUniformf( "u_offset", 0.6f); + + Gdx.gl20.glTexParameteri(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MIN_FILTER, GL20.GL_LINEAR_MIPMAP_LINEAR); + shader.setUniformf("u_offset", 0.6f); mesh.render(shader, GL20.GL_TRIANGLES); - + shader.end(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/Shapes.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/Shapes.java index a5166a87aaf..51f09a35698 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/Shapes.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/Shapes.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.gles2; import com.badlogic.gdx.graphics.Mesh; @@ -20,125 +21,46 @@ import com.badlogic.gdx.graphics.VertexAttributes.Usage; public class Shapes { - public static Mesh genCube() { - Mesh mesh = new Mesh(true, 24, 36, new VertexAttribute(Usage.Position, 3, "a_position"), - new VertexAttribute(Usage.Normal, 3, "a_normal"), - new VertexAttribute(Usage.TextureCoordinates, 2, "a_texcoords")); - - float[] cubeVerts = { - -0.5f, -0.5f, -0.5f, - -0.5f, -0.5f, 0.5f, - 0.5f, -0.5f, 0.5f, - 0.5f, -0.5f, -0.5f, - -0.5f, 0.5f, -0.5f, - -0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, -0.5f, - -0.5f, -0.5f, -0.5f, - -0.5f, 0.5f, -0.5f, - 0.5f, 0.5f, -0.5f, - 0.5f, -0.5f, -0.5f, - -0.5f, -0.5f, 0.5f, - -0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, 0.5f, - 0.5f, -0.5f, 0.5f, - -0.5f, -0.5f, -0.5f, - -0.5f, -0.5f, 0.5f, - -0.5f, 0.5f, 0.5f, - -0.5f, 0.5f, -0.5f, - 0.5f, -0.5f, -0.5f, - 0.5f, -0.5f, 0.5f, - 0.5f, 0.5f, 0.5f, - 0.5f, 0.5f, -0.5f, - }; - - float[] cubeNormals = { - 0.0f, -1.0f, 0.0f, - 0.0f, -1.0f, 0.0f, - 0.0f, -1.0f, 0.0f, - 0.0f, -1.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, -1.0f, - 0.0f, 0.0f, -1.0f, - 0.0f, 0.0f, -1.0f, - 0.0f, 0.0f, -1.0f, - 0.0f, 0.0f, 1.0f, - 0.0f, 0.0f, 1.0f, - 0.0f, 0.0f, 1.0f, - 0.0f, 0.0f, 1.0f, - -1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, - -1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - }; + public static Mesh genCube () { + Mesh mesh = new Mesh(true, 24, 36, new VertexAttribute(Usage.Position, 3, "a_position"), new VertexAttribute(Usage.Normal, + 3, "a_normal"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texcoords")); + + float[] cubeVerts = {-0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, + -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, + 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, + -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, + 0.5f, 0.5f, -0.5f,}; + + float[] cubeNormals = {0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, + -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, + -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,}; + + float[] cubeTex = {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,}; + + float[] vertices = new float[24 * 8]; + int pIdx = 0; + int nIdx = 0; + int tIdx = 0; + for (int i = 0; i < vertices.length;) { + vertices[i++] = cubeVerts[pIdx++]; + vertices[i++] = cubeVerts[pIdx++]; + vertices[i++] = cubeVerts[pIdx++]; + vertices[i++] = cubeNormals[nIdx++]; + vertices[i++] = cubeNormals[nIdx++]; + vertices[i++] = cubeNormals[nIdx++]; + vertices[i++] = cubeTex[tIdx++]; + vertices[i++] = cubeTex[tIdx++]; + } + + short[] indices = {0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 15, 14, 12, 14, 13, 16, 17, 18, 16, 18, 19, + 20, 23, 22, 20, 22, 21}; + + mesh.setVertices(vertices); + mesh.setIndices(indices); - float[] cubeTex = { - 0.0f, 0.0f, - 0.0f, 1.0f, - 1.0f, 1.0f, - 1.0f, 0.0f, - 1.0f, 0.0f, - 1.0f, 1.0f, - 0.0f, 1.0f, - 0.0f, 0.0f, - 0.0f, 0.0f, - 0.0f, 1.0f, - 1.0f, 1.0f, - 1.0f, 0.0f, - 0.0f, 0.0f, - 0.0f, 1.0f, - 1.0f, 1.0f, - 1.0f, 0.0f, - 0.0f, 0.0f, - 0.0f, 1.0f, - 1.0f, 1.0f, - 1.0f, 0.0f, - 0.0f, 0.0f, - 0.0f, 1.0f, - 1.0f, 1.0f, - 1.0f, 0.0f, - }; - - float[] vertices = new float[24*8]; - int pIdx = 0; - int nIdx = 0; - int tIdx = 0; - for(int i = 0; i < vertices.length; ) { - vertices[i++] = cubeVerts[pIdx++]; - vertices[i++] = cubeVerts[pIdx++]; - vertices[i++] = cubeVerts[pIdx++]; - vertices[i++] = cubeNormals[nIdx++]; - vertices[i++] = cubeNormals[nIdx++]; - vertices[i++] = cubeNormals[nIdx++]; - vertices[i++] = cubeTex[tIdx++]; - vertices[i++] = cubeTex[tIdx++]; - } - - short[] indices = { - 0, 2, 1, - 0, 3, 2, - 4, 5, 6, - 4, 6, 7, - 8, 9, 10, - 8, 10, 11, - 12, 15, 14, - 12, 14, 13, - 16, 17, 18, - 16, 18, 19, - 20, 23, 22, - 20, 22, 21 - }; - - mesh.setVertices(vertices); - mesh.setIndices(indices); - return mesh; } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/SimpleVertexShader.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/SimpleVertexShader.java index f090ddaabc1..b3df78448a5 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/SimpleVertexShader.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/gles2/SimpleVertexShader.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.gles2; import com.badlogic.gdx.Gdx; @@ -34,49 +35,41 @@ public class SimpleVertexShader extends GdxTest { Vector3 axis = new Vector3(1, 0, 1).nor(); float angle = 45; - @Override public boolean needsGL20 () { + @Override + public boolean needsGL20 () { return true; } @Override - public void create() { - String vertexShader = - "uniform mat4 u_mvpMatrix; \n" + - "attribute vec4 a_position; \n" + - "void main() \n" + - "{ \n" + - " gl_Position = u_mvpMatrix * a_position; \n" + - "} \n"; - String fragmentShader = - "#ifdef GL_ES\n" - + "precision mediump float;\n" - + "#endif\n" + - "void main() \n" + - "{ \n" + - " gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n" + - "}"; - + public void create () { + String vertexShader = "uniform mat4 u_mvpMatrix; \n" + "attribute vec4 a_position; \n" + + "void main() \n" + "{ \n" + + " gl_Position = u_mvpMatrix * a_position; \n" + "} \n"; + String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\n" + + "void main() \n" + "{ \n" + + " gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n" + "}"; + shader = new ShaderProgram(vertexShader, fragmentShader); mesh = Shapes.genCube(); mesh.getVertexAttribute(Usage.Position).alias = "a_position"; } - + @Override - public void render() { + public void render () { angle += Gdx.graphics.getDeltaTime() * 40.0f; float aspect = Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight(); - projection.setToProjection( 1.0f, 20.0f, 60.0f, aspect); + projection.setToProjection(1.0f, 20.0f, 60.0f, aspect); view.idt().trn(0, 0, -2.0f); model.setToRotation(axis, angle); combined.set(projection).mul(view).mul(model); - + Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT); shader.begin(); shader.setUniformMatrix("u_mvpMatrix", combined); mesh.render(shader, GL20.GL_TRIANGLES); shader.end(); - + Gdx.app.log("angle", "" + angle); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTest.java index bf96a62cbed..40f565ef94c 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTest.java @@ -30,13 +30,24 @@ import com.badlogic.gdx.ApplicationListener; -public abstract class GdxTest implements ApplicationListener -{ - public abstract boolean needsGL20( ); - public void create( ) { }; - public void resume( ) { }; - public void render( ) { }; - public void resize(int width, int height) { }; - public void pause( ) { }; - public void dispose( ) { }; +public abstract class GdxTest implements ApplicationListener { + public abstract boolean needsGL20 (); + + public void create () { + }; + + public void resume () { + }; + + public void render () { + }; + + public void resize (int width, int height) { + }; + + public void pause () { + }; + + public void dispose () { + }; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTests.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTests.java index a426c9c96cc..155dbaa325f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTests.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/GdxTests.java @@ -35,24 +35,12 @@ import com.badlogic.gdx.tests.gles2.HelloTriangle; import com.badlogic.gdx.tests.gles2.SimpleVertexShader; -/** - * List of GdxTest classes. To be used by the test launchers. - * If you write your own test, add it in here! +/** List of GdxTest classes. To be used by the test launchers. If you write your own test, add it in here! * - * @author badlogicgames@gmail.com - * - */ -public class GdxTests -{ - public static final Class[] tests = { - AnimationTest.class, - AccelerometerTest.class, - ActionTest.class, - ActionSequenceTest.class, - AlphaTest.class, - AtlasIssueTest.class, - AssetManagerTest.class, - FilterPerformanceTest.class, + * @author badlogicgames@gmail.com */ +public class GdxTests { + public static final Class[] tests = {AnimationTest.class, AccelerometerTest.class, ActionTest.class, ActionSequenceTest.class, + AlphaTest.class, AtlasIssueTest.class, AssetManagerTest.class, FilterPerformanceTest.class, AudioDeviceTest.class, AudioRecorderTest.class, BitmapFontAlignmentTest.class, @@ -71,24 +59,11 @@ public class GdxTests ETC1Test.class, ExitTest.class, FilesTest.class, - //FillrateTest.class, - FlickScrollPaneTest.class, - FloatTest.class, - FrameBufferTest.class, - FramebufferToTextureTest.class, - FrustumTest.class, - FullscreenTest.class, - Gdx2DTest.class, - GroupFadeTest.class, - ImmediateModeRendererTest.class, - ImmediateModeRendererAlphaTest.class, - IndexBufferObjectClassTest.class, - IndexBufferObjectShaderTest.class, - InputTest.class, - IntegerBitmapFontTest.class, - InverseKinematicsTest.class, - IsoCamTest.class, - IsometricTileTest.class, + // FillrateTest.class, + FlickScrollPaneTest.class, FloatTest.class, FrameBufferTest.class, FramebufferToTextureTest.class, FrustumTest.class, + FullscreenTest.class, Gdx2DTest.class, GroupFadeTest.class, ImmediateModeRendererTest.class, + ImmediateModeRendererAlphaTest.class, IndexBufferObjectClassTest.class, IndexBufferObjectShaderTest.class, InputTest.class, + IntegerBitmapFontTest.class, InverseKinematicsTest.class, IsoCamTest.class, IsometricTileTest.class, KinematicBodyTest.class, LifeCycleTest.class, LineDrawingTest.class, @@ -97,90 +72,43 @@ public class GdxTests MatrixJNITest.class, MD5Test.class, MeshMultitextureTest.class, - MeshShaderTest.class, - MeshTest.class, + MeshShaderTest.class, + MeshTest.class, MipMapTest.class, - //Mpg123Test.class, - MultitouchTest.class, - MusicTest.class, - MultiTouchActorTest.class, - MyFirstTriangle.class, - ObjTest.class, - OldUITest.class, - OnscreenKeyboardTest.class, - OrthoCamBorderTest.class, - ParallaxTest.class, - ParticleEmitterTest.class, - PickingTest.class, - PixelsPerInchTest.class, - PixmapBlendingTest.class, - PixmapTest.class, - PreferencesTest.class, - ProjectiveTextureTest.class, - Pong.class, - ProjectTest.class, - RemoteTest.class, - RotationTest.class, - ShaderMultitextureTest.class, - ShadowMappingTest.class, - SplineTest.class, - SimpleTest.class, - SimpleAnimationTest.class, - SimpleDecalTest.class, - SimpleStageCullingTest.class, - SoundTest.class, - SpriteCacheTest.class, - SpriteCacheOffsetTest.class, - SpriteBatchRotationTest.class, - SpriteBatchShaderTest.class, - SpriteBatchTest.class, - SpritePerformanceTest.class, - SpritePerformanteTest2.class, - StagePerformanceTest.class, - StageTest.class, - TerrainTest.class, - TextureDataTest.class, - TextureDownloadTest.class, - TextureFormatTest.class, - TextureAtlasTest.class, - TextInputDialogTest.class, - TextureRenderTest.class, - TiledMapTest.class, - TileTest.class, - UITest.class, - VBOVATest.class, - VertexArrayTest.class, - VertexBufferObjectTest.class, - VertexArrayClassTest.class, - VertexBufferObjectClassTest.class, - VertexBufferObjectShaderTest.class, - VibratorTest.class, - //VorbisTest.class, - WaterRipples.class, - HelloTriangle.class, - SimpleVertexShader.class - }; - + // Mpg123Test.class, + MultitouchTest.class, MusicTest.class, MultiTouchActorTest.class, MyFirstTriangle.class, ObjTest.class, OldUITest.class, + OnscreenKeyboardTest.class, OrthoCamBorderTest.class, ParallaxTest.class, ParticleEmitterTest.class, PickingTest.class, + PixelsPerInchTest.class, PixmapBlendingTest.class, PixmapTest.class, PreferencesTest.class, ProjectiveTextureTest.class, + Pong.class, ProjectTest.class, RemoteTest.class, RotationTest.class, ShaderMultitextureTest.class, ShadowMappingTest.class, + SplineTest.class, SimpleTest.class, SimpleAnimationTest.class, SimpleDecalTest.class, SimpleStageCullingTest.class, + SoundTest.class, SpriteCacheTest.class, SpriteCacheOffsetTest.class, SpriteBatchRotationTest.class, + SpriteBatchShaderTest.class, SpriteBatchTest.class, SpritePerformanceTest.class, SpritePerformanteTest2.class, + StagePerformanceTest.class, StageTest.class, TerrainTest.class, TextureDataTest.class, TextureDownloadTest.class, + TextureFormatTest.class, TextureAtlasTest.class, TextInputDialogTest.class, TextureRenderTest.class, TiledMapTest.class, + TileTest.class, UITest.class, VBOVATest.class, VertexArrayTest.class, VertexBufferObjectTest.class, + VertexArrayClassTest.class, VertexBufferObjectClassTest.class, VertexBufferObjectShaderTest.class, VibratorTest.class, + // VorbisTest.class, + WaterRipples.class, HelloTriangle.class, SimpleVertexShader.class}; + public static String[] getNames () { - List names = new ArrayList( ); - for( Class clazz: tests ) + List names = new ArrayList(); + for (Class clazz : tests) names.add(clazz.getSimpleName()); return names.toArray(new String[names.size()]); } - public static GdxTest newTest (String testName) { + public static GdxTest newTest (String testName) { try { Class clazz = Class.forName("com.badlogic.gdx.tests." + testName); return (GdxTest)clazz.newInstance(); - } - catch( Exception ex ) { + } catch (Exception ex) { try { Class clazz = Class.forName("com.badlogic.gdx.tests.gles2." + testName); return (GdxTest)clazz.newInstance(); - } catch(Exception e) { + } catch (Exception e) { ex.printStackTrace(); return null; } - } + } } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/OrthoCamController.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/OrthoCamController.java index 5810f98ff0b..414758c9a9f 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/OrthoCamController.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/OrthoCamController.java @@ -13,35 +13,37 @@ * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ + package com.badlogic.gdx.tests.utils; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.OrthographicCamera; -import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; public class OrthoCamController extends InputAdapter { final OrthographicCamera camera; final Vector3 curr = new Vector3(); - final Vector3 last = new Vector3(-1, -1, -1); + final Vector3 last = new Vector3(-1, -1, -1); final Vector3 delta = new Vector3(); - - public OrthoCamController(OrthographicCamera camera) { + + public OrthoCamController (OrthographicCamera camera) { this.camera = camera; } - @Override public boolean touchDragged (int x, int y, int pointer) { - camera.unproject(curr.set(x, y,0)); - if(!(last.x == -1 && last.y == -1 && last.z == -1)) { - camera.unproject(delta.set(last.x, last.y, 0)); + @Override + public boolean touchDragged (int x, int y, int pointer) { + camera.unproject(curr.set(x, y, 0)); + if (!(last.x == -1 && last.y == -1 && last.z == -1)) { + camera.unproject(delta.set(last.x, last.y, 0)); delta.sub(curr); camera.position.add(delta.x, delta.y, 0); } last.set(x, y, 0); return false; } - - @Override public boolean touchUp(int x, int y, int pointer, int button) { + + @Override + public boolean touchUp (int x, int y, int pointer, int button) { last.set(-1, -1, -1); return false; } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/PerspectiveCamController.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/PerspectiveCamController.java index 939f3dd4170..c5f02216b65 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/PerspectiveCamController.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/utils/PerspectiveCamController.java @@ -1,3 +1,4 @@ + package com.badlogic.gdx.tests.utils; import com.badlogic.gdx.Gdx; @@ -10,30 +11,29 @@ public class PerspectiveCamController extends InputAdapter { public PerspectiveCamera cam; - + enum TransformMode { - Rotate, - Translate, - Zoom, - None + Rotate, Translate, Zoom, None } - + Vector3 lookAt = new Vector3(); - TransformMode mode = TransformMode.Translate; + TransformMode mode = TransformMode.Translate; boolean translated = false; - - public PerspectiveCamController(PerspectiveCamera cam) { + + public PerspectiveCamController (PerspectiveCamera cam) { this.cam = cam; } - - @Override public boolean touchDown (int x, int y, int pointer, int button) { + + @Override + public boolean touchDown (int x, int y, int pointer, int button) { mode = TransformMode.Rotate; - last.set(x, y); + last.set(x, y); tCurr.set(x, y); - return true; + return true; } - @Override public boolean touchUp (int x, int y, int pointer, int button) { + @Override + public boolean touchUp (int x, int y, int pointer, int button) { mode = TransformMode.None; return true; } @@ -43,46 +43,49 @@ public PerspectiveCamController(PerspectiveCamera cam) { Vector2 delta = new Vector2(); Vector2 currWindow = new Vector2(); Vector2 lastWindow = new Vector2(); - Vector3 curr3 = new Vector3(); + Vector3 curr3 = new Vector3(); Vector3 delta3 = new Vector3(); - Plane lookAtPlane = new Plane(new Vector3(0, 1, 0), 0); + Plane lookAtPlane = new Plane(new Vector3(0, 1, 0), 0); Matrix4 rotMatrix = new Matrix4(); Vector3 xAxis = new Vector3(1, 0, 0); Vector3 yAxis = new Vector3(0, 1, 0); Vector3 point = new Vector3(); - @Override public boolean touchDragged (int x, int y, int pointer) { - if(pointer != 0) return false; - delta.set(x, y).sub(last); - - if(mode == TransformMode.Rotate) { - point.set(cam.position).sub(lookAt); - - if(point.tmp().nor().dot(yAxis) < 0.9999f) { - xAxis.set(cam.direction).crs(yAxis).nor(); + + @Override + public boolean touchDragged (int x, int y, int pointer) { + if (pointer != 0) return false; + delta.set(x, y).sub(last); + + if (mode == TransformMode.Rotate) { + point.set(cam.position).sub(lookAt); + + if (point.tmp().nor().dot(yAxis) < 0.9999f) { + xAxis.set(cam.direction).crs(yAxis).nor(); rotMatrix.setToRotation(xAxis, delta.y / 5); point.mul(rotMatrix); } - - rotMatrix.setToRotation(yAxis, -delta.x / 5); + + rotMatrix.setToRotation(yAxis, -delta.x / 5); point.mul(rotMatrix); - + cam.position.set(point.add(lookAt)); - cam.lookAt(lookAt.x, lookAt.y, lookAt.z); + cam.lookAt(lookAt.x, lookAt.y, lookAt.z); } - if(mode == TransformMode.Zoom) { + if (mode == TransformMode.Zoom) { cam.fieldOfView -= -delta.y / 10; } - if(mode == TransformMode.Translate) { - tCurr.set(x,y); + if (mode == TransformMode.Translate) { + tCurr.set(x, y); translated = true; } - + cam.update(); - last.set(x, y); + last.set(x, y); return true; } - - @Override public boolean scrolled(int amount) { + + @Override + public boolean scrolled (int amount) { cam.fieldOfView -= -amount * Gdx.graphics.getDeltaTime() * 100; cam.update(); return true;