From 7add915e00f88105d3fdb254037dd38ccdc4ac1d Mon Sep 17 00:00:00 2001 From: Stephen Gold Date: Sat, 22 Jan 2022 21:53:52 -0800 Subject: [PATCH] whitespace changes in jme3-core (#1760) * jme3-core: whitespace * jme3-core: whitespace again * jme3-core: whitespace some more * Tweens: tweak whitespace in javadoc * BoneTrack: correct indentation * Pose: delete extra whitespace * Skeleton.java: horizontal whitespace per style guide * SkeletonControl: delete excess whitespace * BasicProfiler: whitespace * BasicProfilerState: whitespace * FlyCamAppState: whitespace in javadoc * LegacyApplication: add space per 4.6.2.5 * SimpleApplication: indentation * StatsAppState: whitespace * AssetConfig: add whitespace * AssetKey: whitespace in cast per 4.6.2.5 * AssetLoadException: add vertical whitespace required by 4.6.1 * AssetNotFoundException: add vertical whitespace required by 4.6.1.1 * DesktopAssetManager: whitespace * ImplHandler: whitespace per the style guide * ThreadingManager: indentation * WeakRefAssetCache: cast spacing per 4.6.2.5 * WeakRefCloneAssetCache: whitespace * AudioBuffer: whitespace * AudioKey: line wrapping * AudioNode: whitespace * Filter: whitespace per 4.6.2.5 * Listener: delete trailing whitespace * AlAudioRenderer: whitespace per perferred style * BoundingSphere: whitespace per perferred style * Intersection: whitespace per perferred style * KeyFrame: whitespace * MotionPath: whitespace * TimeLine: delete excess vertical whitespace * AbstractCinematicEvent: whitespace * AnimationEvent: whitespace * MotionEvent: tweak the whitespace * SoundEvent: tweak the whitespace * CollisionResult: space after closing parenthesis of a cast * CollisionResults: space on both sides of a binary operator * SweepSphere: whitespace * BIHTree: space before { * TriangleAxisComparator: one statement per line * ParticleEmitter: whitespace * ParticlePointMesh: whitespace * ParticleTriMesh: misc whitespace * ReadialParticleInfluencer: delete extra vertical whitespace --- .../main/java/com/jme3/anim/AnimComposer.java | 57 +++--- .../anim/interpolator/FrameInterpolator.java | 21 +- .../main/java/com/jme3/anim/tween/Tweens.java | 16 +- .../jme3/anim/tween/action/ClipAction.java | 4 +- .../java/com/jme3/animation/AnimChannel.java | 98 +++++---- .../java/com/jme3/animation/AnimControl.java | 32 +-- .../java/com/jme3/animation/Animation.java | 44 ++--- .../com/jme3/animation/AnimationUtils.java | 13 +- .../java/com/jme3/animation/AudioTrack.java | 22 +-- .../main/java/com/jme3/animation/Bone.java | 184 +++++++++-------- .../java/com/jme3/animation/BoneTrack.java | 18 +- .../com/jme3/animation/CompactFloatArray.java | 6 +- .../java/com/jme3/animation/EffectTrack.java | 13 +- .../main/java/com/jme3/animation/Pose.java | 20 +- .../java/com/jme3/animation/PoseTrack.java | 29 ++- .../java/com/jme3/animation/Skeleton.java | 22 +-- .../com/jme3/animation/SkeletonControl.java | 84 ++++---- .../java/com/jme3/animation/TrackInfo.java | 18 +- .../main/java/com/jme3/app/BasicProfiler.java | 90 ++++----- .../java/com/jme3/app/BasicProfilerState.java | 85 ++++---- .../com/jme3/app/ChaseCameraAppState.java | 14 +- .../java/com/jme3/app/FlyCamAppState.java | 34 ++-- .../java/com/jme3/app/LegacyApplication.java | 137 ++++++------- .../java/com/jme3/app/SimpleApplication.java | 34 ++-- .../main/java/com/jme3/app/StatsAppState.java | 31 ++- .../src/main/java/com/jme3/app/StatsView.java | 9 +- .../com/jme3/app/state/AbstractAppState.java | 15 +- .../com/jme3/app/state/AppStateManager.java | 187 +++++++++--------- .../java/com/jme3/app/state/BaseAppState.java | 72 ++++--- .../jme3/app/state/ConstantVerifierState.java | 84 ++++---- .../com/jme3/app/state/RootNodeAppState.java | 10 +- .../jme3/app/state/ScreenshotAppState.java | 22 +-- .../main/java/com/jme3/asset/AssetConfig.java | 21 +- .../main/java/com/jme3/asset/AssetInfo.java | 5 +- .../main/java/com/jme3/asset/AssetKey.java | 40 ++-- .../com/jme3/asset/AssetLoadException.java | 5 +- .../jme3/asset/AssetNotFoundException.java | 5 +- .../com/jme3/asset/DesktopAssetManager.java | 172 ++++++++-------- .../main/java/com/jme3/asset/FilterKey.java | 4 +- .../main/java/com/jme3/asset/ImplHandler.java | 154 +++++++-------- .../main/java/com/jme3/asset/ModelKey.java | 12 +- .../main/java/com/jme3/asset/TextureKey.java | 30 +-- .../java/com/jme3/asset/ThreadingManager.java | 10 +- .../jme3/asset/cache/WeakRefAssetCache.java | 45 ++--- .../asset/cache/WeakRefCloneAssetCache.java | 87 ++++---- .../main/java/com/jme3/audio/AudioBuffer.java | 26 +-- .../java/com/jme3/audio/AudioContext.java | 8 +- .../main/java/com/jme3/audio/AudioData.java | 12 +- .../main/java/com/jme3/audio/AudioKey.java | 45 ++--- .../main/java/com/jme3/audio/AudioNode.java | 74 +++---- .../main/java/com/jme3/audio/Environment.java | 8 +- .../src/main/java/com/jme3/audio/Filter.java | 10 +- .../main/java/com/jme3/audio/Listener.java | 18 +- .../java/com/jme3/audio/LowPassFilter.java | 12 +- .../jme3/audio/openal/ALAudioRenderer.java | 152 +++++++------- .../com/jme3/bounding/BoundingSphere.java | 135 +++++++------ .../java/com/jme3/bounding/Intersection.java | 48 ++--- .../java/com/jme3/cinematic/Cinematic.java | 12 +- .../java/com/jme3/cinematic/KeyFrame.java | 13 +- .../java/com/jme3/cinematic/MotionPath.java | 9 +- .../java/com/jme3/cinematic/TimeLine.java | 6 +- .../events/AbstractCinematicEvent.java | 38 ++-- .../jme3/cinematic/events/AnimationEvent.java | 38 ++-- .../jme3/cinematic/events/CameraEvent.java | 21 +- .../jme3/cinematic/events/MotionEvent.java | 30 +-- .../com/jme3/cinematic/events/SoundEvent.java | 30 ++- .../com/jme3/collision/CollisionResult.java | 18 +- .../com/jme3/collision/CollisionResults.java | 45 +++-- .../java/com/jme3/collision/SweepSphere.java | 142 ++++++------- .../java/com/jme3/collision/bih/BIHTree.java | 24 +-- .../com/jme3/collision/bih/BIHTriangle.java | 50 +++-- .../collision/bih/TriangleAxisComparator.java | 25 ++- .../java/com/jme3/effect/ParticleEmitter.java | 85 ++++---- .../com/jme3/effect/ParticlePointMesh.java | 24 +-- .../java/com/jme3/effect/ParticleTriMesh.java | 57 +++--- .../DefaultParticleInfluencer.java | 6 +- .../influencers/EmptyParticleInfluencer.java | 2 +- .../influencers/RadialParticleInfluencer.java | 3 +- .../jme3/effect/shapes/EmitterBoxShape.java | 2 +- .../effect/shapes/EmitterMeshVertexShape.java | 4 +- .../jme3/effect/shapes/EmitterPointShape.java | 2 +- .../effect/shapes/EmitterSphereShape.java | 2 +- .../jme3/environment/EnvironmentCamera.java | 8 +- .../environment/util/LightsDebugState.java | 13 +- .../java/com/jme3/export/FormatVersion.java | 8 +- .../com/jme3/export/SavableClassUtil.java | 31 +-- .../java/com/jme3/font/BitmapCharacter.java | 16 +- .../com/jme3/font/BitmapCharacterSet.java | 16 +- .../main/java/com/jme3/font/BitmapFont.java | 59 +++--- .../main/java/com/jme3/font/BitmapText.java | 9 +- .../java/com/jme3/font/BitmapTextPage.java | 4 +- .../main/java/com/jme3/font/ColorTags.java | 26 +-- .../main/java/com/jme3/font/LetterQuad.java | 82 ++++---- .../src/main/java/com/jme3/font/Letters.java | 11 +- .../main/java/com/jme3/font/Rectangle.java | 7 +- .../main/java/com/jme3/font/StringBlock.java | 22 +-- .../java/com/jme3/input/AbstractJoystick.java | 50 ++--- .../main/java/com/jme3/input/ChaseCamera.java | 57 +++--- .../com/jme3/input/DefaultJoystickAxis.java | 22 +-- .../com/jme3/input/DefaultJoystickButton.java | 26 +-- .../main/java/com/jme3/input/FlyByCamera.java | 72 +++---- .../input/JoystickCompatibilityMappings.java | 2 +- .../jme3/input/controls/JoyAxisTrigger.java | 4 +- .../jme3/input/controls/JoyButtonTrigger.java | 4 +- .../com/jme3/input/event/KeyInputEvent.java | 22 +-- .../jme3/input/event/MouseButtonEvent.java | 19 +- .../com/jme3/light/DefaultLightFilter.java | 20 +- .../main/java/com/jme3/light/LightList.java | 57 +++--- .../main/java/com/jme3/light/PointLight.java | 36 ++-- .../main/java/com/jme3/material/MatParam.java | 12 +- .../java/com/jme3/material/TechniqueDef.java | 94 ++++----- .../SinglePassAndImageBasedLightingLogic.java | 12 +- .../logic/SinglePassLightingLogic.java | 2 +- .../com/jme3/post/FilterPostProcessor.java | 58 +++--- .../main/java/com/jme3/post/HDRRenderer.java | 63 +++--- .../com/jme3/renderer/opengl/GLRenderer.java | 132 +++++++------ .../com/jme3/renderer/queue/GeometryList.java | 28 ++- .../jme3/renderer/queue/OpaqueComparator.java | 21 +- .../java/com/jme3/scene/AssetLinkNode.java | 2 +- .../main/java/com/jme3/scene/CameraNode.java | 2 +- .../main/java/com/jme3/scene/LightNode.java | 2 +- .../jme3/scene/control/AbstractControl.java | 15 +- .../jme3/scene/control/BillboardControl.java | 14 +- .../main/java/com/jme3/scene/debug/Grid.java | 15 +- .../java/com/jme3/scene/debug/WireBox.java | 14 +- .../scene/instancing/InstancedGeometry.java | 2 +- .../jme3/scene/instancing/InstancedNode.java | 16 +- .../java/com/jme3/scene/shape/Cylinder.java | 83 ++++---- .../main/java/com/jme3/scene/shape/Dome.java | 42 ++-- .../main/java/com/jme3/scene/shape/Quad.java | 28 +-- .../java/com/jme3/scene/shape/Surface.java | 29 ++- .../src/main/java/com/jme3/shader/Shader.java | 58 +++--- .../java/com/jme3/shader/ShaderGenerator.java | 20 +- .../com/jme3/shader/ShaderNodeDefinition.java | 12 +- .../main/java/com/jme3/shader/Uniform.java | 18 +- .../jme3/shadow/AbstractShadowRenderer.java | 60 +++--- .../main/java/com/jme3/shadow/ShadowUtil.java | 89 ++++----- .../java/com/jme3/system/AppSettings.java | 66 +++---- .../main/java/com/jme3/texture/Texture.java | 45 ++--- .../java/com/jme3/texture/TextureCubeMap.java | 18 +- .../jme3/texture/image/BitMaskImageCodec.java | 22 ++- .../texture/image/ByteAlignedImageCodec.java | 33 ++-- .../texture/image/DefaultImageRaster.java | 52 ++--- .../com/jme3/texture/image/ImageRaster.java | 56 +++--- .../src/main/java/com/jme3/util/IntMap.java | 17 +- .../main/java/com/jme3/util/JmeFormatter.java | 6 +- .../java/com/jme3/util/MipMapGenerator.java | 30 +-- .../java/com/jme3/util/SafeArrayList.java | 66 +++---- .../src/main/java/com/jme3/util/SortUtil.java | 22 +-- .../util/blockparser/BlockLanguageParser.java | 42 ++-- .../com/jme3/util/clone/CloneFunction.java | 21 +- .../main/java/com/jme3/util/clone/Cloner.java | 71 ++++--- .../util/clone/IdentityCloneFunction.java | 8 +- .../com/jme3/util/clone/JmeCloneable.java | 14 +- .../jme3/util/clone/ListCloneFunction.java | 14 +- .../main/java/com/jme3/util/xml/SAXUtil.java | 29 ++- 156 files changed, 2806 insertions(+), 2823 deletions(-) diff --git a/jme3-core/src/main/java/com/jme3/anim/AnimComposer.java b/jme3-core/src/main/java/com/jme3/anim/AnimComposer.java index 78eeffd0dd..4bc6c383a1 100644 --- a/jme3-core/src/main/java/com/jme3/anim/AnimComposer.java +++ b/jme3-core/src/main/java/com/jme3/anim/AnimComposer.java @@ -48,11 +48,10 @@ /** * AnimComposer is a Spatial control that allows manipulation of * {@link Armature armature} (skeletal) animation. - * + * * @author Nehon */ public class AnimComposer extends AbstractControl { - /** * The name of the default layer. */ @@ -72,7 +71,7 @@ public AnimComposer() { /** * Tells if an animation is contained in the list of animations. - * + * * @param name The name of the animation. * @return true, if the named animation is in the list of animations. */ @@ -117,17 +116,17 @@ public void removeAnimClip(AnimClip anim) { /** * Run an action on the default layer. - * + * * @param name The name of the action to run. * @return The action corresponding to the given name. */ public Action setCurrentAction(String name) { return setCurrentAction(name, DEFAULT_LAYER); } - + /** * Run an action on specified layer. - * + * * @param actionName The name of the action to run. * @param layerName The layer on which action should run. * @return The action corresponding to the given name. @@ -139,19 +138,19 @@ public Action setCurrentAction(String actionName, String layerName) { return currentAction; } - + /** * Return the current action on the default layer. - * - * @return The action corresponding to the given name. + * + * @return The action corresponding to the given name. */ public Action getCurrentAction() { return getCurrentAction(DEFAULT_LAYER); } - + /** * Return current action on specified layer. - * + * * @param layerName The layer on which action should run. * @return The action corresponding to the given name. */ @@ -161,14 +160,14 @@ public Action getCurrentAction(String layerName) { return result; } - + /** * Remove current action on default layer. */ public void removeCurrentAction() { removeCurrentAction(DEFAULT_LAYER); } - + /** * Remove current action on specified layer. * @@ -178,19 +177,19 @@ public void removeCurrentAction(String layerName) { AnimLayer l = getLayer(layerName); l.setCurrentAction(null); } - + /** * Returns current time of the default layer. - * + * * @return The current time. */ public double getTime() { return getTime(DEFAULT_LAYER); } - + /** * Returns current time of the specified layer. - * + * * @param layerName The layer from which to get the time. * @return the time (in seconds) */ @@ -200,7 +199,7 @@ public double getTime(String layerName) { return result; } - + /** * Sets current time on the default layer. * @@ -226,7 +225,7 @@ public void setTime(String layerName, double time) { } /** - * + * * @param name The name of the action to return. * @return The action registered with specified name. It will make a new action if there isn't any. * @see #makeAction(java.lang.String) @@ -239,29 +238,29 @@ public Action action(String name) { } return action; } - + /** - * + * * @param name The name of the action to return. * @return The action registered with specified name or null if nothing is registered. */ - public Action getAction(String name){ + public Action getAction(String name) { return actions.get(name); } - + /** * Register given action with specified name. - * + * * @param name The name of the action. * @param action The action to add. */ - public void addAction(String name, Action action){ + public void addAction(String name, Action action) { actions.put(name, action); } /** * Create a new ClipAction with specified clip name. - * + * * @param name The name of the clip. * @return a new action * @throws IllegalArgumentException if clip with specified name not found. @@ -275,17 +274,17 @@ public Action makeAction(String name) { action = new ClipAction(clip); return action; } - + /** * Tells if an action is contained in the list of actions. - * + * * @param name The name of the action. * @return true, if the named action is in the list of actions. */ public boolean hasAction(String name) { return actions.containsKey(name); } - + /** * Remove specified action. * diff --git a/jme3-core/src/main/java/com/jme3/anim/interpolator/FrameInterpolator.java b/jme3-core/src/main/java/com/jme3/anim/interpolator/FrameInterpolator.java index 6283baf31b..89cde24dda 100644 --- a/jme3-core/src/main/java/com/jme3/anim/interpolator/FrameInterpolator.java +++ b/jme3-core/src/main/java/com/jme3/anim/interpolator/FrameInterpolator.java @@ -38,7 +38,6 @@ * Created by nehon on 15/04/17. */ public class FrameInterpolator { - public static final FrameInterpolator DEFAULT = new FrameInterpolator(); private AnimInterpolator timeInterpolator; @@ -51,23 +50,23 @@ public class FrameInterpolator { final private TrackDataReader scaleReader = new TrackDataReader<>(); final private TrackTimeReader timesReader = new TrackTimeReader(); - final private Transform transforms = new Transform(); - public Transform interpolate(float t, int currentIndex, CompactVector3Array translations, CompactQuaternionArray rotations, CompactVector3Array scales, float[] times){ + public Transform interpolate(float t, int currentIndex, CompactVector3Array translations, + CompactQuaternionArray rotations, CompactVector3Array scales, float[] times) { timesReader.setData(times); - if( timeInterpolator != null){ - t = timeInterpolator.interpolate(t,currentIndex, null, timesReader, null ); + if (timeInterpolator != null) { + t = timeInterpolator.interpolate(t, currentIndex, null, timesReader, null); } - if(translations != null) { + if (translations != null) { translationReader.setData(translations); translationInterpolator.interpolate(t, currentIndex, translationReader, timesReader, transforms.getTranslation()); } - if(rotations != null) { + if (rotations != null) { rotationReader.setData(rotations); rotationInterpolator.interpolate(t, currentIndex, rotationReader, timesReader, transforms.getRotation()); } - if(scales != null){ + if (scales != null) { scaleReader.setData(scales); scaleInterpolator.interpolate(t, currentIndex, scaleReader, timesReader, transforms.getScale()); } @@ -83,7 +82,7 @@ public void interpolateWeights(float t, int currentIndex, float[] weights, int n next = current; } - float val = FastMath.interpolateLinear(t, weights[current], weights[next]); + float val = FastMath.interpolateLinear(t, weights[current], weights[next]); store[i] = val; } } @@ -104,7 +103,6 @@ public void setScaleInterpolator(AnimInterpolator scaleInterpolator) { this.scaleInterpolator = scaleInterpolator; } - public static class TrackTimeReader { private float[] data; @@ -122,7 +120,6 @@ public int getLength() { } public static class TrackDataReader { - private CompactArray data; protected void setData(CompactArray data) { @@ -148,7 +145,6 @@ public T getEntryModSkip(int index, T store) { index = mod(index, total); - return data.get(index, store); } } @@ -163,5 +159,4 @@ public T getEntryModSkip(int index, T store) { private static int mod(int val, int n) { return ((val % n) + n) % n; } - } diff --git a/jme3-core/src/main/java/com/jme3/anim/tween/Tweens.java b/jme3-core/src/main/java/com/jme3/anim/tween/Tweens.java index 454f62d7ba..d4200d71b0 100644 --- a/jme3-core/src/main/java/com/jme3/anim/tween/Tweens.java +++ b/jme3-core/src/main/java/com/jme3/anim/tween/Tweens.java @@ -163,11 +163,11 @@ public static Tween callMethod(Object target, String method, Object... args) { *
Tweens.callTweenMethod(1, myObject, "foo", "bar")
*

Would work for any of the following method signatures:

*
-     *    void foo( float t, String arg )
-     *    void foo( double t, String arg )
-     *    void foo( String arg, float t )
-     *    void foo( String arg, double t )
-     *  
+ * void foo(float t, String arg) + * void foo(double t, String arg) + * void foo(String arg, float t) + * void foo(String arg, double t) + * * * @param length the desired duration (in seconds) * @param target object on which the method is to be invoked @@ -208,7 +208,7 @@ public double curve(double t) { } else if (t > 1) { return 1; } - // Sine starting at -90 will go from -1 to 1 through 0 + // Sine starting at -90 will go from -1 to 1 through 0 double result = Math.sin(t * Math.PI - Math.PI * 0.5); return (result + 1) * 0.5; } @@ -575,7 +575,7 @@ private Method findMethod(Class type, String name, Object... args) { // We accept the 't' parameter as either first or last, // so we'll see which one matches. if (isFloatType(paramTypes[0]) || isDoubleType(paramTypes[0])) { - // Try it as the first parameter + // Try it as the first parameter int matches = 0; for (int i = 1; i < paramTypes.length; i++) { @@ -597,7 +597,7 @@ private Method findMethod(Class type, String name, Object... args) { return m; } - // Else try it at the end + // Else try it at the end int last = paramTypes.length - 1; if (isFloatType(paramTypes[last]) || isDoubleType(paramTypes[last])) { int matches = 0; diff --git a/jme3-core/src/main/java/com/jme3/anim/tween/action/ClipAction.java b/jme3-core/src/main/java/com/jme3/anim/tween/action/ClipAction.java index 35dbf83aba..9f5c855521 100644 --- a/jme3-core/src/main/java/com/jme3/anim/tween/action/ClipAction.java +++ b/jme3-core/src/main/java/com/jme3/anim/tween/action/ClipAction.java @@ -10,7 +10,6 @@ import java.util.List; public class ClipAction extends BlendableAction { - private AnimClip clip; private Transform transform = new Transform(); @@ -25,7 +24,7 @@ public void doInterpolate(double t) { for (AnimTrack track : tracks) { if (track instanceof TransformTrack) { TransformTrack tt = (TransformTrack) track; - if(getMask() != null && !getMask().contains(tt.getTarget())){ + if (getMask() != null && !getMask().contains(tt.getTarget())) { continue; } interpolateTransformTrack(t, tt); @@ -46,6 +45,7 @@ private void interpolateTransformTrack(double t, TransformTrack track) { this.collectTransform(target, transform, getTransitionWeight(), this); } } + private void interpolateMorphTrack(double t, MorphTrack track) { Geometry target = track.getTarget(); float[] weights = target.getMorphState(); diff --git a/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java b/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java index 0396e07486..9f5ef50d56 100644 --- a/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java +++ b/jme3-core/src/main/java/com/jme3/animation/AnimChannel.java @@ -44,14 +44,13 @@ * various parts of its body. For example, a character model may have an * animation channel for its feet, and another for its torso, and * the animations for each channel are controlled independently. - * + * * @author Kirill Vainer */ @Deprecated public final class AnimChannel { - private static final float DEFAULT_BLEND_TIME = 0.15f; - + private AnimControl control; private BitSet affectedBones; @@ -63,36 +62,35 @@ public final class AnimChannel { private float timeBlendFrom; private float blendTime; private float speedBlendFrom; - private boolean notified=false; + private boolean notified = false; private LoopMode loopMode, loopModeBlendFrom; - + private float blendAmount = 1f; - private float blendRate = 0; - - public AnimChannel(){ - + private float blendRate = 0; + + public AnimChannel() { } - - public AnimChannel(AnimControl control){ + + public AnimChannel(AnimControl control) { this.control = control; } /** * Returns the parent control of this AnimChannel. - * + * * @return the parent control of this AnimChannel. * @see AnimControl */ public AnimControl getControl() { return control; } - + /** * @return The name of the currently playing animation, or null if * none is assigned. * - * @see AnimChannel#setAnim(java.lang.String) + * @see AnimChannel#setAnim(java.lang.String) */ public String getAnimationName() { return animation != null ? animation.getName() : null; @@ -102,7 +100,7 @@ public String getAnimationName() { * @return The loop mode currently set for the animation. The loop mode * determines what will happen to the animation once it finishes * playing. - * + * * For more information, see the LoopMode enum class. * @see LoopMode * @see AnimChannel#setLoopMode(com.jme3.animation.LoopMode) @@ -141,10 +139,10 @@ public float getSpeed() { */ public void setSpeed(float speed) { this.speed = speed; - if(blendTime>0){ + if (blendTime > 0) { this.speedBlendFrom = speed; - blendTime = Math.min(blendTime, animation.getLength() / speed); - blendRate = 1/ blendTime; + blendTime = Math.min(blendTime, animation.getLength() / speed); + blendRate = 1 / blendTime; } } @@ -160,7 +158,7 @@ public float getTime() { /** * @param time Set the time of the currently playing animation, the time - * is clamped from 0 to {@link #getAnimMaxTime()}. + * is clamped from 0 to {@link #getAnimMaxTime()}. */ public void setTime(float time) { this.time = FastMath.clamp(time, 0, getAnimMaxTime()); @@ -172,7 +170,7 @@ public void setTime(float time) { * * @see AnimChannel#getTime() */ - public float getAnimMaxTime(){ + public float getAnimMaxTime() { return animation != null ? animation.getLength() : 0f; } @@ -188,7 +186,7 @@ public float getAnimMaxTime(){ * with the old one. If zero, then no blending will occur and the new * animation will be applied instantly. */ - public void setAnim(String name, float blendTime){ + public void setAnim(String name, float blendTime) { if (name == null) throw new IllegalArgumentException("name cannot be null"); @@ -197,21 +195,21 @@ public void setAnim(String name, float blendTime){ Animation anim = control.animationMap.get(name); if (anim == null) - throw new IllegalArgumentException("Cannot find animation named: '"+name+"'"); + throw new IllegalArgumentException("Cannot find animation named: '" + name + "'"); control.notifyAnimChange(this, name); - if (animation != null && blendTime > 0f){ + if (animation != null && blendTime > 0f) { this.blendTime = blendTime; // activate blending - blendTime = Math.min(blendTime, anim.getLength() / speed); + blendTime = Math.min(blendTime, anim.getLength() / speed); blendFrom = animation; timeBlendFrom = time; speedBlendFrom = speed; loopModeBlendFrom = loopMode; blendAmount = 0f; - blendRate = 1f / blendTime; - }else{ + blendRate = 1f / blendTime; + } else { blendFrom = null; } @@ -227,10 +225,10 @@ public void setAnim(String name, float blendTime){ *

* See {@link #setAnim(java.lang.String, float)}. * The blendTime argument by default is 150 milliseconds. - * + * * @param name The name of the animation to play */ - public void setAnim(String name){ + public void setAnim(String name) { setAnim(name, DEFAULT_BLEND_TIME); } @@ -244,7 +242,7 @@ public void addAllBones() { /** * Add a single bone to be influenced by this animation channel. - * + * * @param name the name of the Bone to be influenced */ public void addBone(String name) { @@ -258,7 +256,7 @@ public void addBone(String name) { */ public void addBone(Bone bone) { int boneIndex = control.getSkeleton().getBoneIndex(bone); - if(affectedBones == null) { + if (affectedBones == null) { affectedBones = new BitSet(control.getSkeleton().getBoneCount()); } affectedBones.set(boneIndex); @@ -314,19 +312,19 @@ public void addFromRootBone(Bone bone) { } } - BitSet getAffectedBones(){ + BitSet getAffectedBones() { return affectedBones; } - - public void reset(boolean rewind){ - if(rewind){ - setTime(0); - if(control.getSkeleton()!=null){ + + public void reset(boolean rewind) { + if (rewind) { + setTime(0); + if (control.getSkeleton() != null) { control.getSkeleton().resetAndUpdate(); - }else{ + } else { TempVars vars = TempVars.get(); update(0, vars); - vars.release(); + vars.release(); } } animation = null; @@ -337,31 +335,31 @@ void update(float tpf, TempVars vars) { if (animation == null) return; - if (blendFrom != null && blendAmount != 1.0f){ + if (blendFrom != null && blendAmount != 1.0f) { // The blendFrom anim is set, the actual animation - // playing will be set + // playing will be set // blendFrom.setTime(timeBlendFrom, 1f, control, this, vars); blendFrom.setTime(timeBlendFrom, 1f - blendAmount, control, this, vars); - + timeBlendFrom += tpf * speedBlendFrom; timeBlendFrom = AnimationUtils.clampWrapTime(timeBlendFrom, - blendFrom.getLength(), - loopModeBlendFrom); - if (timeBlendFrom < 0){ + blendFrom.getLength(), + loopModeBlendFrom); + if (timeBlendFrom < 0) { timeBlendFrom = -timeBlendFrom; speedBlendFrom = -speedBlendFrom; } blendAmount += tpf * blendRate; - if (blendAmount > 1f){ + if (blendAmount > 1f) { blendAmount = 1f; blendFrom = null; } } - + animation.setTime(time, blendAmount, control, this, vars); - time += tpf * speed; - if (animation.getLength() > 0){ + time += tpf * speed; + if (animation.getLength() > 0) { if (!notified && (time >= animation.getLength() || time < 0)) { if (loopMode == LoopMode.DontLoop) { // Note that this flag has to be set before calling the notify, @@ -370,10 +368,10 @@ void update(float tpf, TempVars vars) { notified = true; } control.notifyAnimCycleDone(this, animation.getName()); - } + } } time = AnimationUtils.clampWrapTime(time, animation.getLength(), loopMode); - if (time < 0){ + if (time < 0) { // Negative time indicates that speed should be inverted // (for cycle loop mode only) time = -time; diff --git a/jme3-core/src/main/java/com/jme3/animation/AnimControl.java b/jme3-core/src/main/java/com/jme3/animation/AnimControl.java index 68cb7f44cc..a7f9f1a35a 100644 --- a/jme3-core/src/main/java/com/jme3/animation/AnimControl.java +++ b/jme3-core/src/main/java/com/jme3/animation/AnimControl.java @@ -109,32 +109,32 @@ public AnimControl(Skeleton skeleton) { public AnimControl() { } - @Override + @Override public Object jmeClone() { AnimControl clone = (AnimControl) super.jmeClone(); clone.channels = new ArrayList(); clone.listeners = new ArrayList(); return clone; - } + } - @Override - public void cloneFields( Cloner cloner, Object original ) { + @Override + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); - + this.skeleton = cloner.clone(skeleton); - - // Note cloneForSpatial() never actually cloned the animation map... just its reference + + // Note cloneForSpatial() never actually cloned the animation map... just its reference HashMap newMap = new HashMap<>(); - - // animationMap is cloned, but only cloneable tracks will be cloned as they need a reference to a cloned spatial - for( Map.Entry e : animationMap.entrySet() ) { + + // animationMap is cloned, but only ClonableTracks will be cloned as they need a reference to a cloned spatial + for (Map.Entry e : animationMap.entrySet()) { newMap.put(e.getKey(), cloner.clone(e.getValue())); } - + this.animationMap = newMap; } - + /** * @param animations Set the animations that this AnimControl * will be capable of playing. The animations should be compatible @@ -182,7 +182,7 @@ public void removeAnim(Animation anim) { /** * Create a new animation channel, by default assigned to all bones * in the skeleton. - * + * * @return A new animation channel for this AnimControl. */ public AnimChannel createChannel() { @@ -376,11 +376,11 @@ public void read(JmeImporter im) throws IOException { } if (im.getFormatVersion() == 0) { - // Changed for backward compatibility with j3o files generated + // Changed for backward compatibility with j3o files generated // before the AnimControl/SkeletonControl split. - // If we find a target mesh array the AnimControl creates the - // SkeletonControl for old files and add it to the spatial. + // If we find a target mesh array the AnimControl creates the + // SkeletonControl for old files and add it to the spatial. // When backward compatibility isn't needed anymore, this can be deleted. Savable[] sav = in.readSavableArray("targets", null); if (sav != null) { diff --git a/jme3-core/src/main/java/com/jme3/animation/Animation.java b/jme3-core/src/main/java/com/jme3/animation/Animation.java index c6828cf7b3..554e6a0cc5 100644 --- a/jme3-core/src/main/java/com/jme3/animation/Animation.java +++ b/jme3-core/src/main/java/com/jme3/animation/Animation.java @@ -42,23 +42,22 @@ /** * The animation class updates the animation target with the tracks of a given type. - * + * * @author Kirill Vainer, Marcin Roguski (Kaelthas) * @deprecated use {@link com.jme3.anim.AnimClip} */ @Deprecated public class Animation implements Savable, Cloneable, JmeCloneable { - - /** - * The name of the animation. + /** + * The name of the animation. */ private String name; - /** - * The length of the animation. + /** + * The length of the animation. */ private float length; - /** - * The tracks of the animation. + /** + * The tracks of the animation. */ private SafeArrayList tracks = new SafeArrayList<>(Track.class); @@ -70,7 +69,7 @@ protected Animation() { /** * Creates a new Animation with the given name and length. - * + * * @param name The name of the animation. * @param length Length in seconds of the animation. */ @@ -89,7 +88,7 @@ public String getName() { /** * Returns the length in seconds of this animation - * + * * @return the length in seconds of this animation */ public float getLength() { @@ -118,7 +117,7 @@ public void setName(String name) { * This method sets the current time of the animation. * This method behaves differently for every known track type. * Override this method if you have your own type of track. - * + * * @param time the time of the animation * @param blendAmount the blend amount factor * @param control the animation control @@ -136,7 +135,7 @@ void setTime(float time, float blendAmount, AnimControl control, AnimChannel cha /** * Set the {@link Track}s to be used by this animation. - * + * * @param tracksArray The tracks to set. */ public void setTracks(Track[] tracksArray) { @@ -166,7 +165,7 @@ public void removeTrack(Track track) { /** * Returns the tracks set in {@link #setTracks(com.jme3.animation.Track[]) }. - * + * * @return the tracks set previously */ public Track[] getTracks() { @@ -192,7 +191,7 @@ public Animation clone() { } /** - * + * * @param spat the Spatial to clone for * @return a new instance */ @@ -213,33 +212,32 @@ public Animation cloneForSpatial(Spatial spat) { } } - @Override + @Override public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning", e); } - } + } - @Override - public void cloneFields( Cloner cloner, Object original ) { - + @Override + public void cloneFields(Cloner cloner, Object original) { // There is some logic here that I'm copying, but I'm not sure if // it's a mistake or not. If a track is not a CloneableTrack then it // isn't cloned at all... even though they all implement clone() methods. -pspeed SafeArrayList newTracks = new SafeArrayList<>(Track.class); - for( Track track : tracks ) { + for (Track track : tracks) { if (track instanceof JmeCloneable) { newTracks.add(cloner.clone(track)); } else { - // this is the part that seems fishy + // this is the part that seems fishy newTracks.add(track); } } this.tracks = newTracks; } - + @Override public String toString() { return getClass().getSimpleName() + "[name=" + name + ", length=" + length + ']'; diff --git a/jme3-core/src/main/java/com/jme3/animation/AnimationUtils.java b/jme3-core/src/main/java/com/jme3/animation/AnimationUtils.java index 4092821952..3e311a288a 100644 --- a/jme3-core/src/main/java/com/jme3/animation/AnimationUtils.java +++ b/jme3-core/src/main/java/com/jme3/animation/AnimationUtils.java @@ -36,10 +36,9 @@ * @author Nehon */ public class AnimationUtils { - - private AnimationUtils(){ - + private AnimationUtils() { } + /** * Clamps the time according to duration and loopMode * @@ -48,10 +47,10 @@ private AnimationUtils(){ * @param loopMode the animation's looping behavior (not null) * @return the clamped time (in seconds) */ - public static float clampWrapTime(float time, float duration, LoopMode loopMode){ - if (time == 0 || duration == 0) { + public static float clampWrapTime(float time, float duration, LoopMode loopMode) { + if (time == 0 || duration == 0) { return 0; // prevent division by 0 errors - } + } switch (loopMode) { case Cycle: boolean sign = ((int) (time / duration) % 2) != 0; @@ -62,5 +61,5 @@ public static float clampWrapTime(float time, float duration, LoopMode loopMode) return time % duration; } return time; - } + } } diff --git a/jme3-core/src/main/java/com/jme3/animation/AudioTrack.java b/jme3-core/src/main/java/com/jme3/animation/AudioTrack.java index a7112b9555..cccb883bee 100644 --- a/jme3-core/src/main/java/com/jme3/animation/AudioTrack.java +++ b/jme3-core/src/main/java/com/jme3/animation/AudioTrack.java @@ -156,9 +156,9 @@ public float getLength() { @Override public float[] getKeyFrameTimes() { - return new float[] { startOffset }; + return new float[]{startOffset}; } - + /** * Clone this track * @@ -197,27 +197,25 @@ public Track cloneForSpatial(Spatial spatial) { return audioTrack; } - @Override + @Override public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning", e); } - } - + } - @Override - public void cloneFields( Cloner cloner, Object original ) { + @Override + public void cloneFields(Cloner cloner, Object original) { // Duplicating the old cloned state from cloneForSpatial() this.initialized = false; this.started = false; - this.played = false; + this.played = false; this.audio = cloner.clone(audio); } - - - /** + + /** * recursive function responsible for finding the newly cloned AudioNode * * @param spat diff --git a/jme3-core/src/main/java/com/jme3/animation/Bone.java b/jme3-core/src/main/java/com/jme3/animation/Bone.java index 1cf7ce1b20..2d4211b90a 100644 --- a/jme3-core/src/main/java/com/jme3/animation/Bone.java +++ b/jme3-core/src/main/java/com/jme3/animation/Bone.java @@ -48,21 +48,21 @@ * Bone describes a bone in the bone-weight skeletal animation * system. A bone contains a name and an index, as well as relevant * transformation data. - * + * * A bone has 3 sets of transforms : * 1. The bind transforms, that are the transforms of the bone when the skeleton - * is in its rest pose (also called bind pose or T pose in the literature). - * The bind transforms are expressed in Local space meaning relatively to the + * is in its rest pose (also called bind pose or T pose in the literature). + * The bind transforms are expressed in Local space meaning relatively to the * parent bone. - * + * * 2. The Local transforms, that are the transforms of the bone once animation * or user transforms has been applied to the bind pose. The local transforms are * expressed in Local space meaning relatively to the parent bone. - * - * 3. The Model transforms, that are the transforms of the bone relatives to the - * rootBone of the skeleton. Those transforms are what is needed to apply skinning + * + * 3. The Model transforms, that are the transforms of the bone relatives to the + * rootBone of the skeleton. Those transforms are what is needed to apply skinning * to the mesh the skeleton controls. - * Note that there can be several rootBones in a skeleton. The one considered for + * Note that there can be several rootBones in a skeleton. The one considered for * these transforms is the one that is an ancestor of this bone. * * @author Kirill Vainer @@ -96,14 +96,14 @@ public final class Bone implements Savable, JmeCloneable { private Vector3f bindPos; private Quaternion bindRot; private Vector3f bindScale; - + /** - * The inverse bind transforms of this bone expressed in model space + * The inverse bind transforms of this bone expressed in model space */ private Vector3f modelBindInversePos; private Quaternion modelBindInverseRot; private Vector3f modelBindInverseScale; - + /** * The local animated or user transform combined with the local bind transform */ @@ -111,15 +111,15 @@ public final class Bone implements Savable, JmeCloneable { private Quaternion localRot = new Quaternion(); private Vector3f localScale = new Vector3f(1.0f, 1.0f, 1.0f); /** - * The model transforms of this bone + * The model transforms of this bone */ private Vector3f modelPos = new Vector3f(); private Quaternion modelRot = new Quaternion(); private Vector3f modelScale = new Vector3f(); - + // Used for getCombinedTransform private Transform tmpTransform; - + /** * Used to handle blending from one animation to another. * See {@link #blendAnimTransforms(com.jme3.math.Vector3f, com.jme3.math.Quaternion, com.jme3.math.Vector3f, float)} @@ -129,13 +129,13 @@ public final class Bone implements Savable, JmeCloneable { /** * Creates a new bone with the given name. - * + * * @param name Name to give to this bone */ public Bone(String name) { if (name == null) throw new IllegalArgumentException("Name cannot be null"); - + this.name = name; bindPos = new Vector3f(); @@ -148,13 +148,13 @@ public Bone(String name) { } /** - * Special-purpose copy constructor. + * Special-purpose copy constructor. *

* Only copies the name, user control state and bind pose transforms from the original. *

* The rest of the data is NOT copied, as it will be * generated automatically when the bone is animated. - * + * * @param source The bone from which to copy the data. */ Bone(Bone source) { @@ -178,48 +178,48 @@ public Bone(String name) { */ protected Bone() { } - - @Override + + @Override public Object jmeClone() { try { - Bone clone = (Bone)super.clone(); + Bone clone = (Bone) super.clone(); return clone; } catch (CloneNotSupportedException ex) { throw new AssertionError(); } - } + } + + @Override + public void cloneFields(Cloner cloner, Object original) { - @Override - public void cloneFields( Cloner cloner, Object original ) { - this.parent = cloner.clone(parent); - this.children = cloner.clone(children); - + this.children = cloner.clone(children); + this.attachNode = cloner.clone(attachNode); this.targetGeometry = cloner.clone(targetGeometry); this.bindPos = cloner.clone(bindPos); this.bindRot = cloner.clone(bindRot); this.bindScale = cloner.clone(bindScale); - + this.modelBindInversePos = cloner.clone(modelBindInversePos); this.modelBindInverseRot = cloner.clone(modelBindInverseRot); this.modelBindInverseScale = cloner.clone(modelBindInverseScale); - + this.localPos = cloner.clone(localPos); this.localRot = cloner.clone(localRot); this.localScale = cloner.clone(localScale); - + this.modelPos = cloner.clone(modelPos); this.modelRot = cloner.clone(modelRot); this.modelScale = cloner.clone(modelScale); - + this.tmpTransform = cloner.clone(tmpTransform); } /** * Returns the name of the bone, set in the constructor. - * + * * @return The name of the bone, set in the constructor. */ public String getName() { @@ -236,7 +236,7 @@ public Bone getParent() { /** * Returns all the children bones of this bone. - * + * * @return All the children bones of this bone. */ public ArrayList getChildren() { @@ -245,7 +245,7 @@ public ArrayList getChildren() { /** * Returns the local position of the bone, relative to the parent bone. - * + * * @return The local position of the bone, relative to the parent bone. */ public Vector3f getLocalPosition() { @@ -254,7 +254,7 @@ public Vector3f getLocalPosition() { /** * Returns the local rotation of the bone, relative to the parent bone. - * + * * @return The local rotation of the bone, relative to the parent bone. */ public Quaternion getLocalRotation() { @@ -263,7 +263,7 @@ public Quaternion getLocalRotation() { /** * Returns the local scale of the bone, relative to the parent bone. - * + * * @return The local scale of the bone, relative to the parent bone. */ public Vector3f getLocalScale() { @@ -272,7 +272,7 @@ public Vector3f getLocalScale() { /** * Returns the position of the bone in model space. - * + * * @return The position of the bone in model space. */ public Vector3f getModelSpacePosition() { @@ -281,7 +281,7 @@ public Vector3f getModelSpacePosition() { /** * Returns the rotation of the bone in model space. - * + * * @return The rotation of the bone in model space. */ public Quaternion getModelSpaceRotation() { @@ -290,7 +290,7 @@ public Quaternion getModelSpaceRotation() { /** * Returns the scale of the bone in model space. - * + * * @return The scale of the bone in model space. */ public Vector3f getModelSpaceScale() { @@ -301,19 +301,19 @@ public Vector3f getModelSpaceScale() { * @return the pre-existing vector * @deprecated use {@link #getModelBindInversePosition()} */ - @Deprecated + @Deprecated public Vector3f getWorldBindInversePosition() { return modelBindInversePos; } - - /** + + /** * Returns the inverse Bind position of this bone expressed in model space. *

* The inverse bind pose transform of the bone in model space is its "default" * transform with no animation applied. - * + * * @return the inverse bind position of this bone expressed in model space. - */ + */ public Vector3f getModelBindInversePosition() { return modelBindInversePos; } @@ -326,20 +326,19 @@ public Vector3f getModelBindInversePosition() { public Quaternion getWorldBindInverseRotation() { return modelBindInverseRot; } - - /** + + /** * Returns the inverse bind rotation of this bone expressed in model space. *

* The inverse bind pose transform of the bone in model space is its "default" * transform with no animation applied. - * + * * @return the inverse bind rotation of this bone expressed in model space. */ public Quaternion getModelBindInverseRotation() { return modelBindInverseRot; } - /** * @return the pre-existing vector * @deprecated use {@link #getModelBindInverseScale()} @@ -348,13 +347,13 @@ public Quaternion getModelBindInverseRotation() { public Vector3f getWorldBindInverseScale() { return modelBindInverseScale; } - + /** * Returns the inverse world bind pose scale. *

* The inverse bind pose transform of the bone in model space is its "default" * transform with no animation applied. - * + * * @return the inverse world bind pose scale. */ public Vector3f getModelBindInverseScale() { @@ -370,7 +369,7 @@ public Transform getModelBindInverseTransform() { } return t; } - + public Transform getBindInverseTransform() { Transform t = new Transform(); t.setTranslation(bindPos); @@ -380,7 +379,7 @@ public Transform getBindInverseTransform() { } return t.invert(); } - + /** * @return the pre-existing vector * @deprecated use {@link #getBindPosition()} @@ -389,13 +388,13 @@ public Transform getBindInverseTransform() { public Vector3f getWorldBindPosition() { return bindPos; } - - /** + + /** * Returns the bind position expressed in local space (relative to the parent bone). *

* The bind pose transform of the bone in local space is its "default" * transform with no animation applied. - * + * * @return the bind position in local space. */ public Vector3f getBindPosition() { @@ -405,7 +404,7 @@ public Vector3f getBindPosition() { /** * @return the pre-existing Quaternion * @deprecated use {@link #getBindRotation() } - */ + */ @Deprecated public Quaternion getWorldBindRotation() { return bindRot; @@ -416,13 +415,13 @@ public Quaternion getWorldBindRotation() { *

* The bind pose transform of the bone in local space is its "default" * transform with no animation applied. - * + * * @return the bind rotation in local space. - */ + */ public Quaternion getBindRotation() { return bindRot; - } - + } + /** * @return the pre-existing vector * @deprecated use {@link #getBindScale() } @@ -431,13 +430,13 @@ public Quaternion getBindRotation() { public Vector3f getWorldBindScale() { return bindScale; } - + /** * Returns the bind scale expressed in local space (relative to the parent bone). *

* The bind pose transform of the bone in local space is its "default" * transform with no animation applied. - * + * * @return the bind scale in local space. */ public Vector3f getBindScale() { @@ -457,7 +456,7 @@ public void setUserControl(boolean enable) { /** * Add a new child to this bone. Shouldn't be used by user code. * Can corrupt skeleton. - * + * * @param bone The bone to add */ public void addChild(Bone bone) { @@ -466,15 +465,14 @@ public void addChild(Bone bone) { } /** - * + * * @deprecated use {@link #updateModelTransforms() } */ @Deprecated - public final void updateWorldVectors(){ + public final void updateWorldVectors() { updateModelTransforms(); } - - + /** * Updates the model transforms for this bone and, possibly, the attachments node * if not null. @@ -497,11 +495,11 @@ public final void updateModelTransforms() { localPos.interpolateLocal(bindPos, invWeightSum); localScale.interpolateLocal(bindScale, invWeightSum); } - + // Future invocations of transform blend will start over. currentWeightSum = -1; } - + if (parent != null) { //rotation parent.modelRot.mult(localRot, modelRot); @@ -512,7 +510,7 @@ public final void updateModelTransforms() { parent.modelScale.mult(localScale, modelScale); //translation - //scale and rotation of parent affect bone position + //scale and rotation of parent affect bone position parent.modelRot.mult(localPos, modelPos); modelPos.multLocal(parent.modelScale); modelPos.addLocal(parent.modelPos); @@ -624,14 +622,14 @@ final void reset() { } } - /** + /** * Stores the skinning transform in the specified Matrix4f. * The skinning transform applies the animation of the bone to a vertex. - * + * * This assumes that the world transforms for the entire bone hierarchy * have already been computed, otherwise this method will return undefined * results. - * + * * @param outTransform */ void getOffsetTransform(Matrix4f outTransform, Quaternion tmp1, Vector3f tmp2, Vector3f tmp3, Matrix3f tmp4) { @@ -650,7 +648,7 @@ void getOffsetTransform(Matrix4f outTransform, Quaternion tmp1, Vector3f tmp2, V } /** - * + * * Sets the transforms of this bone in local space (relative to the parent bone) * * @param translation the translation in local space @@ -673,7 +671,7 @@ public void setUserTransforms(Vector3f translation, Quaternion rotation, Vector3 /** * Sets the transforms of this bone in model space (relative to the root bone) - * + * * Must update all bones in skeleton for this to work. * @param translation translation in model space * @param rotation rotation in model space @@ -686,9 +684,9 @@ public void setUserTransformsInModelSpace(Vector3f translation, Quaternion rotat // TODO: add scale here ??? modelPos.set(translation); modelRot.set(rotation); - - //if there is an attached Node we need to set its local transforms too. - if(attachNode != null){ + + // if there is an attached Node we need to set its local transforms too. + if (attachNode != null) { attachNode.setLocalTranslation(translation); attachNode.setLocalRotation(rotation); } @@ -701,7 +699,7 @@ public void setUserTransformsInModelSpace(Vector3f translation, Quaternion rotat * @return the resulting Transform (in reusable temporary storage!) */ public Transform getCombinedTransform(Vector3f position, Quaternion rotation) { - if(tmpTransform == null){ + if (tmpTransform == null) { tmpTransform = new Transform(); } rotation.mult(localPos, tmpTransform.getTranslation()).addLocal(position); @@ -781,7 +779,7 @@ void setAnimTransforms(Vector3f translation, Quaternion rotation, Vector3f scale * updateModelTransforms() call will result in final transform = transform * 0.5. * Two transform blends with weight = 0.5 each will result in the two * transforms blended together (nlerp) with blend = 0.5. - * + * * @param translation The translation to blend in * @param rotation The rotation to blend in * @param scale The scale to blend in @@ -792,13 +790,13 @@ void blendAnimTransforms(Vector3f translation, Quaternion rotation, Vector3f sca if (userControl) { return; } - + if (weight == 0) { // Do not apply this transform at all. return; } - if (currentWeightSum == 1){ + if (currentWeightSum == 1) { return; // More than 2 transforms are being blended } else if (currentWeightSum == -1 || currentWeightSum == 0) { // Set the transform fully @@ -810,14 +808,14 @@ void blendAnimTransforms(Vector3f translation, Quaternion rotation, Vector3f sca // Set the weight. It will be applied in updateModelTransforms(). currentWeightSum = weight; } else { - // The weight is already set. + // The weight is already set. // Blend in the new transform. TempVars vars = TempVars.get(); Vector3f tmpV = vars.vect1; Vector3f tmpV2 = vars.vect2; Quaternion tmpQ = vars.quat1; - + tmpV.set(bindPos).addLocal(translation); localPos.interpolateLocal(tmpV, weight); @@ -828,10 +826,10 @@ void blendAnimTransforms(Vector3f translation, Quaternion rotation, Vector3f sca tmpV2.set(bindScale).multLocal(scale); localScale.interpolateLocal(tmpV2, weight); } - + // Ensures no new weights will be blended in the future. currentWeightSum = 1; - + vars.release(); } } @@ -884,16 +882,16 @@ public void read(JmeImporter im) throws IOException { name = input.readString("name", null); int ver = input.getSavableVersion(Bone.class); - if(ver < 2){ + if (ver < 2) { bindPos = (Vector3f) input.readSavable("initialPos", null); bindRot = (Quaternion) input.readSavable("initialRot", null); bindScale = (Vector3f) input.readSavable("initialScale", new Vector3f(1.0f, 1.0f, 1.0f)); - }else{ + } else { bindPos = (Vector3f) input.readSavable("bindPos", null); bindRot = (Quaternion) input.readSavable("bindRot", null); bindScale = (Vector3f) input.readSavable("bindScale", new Vector3f(1.0f, 1.0f, 1.0f)); } - + attachNode = (Node) input.readSavable("attachNode", null); targetGeometry = (Geometry) input.readSavable("targetGeometry", null); @@ -931,7 +929,7 @@ public void write(JmeExporter ex) throws IOException { * * @param rot the desired rotation (not null, unaffected) */ - public void setLocalRotation(Quaternion rot){ + public void setLocalRotation(Quaternion rot) { if (!userControl) { throw new IllegalStateException("User control must be on bone to allow user transforms"); } @@ -944,7 +942,7 @@ public void setLocalRotation(Quaternion rot){ * * @param pos the desired translation (not null, unaffected) */ - public void setLocalTranslation(Vector3f pos){ + public void setLocalTranslation(Vector3f pos) { if (!userControl) { throw new IllegalStateException("User control must be on bone to allow user transforms"); } @@ -956,7 +954,7 @@ public void setLocalTranslation(Vector3f pos){ * Warning: you need to call {@link #setUserControl(boolean)} with true to be able to do that operation * @param scale the scale to apply */ - public void setLocalScale(Vector3f scale){ + public void setLocalScale(Vector3f scale) { if (!userControl) { throw new IllegalStateException("User control must be on bone to allow user transforms"); } @@ -968,7 +966,7 @@ public void setLocalScale(Vector3f scale){ * @see #setUserControl(boolean) * @return true if it can be manipulated */ - public boolean hasUserControl(){ + public boolean hasUserControl() { return userControl; } } diff --git a/jme3-core/src/main/java/com/jme3/animation/BoneTrack.java b/jme3-core/src/main/java/com/jme3/animation/BoneTrack.java index e3272413fe..88781f8a08 100644 --- a/jme3-core/src/main/java/com/jme3/animation/BoneTrack.java +++ b/jme3-core/src/main/java/com/jme3/animation/BoneTrack.java @@ -42,7 +42,7 @@ /** * Contains a list of transforms and times for each keyframe. - * + * * @author Kirill Vainer * @deprecated use {@link com.jme3.anim.AnimTrack} */ @@ -53,7 +53,7 @@ public final class BoneTrack implements JmeCloneable, Track { * Bone index in the skeleton which this track affects. */ private int targetBoneIndex; - + /** * Transforms and times for track. */ @@ -61,7 +61,7 @@ public final class BoneTrack implements JmeCloneable, Track { private CompactQuaternionArray rotations; private CompactVector3Array scales; private float[] times; - + /** * Serialization-only. Do not use. */ @@ -191,7 +191,7 @@ public void setKeyframes(float[] times, Vector3f[] translations, Quaternion[] ro } /** - * + * * Modify the bone which this track modifies in the skeleton to contain * the correct animation transforms for a given time. * The transforms can be interpolated in some method from the keyframes. @@ -208,7 +208,7 @@ public void setTime(float time, float weight, AnimControl control, AnimChannel c if (affectedBones != null && !affectedBones.get(targetBoneIndex)) { return; } - + Bone target = control.getSkeleton().getBone(targetBoneIndex); Vector3f tempV = vars.vect1; @@ -217,7 +217,7 @@ public void setTime(float time, float weight, AnimControl control, AnimChannel c Vector3f tempV2 = vars.vect3; Vector3f tempS2 = vars.vect4; Quaternion tempQ2 = vars.quat2; - + int lastFrame = times.length - 1; if (time < 0 || lastFrame == 0) { rotations.get(0, tempQ); @@ -260,12 +260,12 @@ public void setTime(float time, float weight, AnimControl control, AnimChannel c } // if (weight != 1f) { - target.blendAnimTransforms(tempV, tempQ, scales != null ? tempS : null, weight); + target.blendAnimTransforms(tempV, tempQ, scales != null ? tempS : null, weight); // } else { // target.setAnimTransforms(tempV, tempQ, scales != null ? tempS : null); // } } - + /** * @return the length of the track */ @@ -341,7 +341,7 @@ public void read(JmeImporter im) throws IOException { scales = (CompactVector3Array) ic.readSavable("scales", null); //Backward compatibility for old j3o files generated before revision 6807 - if (im.getFormatVersion() == 0){ + if (im.getFormatVersion() == 0) { if (translations == null) { Savable[] sav = ic.readSavableArray("translations", null); if (sav != null) { diff --git a/jme3-core/src/main/java/com/jme3/animation/CompactFloatArray.java b/jme3-core/src/main/java/com/jme3/animation/CompactFloatArray.java index 097bfa4009..27d62c2b63 100644 --- a/jme3-core/src/main/java/com/jme3/animation/CompactFloatArray.java +++ b/jme3-core/src/main/java/com/jme3/animation/CompactFloatArray.java @@ -81,12 +81,12 @@ public void read(JmeImporter im) throws IOException { index = in.readIntArray("index", null); } - public void fill(int startIndex, float[] store ){ + public void fill(int startIndex, float[] store) { for (int i = 0; i < store.length; i++) { store[i] = get(startIndex + i, null); } } - + @Override protected void serialize(int i, Float data) { array[i] = data; @@ -96,4 +96,4 @@ protected void serialize(int i, Float data) { protected Float deserialize(int i, Float store) { return array[i]; } -} \ No newline at end of file +} diff --git a/jme3-core/src/main/java/com/jme3/animation/EffectTrack.java b/jme3-core/src/main/java/com/jme3/animation/EffectTrack.java index b4fafc1904..60a0f30dae 100644 --- a/jme3-core/src/main/java/com/jme3/animation/EffectTrack.java +++ b/jme3-core/src/main/java/com/jme3/animation/EffectTrack.java @@ -96,8 +96,6 @@ public void setSpatial(Spatial spatial) { throw new IllegalArgumentException("KillParticleEmitter can only ba attached to ParticleEmitter"); } } - - } @Override @@ -241,7 +239,7 @@ public float getLength() { @Override public float[] getKeyFrameTimes() { - return new float[] { startOffset }; + return new float[]{startOffset}; } /** @@ -288,14 +286,13 @@ public Track cloneForSpatial(Spatial spatial) { public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning", e); } } - @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.emitter = cloner.clone(emitter); } @@ -391,8 +388,6 @@ private void setUserData(EffectTrack effectTrack) { //adding the given Track to the TrackInfo. data.addTrack(effectTrack); - - } private void removeUserData(EffectTrack effectTrack) { @@ -406,8 +401,6 @@ private void removeUserData(EffectTrack effectTrack) { //removing the given Track to the TrackInfo. data.getTracks().remove(effectTrack); - - } /** diff --git a/jme3-core/src/main/java/com/jme3/animation/Pose.java b/jme3-core/src/main/java/com/jme3/animation/Pose.java index 84ea4cfc75..f2208e1937 100644 --- a/jme3-core/src/main/java/com/jme3/animation/Pose.java +++ b/jme3-core/src/main/java/com/jme3/animation/Pose.java @@ -50,10 +50,10 @@ public final class Pose implements Savable, Cloneable { private Vector3f[] offsets; private int[] indices; - private transient final Vector3f tempVec = new Vector3f(); + private transient final Vector3f tempVec = new Vector3f(); private transient final Vector3f tempVec2 = new Vector3f(); - public Pose(String name, int targetMeshIndex, Vector3f[] offsets, int[] indices){ + public Pose(String name, int targetMeshIndex, Vector3f[] offsets, int[] indices) { this.name = name; this.targetMeshIndex = targetMeshIndex; this.offsets = offsets; @@ -63,25 +63,23 @@ public Pose(String name, int targetMeshIndex, Vector3f[] offsets, int[] indices) /** * Serialization-only. Do not use. */ - protected Pose() - { + protected Pose() { } - - public int getTargetMeshIndex(){ + + public int getTargetMeshIndex() { return targetMeshIndex; } - /** * Applies the offsets of this pose to the vertex buffer given by the blend factor. * * @param blend Blend factor, 0 = no change to vertex buffer, 1 = apply full offsets * @param vertexBuffer Vertex buffer to apply this pose to */ - public void apply(float blend, FloatBuffer vertexBuffer){ - for (int i = 0; i < indices.length; i++){ + public void apply(float blend, FloatBuffer vertexBuffer) { + for (int i = 0; i < indices.length; i++) { Vector3f offset = offsets[i]; - int vertIndex = indices[i]; + int vertIndex = indices[i]; tempVec.set(offset).multLocal(blend); @@ -95,7 +93,7 @@ public void apply(float blend, FloatBuffer vertexBuffer){ BufferUtils.setInBuffer(tempVec2, vertexBuffer, vertIndex); } } - + /** * This method creates a clone of the current object. * @return a clone of the current object diff --git a/jme3-core/src/main/java/com/jme3/animation/PoseTrack.java b/jme3-core/src/main/java/com/jme3/animation/PoseTrack.java index bfb6f76433..4a7405ef7c 100644 --- a/jme3-core/src/main/java/com/jme3/animation/PoseTrack.java +++ b/jme3-core/src/main/java/com/jme3/animation/PoseTrack.java @@ -40,7 +40,6 @@ */ @Deprecated public final class PoseTrack implements Track { - private int targetMeshIndex; private PoseFrame[] frames; private float[] times; @@ -54,14 +53,13 @@ public PoseFrame(Pose[] poses, float[] weights) { this.poses = poses; this.weights = weights; } - + /** * Serialization-only. Do not use. */ - protected PoseFrame() - { + protected PoseFrame() { } - + /** * This method creates a clone of the current object. * @return a clone of the current object @@ -94,7 +92,7 @@ public void write(JmeExporter e) throws IOException { public void read(JmeImporter i) throws IOException { InputCapsule in = i.getCapsule(this); weights = in.readFloatArray("weights", null); - + Savable[] readSavableArray = in.readSavableArray("poses", null); if (readSavableArray != null) { poses = new Pose[readSavableArray.length]; @@ -103,24 +101,23 @@ public void read(JmeImporter i) throws IOException { } } - public PoseTrack(int targetMeshIndex, float[] times, PoseFrame[] frames){ + public PoseTrack(int targetMeshIndex, float[] times, PoseFrame[] frames) { this.targetMeshIndex = targetMeshIndex; this.times = times; this.frames = frames; } - + /** * Serialization-only. Do not use. */ - protected PoseTrack() - { + protected PoseTrack() { } - + @Override public void setTime(float time, float weight, AnimControl control, AnimChannel channel, TempVars vars) { // TODO: When MeshControl is created, it will gather targets // list automatically which is then retrieved here. - + /* Mesh target = targets[targetMeshIndex]; if (time < times[0]) { @@ -150,12 +147,12 @@ public void setTime(float time, float weight, AnimControl control, AnimChannel c public float getLength() { return times == null ? 0 : times[times.length - 1] - times[0]; } - + @Override public float[] getKeyFrameTimes() { return times; } - + /** * This method creates a clone of the current object. * @return a clone of the current object @@ -176,7 +173,7 @@ public PoseTrack clone() { throw new AssertionError(); } } - + @Override public void write(JmeExporter e) throws IOException { OutputCapsule out = e.getCapsule(this); @@ -190,7 +187,7 @@ public void read(JmeImporter i) throws IOException { InputCapsule in = i.getCapsule(this); targetMeshIndex = in.readInt("meshIndex", 0); times = in.readFloatArray("times", null); - + Savable[] readSavableArray = in.readSavableArray("frames", null); if (readSavableArray != null) { frames = new PoseFrame[readSavableArray.length]; diff --git a/jme3-core/src/main/java/com/jme3/animation/Skeleton.java b/jme3-core/src/main/java/com/jme3/animation/Skeleton.java index 31bff375b2..28a8515b2d 100644 --- a/jme3-core/src/main/java/com/jme3/animation/Skeleton.java +++ b/jme3-core/src/main/java/com/jme3/animation/Skeleton.java @@ -46,7 +46,7 @@ * Skeleton is a convenience class for managing a bone hierarchy. * Skeleton updates the world transforms to reflect the current local * animated matrixes. - * + * * @author Kirill Vainer * @deprecated use {@link Armature} */ @@ -55,7 +55,7 @@ public final class Skeleton implements Savable, JmeCloneable { private Bone[] rootBones; private Bone[] boneList; - + /** * Contains the skinning matrices, multiplying it by a vertex affected by a bone * will cause it to go to the animated position. @@ -63,12 +63,12 @@ public final class Skeleton implements Savable, JmeCloneable { private transient Matrix4f[] skinningMatrixes; /** - * Creates a skeleton from a bone list. + * Creates a skeleton from a bone list. * The root bones are found automatically. *

* Note that using this constructor will cause the bones in the list * to have their bind pose recomputed based on their local transforms. - * + * * @param boneList The list of bones to manage by this Skeleton */ public Skeleton(Bone[] boneList) { @@ -97,7 +97,7 @@ public Skeleton(Bone[] boneList) { *

* Shallow copies bind pose data from the source skeleton, does not * copy any other data. - * + * * @param source The source Skeleton to copy from */ public Skeleton(Skeleton source) { @@ -124,18 +124,18 @@ public Skeleton(Skeleton source) { protected Skeleton() { } - @Override + @Override public Object jmeClone() { try { - Skeleton clone = (Skeleton)super.clone(); + Skeleton clone = (Skeleton) super.clone(); return clone; } catch (CloneNotSupportedException ex) { throw new AssertionError(); } - } + } - @Override - public void cloneFields( Cloner cloner, Object original ) { + @Override + public void cloneFields(Cloner cloner, Object original) { this.rootBones = cloner.clone(rootBones); this.boneList = cloner.clone(boneList); this.skinningMatrixes = cloner.clone(skinningMatrixes); @@ -254,7 +254,7 @@ public int getBoneIndex(Bone bone) { * returns the bone index of the bone that has the given name * * @param name the name to search for - * @return the index (≥0) or -1 if not found + * @return the index (≥0) or -1 if not found */ public int getBoneIndex(String name) { for (int i = 0; i < boneList.length; i++) { diff --git a/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java b/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java index 4b2d6db9a6..d6e7392cae 100644 --- a/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java +++ b/jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java @@ -78,38 +78,37 @@ public class SkeletonControl extends AbstractControl implements Cloneable, JmeCl * are visible in at least one camera. */ private boolean wasMeshUpdated = false; - + /** * User wishes to use hardware skinning if available. */ private transient boolean hwSkinningDesired = true; - + /** * Hardware skinning is currently being used. */ private transient boolean hwSkinningEnabled = false; - + /** * Hardware skinning was tested on this GPU, results * are stored in {@link #hwSkinningSupported} variable. */ private transient boolean hwSkinningTested = false; - + /** * If hardware skinning was {@link #hwSkinningTested tested}, then * this variable will be set to true if supported, and false if otherwise. */ private transient boolean hwSkinningSupported = false; - + /** * Bone offset matrices, recreated each frame */ private transient Matrix4f[] offsetMatrices; - private MatParamOverride numberOfBonesParam; private MatParamOverride boneMatricesParam; - + /** * Serialization only. Do not use. */ @@ -119,11 +118,11 @@ protected SkeletonControl() { private void switchToHardware() { numberOfBonesParam.setEnabled(true); boneMatricesParam.setEnabled(true); - + // Next full 10 bones (e.g. 30 on 24 bones) int numBones = ((skeleton.getBoneCount() / 10) + 1) * 10; numberOfBonesParam.setValue(numBones); - + for (Geometry geometry : targets) { Mesh mesh = geometry.getMesh(); if (mesh != null && mesh.isAnimated()) { @@ -135,7 +134,7 @@ private void switchToHardware() { private void switchToSoftware() { numberOfBonesParam.setEnabled(false); boneMatricesParam.setEnabled(false); - + for (Geometry geometry : targets) { Mesh mesh = geometry.getMesh(); if (mesh != null && mesh.isAnimated()) { @@ -152,7 +151,7 @@ private boolean testHardwareSupported(RenderManager rm) { } switchToHardware(); - + try { rm.preloadScene(spatial); return true; @@ -166,32 +165,32 @@ private boolean testHardwareSupported(RenderManager rm) { * Specifies if hardware skinning is preferred. If it is preferred and * supported by GPU, it shall be enabled, if it's not preferred, or not * supported by GPU, then it shall be disabled. - * - * @param preferred true to prefer hardware skinning, false to prefer + * + * @param preferred true to prefer hardware skinning, false to prefer * software skinning (default=true) - * @see #isHardwareSkinningUsed() + * @see #isHardwareSkinningUsed() */ public void setHardwareSkinningPreferred(boolean preferred) { hwSkinningDesired = preferred; } - + /** * @return True if hardware skinning is preferable to software skinning. * Set to false by default. - * - * @see #setHardwareSkinningPreferred(boolean) + * + * @see #setHardwareSkinningPreferred(boolean) */ public boolean isHardwareSkinningPreferred() { return hwSkinningDesired; } - + /** * @return True is hardware skinning is activated and is currently used, false otherwise. */ public boolean isHardwareSkinningUsed() { return hwSkinningEnabled; } - + /** * Creates a skeleton control. The list of targets will be acquired * automatically when the control is attached to a node. @@ -216,7 +215,6 @@ private void findTargets(Geometry geometry) { if (mesh != null && mesh.isAnimated()) { targets.add(geometry); } - } private void findTargets(Node node) { @@ -234,12 +232,12 @@ public void setSpatial(Spatial spatial) { Spatial oldSpatial = this.spatial; super.setSpatial(spatial); updateTargetsAndMaterials(spatial); - + if (oldSpatial != null) { oldSpatial.removeMatParamOverride(numberOfBonesParam); oldSpatial.removeMatParamOverride(boneMatricesParam); } - + if (spatial != null) { spatial.removeMatParamOverride(numberOfBonesParam); spatial.removeMatParamOverride(boneMatricesParam); @@ -259,19 +257,19 @@ private void controlRenderSoftware() { // already ensured this mesh is animated. // Otherwise a crash will happen in skin update. softwareSkinUpdate(mesh, offsetMatrices); - } + } } - + private void controlRenderHardware() { offsetMatrices = skeleton.computeSkinningMatrices(); boneMatricesParam.setValue(offsetMatrices); } - + @Override protected void controlRender(RenderManager rm, ViewPort vp) { if (!wasMeshUpdated) { updateTargetsAndMaterials(spatial); - + // Prevent illegal cases. These should never happen. assert hwSkinningTested || (!hwSkinningTested && !hwSkinningSupported && !hwSkinningEnabled); assert !hwSkinningEnabled || (hwSkinningEnabled && hwSkinningTested && hwSkinningSupported); @@ -282,7 +280,7 @@ protected void controlRender(RenderManager rm, ViewPort vp) { if (hwSkinningSupported) { hwSkinningEnabled = true; - + Logger.getLogger(SkeletonControl.class.getName()).log(Level.INFO, "Hardware skinning engaged for {0}", spatial); } else { switchToSoftware(); @@ -308,7 +306,7 @@ protected void controlRender(RenderManager rm, ViewPort vp) { @Override protected void controlUpdate(float tpf) { wasMeshUpdated = false; - } + } //only do this for software updates void resetToBind() { @@ -344,32 +342,31 @@ void resetToBind() { tb.put(btb).clear(); } - pb.put(bpb).clear(); nb.put(bnb).clear(); } } } - @Override + @Override public Object jmeClone() { return super.jmeClone(); - } + } - @Override - public void cloneFields( Cloner cloner, Object original ) { + @Override + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); - + this.skeleton = cloner.clone(skeleton); - + // If the targets were cloned then this will clone them. If the targets // were shared then this will share them. this.targets = cloner.clone(targets); - + this.numberOfBonesParam = cloner.clone(numberOfBonesParam); this.boneMatricesParam = cloner.clone(boneMatricesParam); } - + /** * Access the attachments node of the named bone. If the bone doesn't * already have an attachments node, create one and attach it to the scene @@ -445,8 +442,6 @@ private void softwareSkinUpdate(Mesh mesh, Matrix4f[] offsetMatrices) { //if there are tangents use the skinning with tangents applySkinningTangents(mesh, offsetMatrices, tb); } - - } /** @@ -582,11 +577,9 @@ private void applySkinningTangents(Mesh mesh, Matrix4f[] offsetMatrices, VertexB FloatBuffer fnb = (FloatBuffer) nb.getData(); fnb.rewind(); - FloatBuffer ftb = (FloatBuffer) tb.getData(); ftb.rewind(); - // get boneIndexes and weights for mesh IndexBuffer ib = IndexBuffer.wrapIndexBuffer(mesh.getBuffer(Type.BoneIndex).getData()); FloatBuffer wb = (FloatBuffer) mesh.getBuffer(Type.BoneWeight).getData(); @@ -598,7 +591,6 @@ private void applySkinningTangents(Mesh mesh, Matrix4f[] offsetMatrices, VertexB TempVars vars = TempVars.get(); - float[] posBuf = vars.skinPositions; float[] normBuf = vars.skinNormals; float[] tanBuf = vars.skinTangents; @@ -695,8 +687,6 @@ private void applySkinningTangents(Mesh mesh, Matrix4f[] offsetMatrices, VertexB vb.updateData(fvb); nb.updateData(fnb); tb.updateData(ftb); - - } @Override @@ -704,7 +694,7 @@ public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); oc.write(skeleton, "skeleton", null); - + oc.write(numberOfBonesParam, "numberOfBonesParam", null); oc.write(boneMatricesParam, "boneMatricesParam", null); } @@ -714,10 +704,10 @@ public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule in = im.getCapsule(this); skeleton = (Skeleton) in.readSavable("skeleton", null); - + numberOfBonesParam = (MatParamOverride) in.readSavable("numberOfBonesParam", null); boneMatricesParam = (MatParamOverride) in.readSavable("boneMatricesParam", null); - + if (numberOfBonesParam == null) { numberOfBonesParam = new MatParamOverride(VarType.Int, "NumberOfBones", null); boneMatricesParam = new MatParamOverride(VarType.Matrix4Array, "BoneMatrices", null); diff --git a/jme3-core/src/main/java/com/jme3/animation/TrackInfo.java b/jme3-core/src/main/java/com/jme3/animation/TrackInfo.java index f8c2169c3b..5d3c1cbfba 100644 --- a/jme3-core/src/main/java/com/jme3/animation/TrackInfo.java +++ b/jme3-core/src/main/java/com/jme3/animation/TrackInfo.java @@ -42,7 +42,7 @@ * This class is intended as a UserData added to a Spatial that is referenced by a Track. * (ParticleEmitter for EffectTrack and AudioNode for AudioTrack) * It holds the list of tracks that are directly referencing the Spatial. - * + * * This is used when loading a Track to find the cloned reference of a Spatial in the cloned model returned by the assetManager. * * @author Nehon @@ -75,18 +75,18 @@ public ArrayList getTracks() { public void addTrack(Track track) { tracks.add(track); } - - @Override + + @Override public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning", e); } - } + } - @Override - public void cloneFields( Cloner cloner, Object original ) { - this.tracks = cloner.clone(tracks); - } + @Override + public void cloneFields(Cloner cloner, Object original) { + this.tracks = cloner.clone(tracks); + } } diff --git a/jme3-core/src/main/java/com/jme3/app/BasicProfiler.java b/jme3-core/src/main/java/com/jme3/app/BasicProfiler.java index 3d1d663e0a..e7ae0a7884 100644 --- a/jme3-core/src/main/java/com/jme3/app/BasicProfiler.java +++ b/jme3-core/src/main/java/com/jme3/app/BasicProfiler.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - + package com.jme3.app; import com.jme3.profile.*; @@ -40,13 +40,12 @@ import com.jme3.util.BufferUtils; import java.nio.FloatBuffer; - /** * An AppProfiler implementation that collects two - * per-frame application-wide timings for update versus - * render and uses it to create a bar chart style Mesh. - * The number of frames displayed and the update interval - * can be specified. The chart Mesh is in 'milliseconds' + * per-frame application-wide timings for update versus + * render and uses it to create a bar chart style Mesh. + * The number of frames displayed and the update interval + * can be specified. The chart Mesh is in 'milliseconds' * and can be scaled up or down as required. * *

Each column of the chart represents a single frames @@ -56,9 +55,9 @@ * the cyan portion represents the rendering time.

* *

When the end of the chart is reached, the current - * frame cycles back around to the beginning.

+ * frame cycles back around to the beginning.

* - * @author Paul Speed + * @author Paul Speed */ public class BasicProfiler implements AppProfiler { @@ -69,38 +68,38 @@ public class BasicProfiler implements AppProfiler { private long renderTime; private long updateInterval = 1000000L; // once a millisecond private long lastUpdate = 0; - + private Mesh mesh; - + public BasicProfiler() { this(1280); } - - public BasicProfiler( int size ) { + + public BasicProfiler(int size) { setFrameCount(size); } /** * Sets the number of frames to display and track. By default, * this is 1280. - * + * * @param size the desired number of frames (≥0, default=1280) */ - public final void setFrameCount( int size ) { - if( this.size == size ) { + public final void setFrameCount(int size) { + if (this.size == size) { return; } - + this.size = size; - this.frames = new long[size*2]; - + this.frames = new long[size * 2]; + createMesh(); - - if( frameIndex >= size ) { + + if (frameIndex >= size) { frameIndex = 0; - } + } } - + public int getFrameCount() { return size; } @@ -108,13 +107,13 @@ public int getFrameCount() { /** * Sets the number of nanoseconds to wait before updating the * mesh. By default, this is once a millisecond, i.e. 1000000 nanoseconds. - * + * * @param nanos the desired update interval (in nanoseconds, default=1e6) */ - public void setUpdateInterval( long nanos ) { + public void setUpdateInterval(long nanos) { this.updateInterval = nanos; } - + public long getUpdateInterval() { return updateInterval; } @@ -122,7 +121,7 @@ public long getUpdateInterval() { /** * Returns the mesh that contains the bar chart of tracked frame * timings. - * + * * @return the pre-existing Mesh */ public Mesh getMesh() { @@ -130,33 +129,33 @@ public Mesh getMesh() { } protected final void createMesh() { - if( mesh == null ) { + if (mesh == null) { mesh = new Mesh(); mesh.setMode(Mesh.Mode.Lines); } - + mesh.setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(size * 4 * 3)); - + FloatBuffer cb = BufferUtils.createFloatBuffer(size * 4 * 4); - for( int i = 0; i < size; i++ ) { + for (int i = 0; i < size; i++) { // For each index we add 4 colors, one for each line // endpoint for two layers. cb.put(0.5f).put(0.5f).put(0).put(1); cb.put(1).put(1).put(0).put(1); cb.put(0).put(0.5f).put(0.5f).put(1); cb.put(0).put(1).put(1).put(1); - } + } mesh.setBuffer(Type.Color, 4, cb); } - + protected void updateMesh() { - FloatBuffer pb = (FloatBuffer)mesh.getBuffer(Type.Position).getData(); + FloatBuffer pb = (FloatBuffer) mesh.getBuffer(Type.Position).getData(); pb.rewind(); float scale = 1 / 1000000f; // scaled to ms as pixels - for( int i = 0; i < size; i++ ) { + for (int i = 0; i < size; i++) { float t1 = frames[i * 2] * scale; float t2 = frames[i * 2 + 1] * scale; - + pb.put(i).put(0).put(0); pb.put(i).put(t1).put(0); pb.put(i).put(t1).put(0); @@ -166,9 +165,8 @@ protected void updateMesh() { } @Override - public void appStep( AppStep step ) { - - switch(step) { + public void appStep(AppStep step) { + switch (step) { case BeginFrame: startTime = System.nanoTime(); break; @@ -180,30 +178,26 @@ public void appStep( AppStep step ) { long time = System.nanoTime(); frames[frameIndex * 2 + 1] = time - renderTime; frameIndex++; - if( frameIndex >= size ) { + if (frameIndex >= size) { frameIndex = 0; } - if( startTime - lastUpdate > updateInterval ) { + if (startTime - lastUpdate > updateInterval) { updateMesh(); lastUpdate = startTime; - } + } break; } } - + @Override public void appSubStep(String... additionalInfo) { } - + @Override - public void vpStep( VpStep step, ViewPort vp, Bucket bucket ) { + public void vpStep(VpStep step, ViewPort vp, Bucket bucket) { } @Override public void spStep(SpStep step, String... additionalInfo) { - } - } - - diff --git a/jme3-core/src/main/java/com/jme3/app/BasicProfilerState.java b/jme3-core/src/main/java/com/jme3/app/BasicProfilerState.java index 50ace1dab6..d7b56511a6 100644 --- a/jme3-core/src/main/java/com/jme3/app/BasicProfilerState.java +++ b/jme3-core/src/main/java/com/jme3/app/BasicProfilerState.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - + package com.jme3.app; import com.jme3.app.state.BaseAppState; @@ -44,13 +44,12 @@ import com.jme3.scene.Node; import com.jme3.scene.VertexBuffer.Type; - /** * Provides a basic profiling visualization that shows * per-frame application-wide timings for update and * rendering. * - * @author Paul Speed + * @author Paul Speed */ public class BasicProfilerState extends BaseAppState { @@ -67,7 +66,7 @@ public BasicProfilerState() { this(false); } - public BasicProfilerState( boolean enabled ) { + public BasicProfilerState(boolean enabled) { setEnabled(enabled); this.profiler = new BasicProfiler(); } @@ -86,82 +85,82 @@ public BasicProfiler getProfiler() { * single millisecond stretches two pixels high. * @param scale the scale */ - public void setGraphScale( float scale ) { - if( this.scale == scale ) { + public void setGraphScale(float scale) { + if (this.scale == scale) { return; } this.scale = scale; - if( graph != null ) { - graph.setLocalScale(1, scale, 1); + if (graph != null) { + graph.setLocalScale(1, scale, 1); } } public float getGraphScale() { return scale; } - + /** * Sets the number frames displayed and tracked. * @param count the number of frames */ - public void setFrameCount( int count ) { - if( profiler.getFrameCount() == count ) { + public void setFrameCount(int count) { + if (profiler.getFrameCount() == count) { return; } profiler.setFrameCount(count); refreshBackground(); } - + public int getFrameCount() { return profiler.getFrameCount(); } - + protected void refreshBackground() { Mesh mesh = background.getMesh(); - + int size = profiler.getFrameCount(); float frameTime = 1000f / 60; mesh.setBuffer(Type.Position, 3, new float[] { - + // first quad 0, 0, 0, size, 0, 0, size, frameTime, 0, 0, frameTime, 0, - + // second quad 0, frameTime, 0, size, frameTime, 0, size, frameTime * 2, 0, 0, frameTime * 2, 0, - + // A lower dark border just to frame the // 'update' stats against bright backgrounds 0, -2, 0, size, -2, 0, size, 0, 0, - 0, 0, 0 + 0, 0, 0 }); - + mesh.setBuffer(Type.Color, 4, new float[] { // first quad, within normal frame limits 0, 1, 0, 0.25f, 0, 1, 0, 0.25f, 0, 0.25f, 0, 0.25f, 0, 0.25f, 0, 0.25f, - - // Second quad, dropped frames + + // Second quad, dropped frames 0.25f, 0, 0, 0.25f, 0.25f, 0, 0, 0.25f, 1, 0, 0, 0.25f, 1, 0, 0, 0.25f, - + 0, 0, 0, 0.5f, 0, 0, 0, 0.5f, 0, 0, 0, 0.5f, - 0, 0, 0, 0.5f + 0, 0, 0, 0.5f }); - + mesh.setBuffer(Type.Index, 3, new short[] { 0, 1, 2, 0, 2, 3, @@ -173,16 +172,15 @@ protected void refreshBackground() { } @Override - protected void initialize( Application app ) { - + protected void initialize(Application app) { graph = new Geometry("profiler", profiler.getMesh()); - + Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setBoolean("VertexColor", true); graph.setMaterial(mat); graph.setLocalTranslation(0, 300, 0); graph.setLocalScale(1, scale, 1); - + Mesh mesh = new Mesh(); background = new Geometry("profiler.background", mesh); mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); @@ -190,34 +188,33 @@ protected void initialize( Application app ) { mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); background.setMaterial(mat); background.setLocalTranslation(0, 300, -1); - background.setLocalScale(1, scale, 1); - + background.setLocalScale(1, scale, 1); + refreshBackground(); - - InputManager inputManager = app.getInputManager(); - if( inputManager != null ) { + + InputManager inputManager = app.getInputManager(); + if (inputManager != null) { inputManager.addMapping(INPUT_MAPPING_PROFILER_TOGGLE, new KeyTrigger(KeyInput.KEY_F6)); - inputManager.addListener(keyListener, INPUT_MAPPING_PROFILER_TOGGLE); - } + inputManager.addListener(keyListener, INPUT_MAPPING_PROFILER_TOGGLE); + } } @Override - protected void cleanup( Application app ) { - InputManager inputManager = app.getInputManager(); - if( inputManager.hasMapping(INPUT_MAPPING_PROFILER_TOGGLE) ) { - inputManager.deleteMapping(INPUT_MAPPING_PROFILER_TOGGLE); + protected void cleanup(Application app) { + InputManager inputManager = app.getInputManager(); + if (inputManager.hasMapping(INPUT_MAPPING_PROFILER_TOGGLE)) { + inputManager.deleteMapping(INPUT_MAPPING_PROFILER_TOGGLE); } inputManager.removeListener(keyListener); } @Override protected void onEnable() { - // Set the number of visible frames to the current width of the screen setFrameCount(getApplication().getCamera().getWidth()); - + getApplication().setAppProfiler(profiler); - Node gui = ((SimpleApplication)getApplication()).getGuiNode(); + Node gui = ((SimpleApplication) getApplication()).getGuiNode(); gui.attachChild(graph); gui.attachChild(background); } @@ -228,9 +225,8 @@ protected void onDisable() { graph.removeFromParent(); background.removeFromParent(); } - - private class ProfilerKeyListener implements ActionListener { + private class ProfilerKeyListener implements ActionListener { @Override public void onAction(String name, boolean value, float tpf) { if (!value) { @@ -240,4 +236,3 @@ public void onAction(String name, boolean value, float tpf) { } } } - diff --git a/jme3-core/src/main/java/com/jme3/app/ChaseCameraAppState.java b/jme3-core/src/main/java/com/jme3/app/ChaseCameraAppState.java index 5c47a631cb..f4beacdf85 100644 --- a/jme3-core/src/main/java/com/jme3/app/ChaseCameraAppState.java +++ b/jme3-core/src/main/java/com/jme3/app/ChaseCameraAppState.java @@ -97,7 +97,7 @@ public void initialize(AppStateManager stateManager, Application app) { super.initialize(stateManager, app); this.inputManager = app.getInputManager(); target = new Node("ChaseCamTarget"); - camNode.setCamera(app.getCamera()); + camNode.setCamera(app.getCamera()); camNode.setControlDir(CameraControl.ControlDirection.SpatialToCamera); target.attachChild(camNode); camNode.setLocalTranslation(0, 0, distance); @@ -281,7 +281,7 @@ public float getMaxDistance() { */ public void setMaxDistance(float maxDistance) { this.maxDistance = maxDistance; - if(initialized){ + if (initialized) { zoomCamera(distance); } } @@ -297,13 +297,13 @@ public float getMinDistance() { /** * Sets the min zoom distance of the camera (default is 1) - * + * * @param minDistance the desired minimum distance (in world units, * default=1) */ public void setMinDistance(float minDistance) { this.minDistance = minDistance; - if(initialized){ + if (initialized) { zoomCamera(distance); } } @@ -325,7 +325,7 @@ public float getMaxVerticalRotation() { */ public void setMaxVerticalRotation(float maxVerticalRotation) { this.maxVerticalRotation = maxVerticalRotation; - if(initialized){ + if (initialized) { rotateCamera(); } } @@ -347,7 +347,7 @@ public float getMinVerticalRotation() { */ public void setMinVerticalRotation(float minHeight) { this.minVerticalRotation = minHeight; - if(initialized){ + if (initialized) { rotateCamera(); } } @@ -438,7 +438,7 @@ public boolean isDragToRotate() { public void setDragToRotate(boolean dragToRotate) { this.dragToRotate = dragToRotate; this.canRotate = !dragToRotate; - if(inputManager != null){ + if (inputManager != null) { inputManager.setCursorVisible(dragToRotate); } } diff --git a/jme3-core/src/main/java/com/jme3/app/FlyCamAppState.java b/jme3-core/src/main/java/com/jme3/app/FlyCamAppState.java index 11d3e3fa29..d8a834b877 100644 --- a/jme3-core/src/main/java/com/jme3/app/FlyCamAppState.java +++ b/jme3-core/src/main/java/com/jme3/app/FlyCamAppState.java @@ -35,11 +35,10 @@ import com.jme3.app.state.AppStateManager; import com.jme3.input.FlyByCamera; - /** - * Manages a FlyByCamera. + * Manages a FlyByCamera. * - * @author Paul Speed + * @author Paul Speed */ public class FlyCamAppState extends AbstractAppState { @@ -47,15 +46,15 @@ public class FlyCamAppState extends AbstractAppState { private FlyByCamera flyCam; public FlyCamAppState() { - } + } /** - * This is called by SimpleApplication during initialize(). + * This is called by SimpleApplication during initialize(). */ - void setCamera( FlyByCamera cam ) { + void setCamera(FlyByCamera cam) { this.flyCam = cam; } - + public FlyByCamera getCamera() { return flyCam; } @@ -63,34 +62,31 @@ public FlyByCamera getCamera() { @Override public void initialize(AppStateManager stateManager, Application app) { super.initialize(stateManager, app); - + this.app = app; if (app.getInputManager() != null) { - + if (flyCam == null) { flyCam = new FlyByCamera(app.getCamera()); } - - flyCam.registerWithInput(app.getInputManager()); - } + + flyCam.registerWithInput(app.getInputManager()); + } } - + @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); - flyCam.setEnabled(enabled); } - + @Override public void cleanup() { super.cleanup(); - if (app.getInputManager() != null) { + if (app.getInputManager() != null) { flyCam.unregisterInput(); - } + } } - - } diff --git a/jme3-core/src/main/java/com/jme3/app/LegacyApplication.java b/jme3-core/src/main/java/com/jme3/app/LegacyApplication.java index a450a705e7..f48fac73a5 100644 --- a/jme3-core/src/main/java/com/jme3/app/LegacyApplication.java +++ b/jme3-core/src/main/java/com/jme3/app/LegacyApplication.java @@ -102,7 +102,7 @@ public class LegacyApplication implements Application, SystemListener { * Create a new instance of LegacyApplication. */ public LegacyApplication() { - this((AppState[])null); + this((AppState[]) null); } /** @@ -111,7 +111,7 @@ public LegacyApplication() { * * @param initialStates app states to pre-attach, or null for none */ - public LegacyApplication( AppState... initialStates ) { + public LegacyApplication(AppState... initialStates) { initStateManager(); if (initialStates != null) { @@ -187,20 +187,20 @@ public void setPauseOnLostFocus(boolean pauseOnLostFocus) { } @Deprecated - public void setAssetManager(AssetManager assetManager){ + public void setAssetManager(AssetManager assetManager) { if (this.assetManager != null) throw new IllegalStateException("Can only set asset manager" - + " before initialization."); + + " before initialization."); this.assetManager = assetManager; } - private void initAssetManager(){ + private void initAssetManager() { URL assetCfgUrl = null; - if (settings != null){ + if (settings != null) { String assetCfg = settings.getString("AssetConfigURL"); - if (assetCfg != null){ + if (assetCfg != null) { try { assetCfgUrl = new URL(assetCfg); } catch (MalformedURLException ex) { @@ -217,7 +217,7 @@ private void initAssetManager(){ if (assetCfgUrl == null) { assetCfgUrl = JmeSystem.getPlatformAssetConfigURL(); } - if (assetManager == null){ + if (assetManager == null) { assetManager = JmeSystem.newAssetManager(assetCfgUrl); } } @@ -233,18 +233,18 @@ private void initAssetManager(){ * @param settings The settings to set. */ @Override - public void setSettings(AppSettings settings){ + public void setSettings(AppSettings settings) { this.settings = settings; - if (context != null && settings.useInput() != inputEnabled){ + if (context != null && settings.useInput() != inputEnabled) { // may need to create or destroy input based // on settings change inputEnabled = !inputEnabled; - if (inputEnabled){ + if (inputEnabled) { initInput(); - }else{ + } else { destroyInput(); } - }else{ + } else { inputEnabled = settings.useInput(); } } @@ -255,7 +255,7 @@ public void setSettings(AppSettings settings){ * by the current JmeContext implementation. */ @Override - public void setTimer(Timer timer){ + public void setTimer(Timer timer) { this.timer = timer; if (timer != null) { @@ -268,11 +268,11 @@ public void setTimer(Timer timer){ } @Override - public Timer getTimer(){ + public Timer getTimer() { return timer; } - private void initDisplay(){ + private void initDisplay() { // acquire important objects // from the context settings = context.getSettings(); @@ -285,8 +285,8 @@ private void initDisplay(){ renderer = context.getRenderer(); } - private void initAudio(){ - if (settings.getAudioRenderer() != null && context.getType() != Type.Headless){ + private void initAudio() { + if (settings.getAudioRenderer() != null && context.getType() != Type.Headless) { audioRenderer = JmeSystem.newAudioRenderer(settings); audioRenderer.initialize(); AudioContext.setAudioRenderer(audioRenderer); @@ -301,10 +301,10 @@ private void initAudio(){ * projection with 45° field of view, with near and far values 1 and 1000 * units respectively. */ - private void initCamera(){ + private void initCamera() { cam = new Camera(settings.getWidth(), settings.getHeight()); - cam.setFrustumPerspective(45f, (float)cam.getWidth() / cam.getHeight(), 1f, 1000f); + cam.setFrustumPerspective(45f, (float) cam.getWidth() / cam.getHeight(), 1f, 1000f); cam.setLocation(new Vector3f(0f, 0f, 10f)); cam.lookAt(new Vector3f(0f, 0f, 0f), Vector3f.UNIT_Y); @@ -330,7 +330,7 @@ private void initCamera(){ * initializes joystick input if joysticks are enabled in the * AppSettings. */ - private void initInput(){ + private void initInput() { mouseInput = context.getMouseInput(); if (mouseInput != null) mouseInput.initialize(); @@ -343,7 +343,7 @@ private void initInput(){ if (touchInput != null) touchInput.initialize(); - if (!settings.getBoolean("DisableJoysticks")){ + if (!settings.getBoolean("DisableJoysticks")) { joyInput = context.getJoyInput(); if (joyInput != null) joyInput.initialize(); @@ -352,7 +352,7 @@ private void initInput(){ inputManager = new InputManager(mouseInput, keyInput, joyInput, touchInput); } - private void initStateManager(){ + private void initStateManager() { stateManager = new AppStateManager(this); // Always register a ResetStatsState to make sure @@ -364,7 +364,7 @@ private void initStateManager(){ * @return The {@link AssetManager asset manager} for this application. */ @Override - public AssetManager getAssetManager(){ + public AssetManager getAssetManager() { return assetManager; } @@ -372,7 +372,7 @@ public AssetManager getAssetManager(){ * @return the {@link InputManager input manager}. */ @Override - public InputManager getInputManager(){ + public InputManager getInputManager() { return inputManager; } @@ -396,7 +396,7 @@ public RenderManager getRenderManager() { * @return The {@link Renderer renderer} for the application */ @Override - public Renderer getRenderer(){ + public Renderer getRenderer() { return renderer; } @@ -420,7 +420,7 @@ public Listener getListener() { * @return The {@link JmeContext display context} for the application */ @Override - public JmeContext getContext(){ + public JmeContext getContext() { return context; } @@ -428,7 +428,7 @@ public JmeContext getContext(){ * @return The {@link Camera camera} for the application */ @Override - public Camera getCamera(){ + public Camera getCamera() { return cam; } @@ -438,7 +438,7 @@ public Camera getCamera(){ * @see #start(com.jme3.system.JmeContext.Type) */ @Override - public void start(){ + public void start() { start(JmeContext.Type.Display, false); } @@ -450,7 +450,7 @@ public void start(){ * @see #start(com.jme3.system.JmeContext.Type) */ @Override - public void start(boolean waitFor){ + public void start(boolean waitFor) { start(JmeContext.Type.Display, waitFor); } @@ -474,13 +474,13 @@ public void start(JmeContext.Type contextType) { * @param waitFor true→wait for the context to be initialized, * false→don't wait */ - public void start(JmeContext.Type contextType, boolean waitFor){ - if (context != null && context.isCreated()){ + public void start(JmeContext.Type contextType, boolean waitFor) { + if (context != null && context.isCreated()) { logger.warning("start() called when application already created!"); return; } - if (settings == null){ + if (settings == null) { settings = new AppSettings(true); } @@ -494,7 +494,7 @@ public void start(JmeContext.Type contextType, boolean waitFor){ * Sets an AppProfiler hook that will be called back for * specific steps within a single update frame. Value defaults * to null. - * + * * @param prof the profiler to use (alias created) or null for none */ @Override @@ -527,13 +527,13 @@ public AppProfiler getAppProfiler() { * * @see Type#Canvas */ - public void createCanvas(){ - if (context != null && context.isCreated()){ + public void createCanvas() { + if (context != null && context.isCreated()) { logger.warning("createCanvas() called when application already created!"); return; } - if (settings == null){ + if (settings == null) { settings = new AppSettings(true); } @@ -551,7 +551,7 @@ public void createCanvas(){ * * @see #startCanvas(boolean) */ - public void startCanvas(){ + public void startCanvas() { startCanvas(false); } @@ -564,7 +564,7 @@ public void startCanvas(){ * @param waitFor If true, the current thread will block until the * rendering thread is running */ - public void startCanvas(boolean waitFor){ + public void startCanvas(boolean waitFor) { context.create(waitFor); } @@ -572,7 +572,7 @@ public void startCanvas(boolean waitFor){ * Internal use only. */ @Override - public void reshape(int w, int h){ + public void reshape(int w, int h) { if (renderManager != null) { renderManager.notifyReshape(w, h); } @@ -586,7 +586,7 @@ public void reshape(int w, int h){ * to restart, applying the new settings. */ @Override - public void restart(){ + public void restart() { context.setSettings(settings); context.restart(); } @@ -600,7 +600,7 @@ public void restart(){ * @see #stop(boolean) */ @Override - public void stop(){ + public void stop() { stop(false); } @@ -613,7 +613,7 @@ public void stop(){ * true→don't wait */ @Override - public void stop(boolean waitFor){ + public void stop(boolean waitFor) { logger.log(Level.FINE, "Closing application: {0}", getClass().getName()); context.destroy(waitFor); } @@ -629,15 +629,15 @@ public void stop(boolean waitFor){ * and far values 1 and 1000 units respectively. */ @Override - public void initialize(){ - if (assetManager == null){ + public void initialize() { + if (assetManager == null) { initAssetManager(); } initDisplay(); initCamera(); - if (inputEnabled){ + if (inputEnabled) { initInput(); } initAudio(); @@ -653,14 +653,14 @@ public void initialize(){ * Internal use only. */ @Override - public void handleError(String errMsg, Throwable t){ + public void handleError(String errMsg, Throwable t) { // Print error to log. logger.log(Level.SEVERE, errMsg, t); // Display error message on screen if not in headless mode if (context.getType() != JmeContext.Type.Headless) { if (t != null) { - JmeSystem.showErrorDialog(errMsg + "\n" + t.getClass().getSimpleName() + - (t.getMessage() != null ? ": " + t.getMessage() : "")); + JmeSystem.showErrorDialog(errMsg + "\n" + t.getClass().getSimpleName() + + (t.getMessage() != null ? ": " + t.getMessage() : "")); } else { JmeSystem.showErrorDialog(errMsg); } @@ -673,7 +673,7 @@ public void handleError(String errMsg, Throwable t){ * Internal use only. */ @Override - public void gainFocus(){ + public void gainFocus() { if (lostFocusBehavior != LostFocusBehavior.Disabled) { if (lostFocusBehavior == LostFocusBehavior.PauseOnLostFocus) { paused = false; @@ -689,8 +689,8 @@ public void gainFocus(){ * Internal use only. */ @Override - public void loseFocus(){ - if (lostFocusBehavior != LostFocusBehavior.Disabled){ + public void loseFocus() { + if (lostFocusBehavior != LostFocusBehavior.Disabled) { if (lostFocusBehavior == LostFocusBehavior.PauseOnLostFocus) { paused = true; } @@ -702,7 +702,7 @@ public void loseFocus(){ * Internal use only. */ @Override - public void requestClose(boolean esc){ + public void requestClose(boolean esc) { context.destroy(false); } @@ -737,7 +737,7 @@ public Future enqueue(Callable callable) { */ @Override @SuppressWarnings("unchecked") - public void enqueue(Runnable runnable){ + public void enqueue(Runnable runnable) { enqueue(new RunnableWrapper(runnable)); } @@ -746,7 +746,7 @@ public void enqueue(Runnable runnable){ */ protected void runQueuedTasks() { AppTask task; - while( (task = taskQueue.poll()) != null ) { + while ((task = taskQueue.poll()) != null) { if (!task.isCancelled()) { task.invoke(); } @@ -758,11 +758,12 @@ protected void runQueuedTasks() { * Callback from ContextListener. */ @Override - public void update(){ + public void update() { // Make sure the audio renderer is available to callables AudioContext.setAudioRenderer(audioRenderer); - if (prof!=null) prof.appStep(AppStep.QueuedTasks); + if (prof != null) + prof.appStep(AppStep.QueuedTasks); runQueuedTasks(); if (speed == 0 || paused) @@ -770,20 +771,22 @@ public void update(){ timer.update(); - if (inputEnabled){ - if (prof!=null) prof.appStep(AppStep.ProcessInput); + if (inputEnabled) { + if (prof != null) + prof.appStep(AppStep.ProcessInput); inputManager.update(timer.getTimePerFrame()); } - if (audioRenderer != null){ - if (prof!=null) prof.appStep(AppStep.ProcessAudio); + if (audioRenderer != null) { + if (prof != null) + prof.appStep(AppStep.ProcessAudio); audioRenderer.update(timer.getTimePerFrame()); } // user code here } - protected void destroyInput(){ + protected void destroyInput() { if (mouseInput != null) mouseInput.destroy(); @@ -804,7 +807,7 @@ protected void destroyInput(){ * Callback from ContextListener. */ @Override - public void destroy(){ + public void destroy() { stateManager.cleanup(); destroyInput(); @@ -828,19 +831,17 @@ public ViewPort getViewPort() { return viewPort; } - private class RunnableWrapper implements Callable{ + private class RunnableWrapper implements Callable { private final Runnable runnable; - public RunnableWrapper(Runnable runnable){ + public RunnableWrapper(Runnable runnable) { this.runnable = runnable; } @Override - public Object call(){ + public Object call() { runnable.run(); return null; } - } - } diff --git a/jme3-core/src/main/java/com/jme3/app/SimpleApplication.java b/jme3-core/src/main/java/com/jme3/app/SimpleApplication.java index e1526f890e..f483133087 100644 --- a/jme3-core/src/main/java/com/jme3/app/SimpleApplication.java +++ b/jme3-core/src/main/java/com/jme3/app/SimpleApplication.java @@ -61,7 +61,7 @@ * M - Display memory usage in the console.
* * A {@link com.jme3.app.FlyCamAppState} is by default attached as well and can - * be removed by calling stateManager.detach( stateManager.getState(FlyCamAppState.class) ); + * be removed by calling stateManager.detach(stateManager.getState(FlyCamAppState.class)); */ public abstract class SimpleApplication extends LegacyApplication { @@ -88,7 +88,7 @@ public void onAction(String name, boolean value, float tpf) { if (name.equals(INPUT_MAPPING_EXIT)) { stop(); - }else if (name.equals(INPUT_MAPPING_HIDE_STATS)){ + } else if (name.equals(INPUT_MAPPING_HIDE_STATS)) { if (stateManager.getState(StatsAppState.class) != null) { stateManager.getState(StatsAppState.class).toggleStats(); } @@ -98,10 +98,10 @@ public void onAction(String name, boolean value, float tpf) { public SimpleApplication() { this(new StatsAppState(), new FlyCamAppState(), new AudioListenerState(), new DebugKeysAppState(), - new ConstantVerifierState()); + new ConstantVerifierState()); } - public SimpleApplication( AppState... initialStates ) { + public SimpleApplication(AppState... initialStates) { super(initialStates); } @@ -125,7 +125,7 @@ public void start() { setSettings(settings); super.start(); } - + /** * Returns the applications speed. * @@ -134,7 +134,7 @@ public void start() { public float getSpeed() { return speed; } - + /** * Changes the application speed. 0.0f prevents the application from updating. * @param speed The speed to set. @@ -186,7 +186,7 @@ public void setShowSettings(boolean showSettings) { /** * Creates the font that will be set to the guiFont field * and subsequently set as the font for the stats text. - * + * * @return the loaded BitmapFont */ protected BitmapFont loadGuiFont() { @@ -214,7 +214,7 @@ public void initialize() { if (stateManager.getState(FlyCamAppState.class) != null) { flyCam = new FlyByCamera(cam); flyCam.setMoveSpeed(1f); // odd to set this here but it did it before - stateManager.getState(FlyCamAppState.class).setCamera( flyCam ); + stateManager.getState(FlyCamAppState.class).setCamera(flyCam); } if (context.getType() == Type.Display) { @@ -242,7 +242,8 @@ public void initialize() { @Override public void update() { - if (prof!=null) prof.appStep(AppStep.BeginFrame); + if (prof != null) + prof.appStep(AppStep.BeginFrame); super.update(); // makes sure to execute AppTasks if (speed == 0 || paused) { @@ -252,13 +253,15 @@ public void update() { float tpf = timer.getTimePerFrame() * speed; // update states - if (prof!=null) prof.appStep(AppStep.StateManagerUpdate); + if (prof != null) + prof.appStep(AppStep.StateManagerUpdate); stateManager.update(tpf); // simple update and root node simpleUpdate(tpf); - if (prof!=null) prof.appStep(AppStep.SpatialUpdate); + if (prof != null) + prof.appStep(AppStep.SpatialUpdate); rootNode.updateLogicalState(tpf); guiNode.updateLogicalState(tpf); @@ -266,15 +269,18 @@ public void update() { guiNode.updateGeometricState(); // render states - if (prof!=null) prof.appStep(AppStep.StateManagerRender); + if (prof != null) + prof.appStep(AppStep.StateManagerRender); stateManager.render(renderManager); - if (prof!=null) prof.appStep(AppStep.RenderFrame); + if (prof != null) + prof.appStep(AppStep.RenderFrame); renderManager.render(tpf, context.isRenderable()); simpleRender(renderManager); stateManager.postRender(); - if (prof!=null) prof.appStep(AppStep.EndFrame); + if (prof != null) + prof.appStep(AppStep.EndFrame); } public void setDisplayFps(boolean show) { diff --git a/jme3-core/src/main/java/com/jme3/app/StatsAppState.java b/jme3-core/src/main/java/com/jme3/app/StatsAppState.java index ded710c069..52a2939143 100644 --- a/jme3-core/src/main/java/com/jme3/app/StatsAppState.java +++ b/jme3-core/src/main/java/com/jme3/app/StatsAppState.java @@ -43,12 +43,11 @@ import com.jme3.scene.Spatial.CullHint; import com.jme3.scene.shape.Quad; - /** * Displays stats in SimpleApplication's GUI node or * using the node and font parameters provided. * - * @author Paul Speed + * @author Paul Speed */ public class StatsAppState extends AbstractAppState { @@ -70,7 +69,7 @@ public class StatsAppState extends AbstractAppState { public StatsAppState() { } - public StatsAppState( Node guiNode, BitmapFont guiFont ) { + public StatsAppState(Node guiNode, BitmapFont guiFont) { this.guiNode = guiNode; this.guiFont = guiFont; } @@ -80,10 +79,10 @@ public StatsAppState( Node guiNode, BitmapFont guiFont ) { * so that the fpsText can be created before init. This * is because several applications expect to directly access * fpsText... unfortunately. - * + * * @param guiFont the desired font (not null, alias created) */ - public void setFont( BitmapFont guiFont ) { + public void setFont(BitmapFont guiFont) { this.guiFont = guiFont; this.fpsText = new BitmapText(guiFont); } @@ -101,8 +100,8 @@ public float getSecondCounter() { } public void toggleStats() { - setDisplayFps( !showFps ); - setDisplayStatView( !showStats ); + setDisplayFps(!showFps); + setDisplayStatView(!showStats); } public void setDisplayFps(boolean show) { @@ -118,7 +117,7 @@ public void setDisplayFps(boolean show) { public void setDisplayStatView(boolean show) { showStats = show; - if (statsView != null ) { + if (statsView != null) { statsView.setEnabled(show); statsView.setCullHint(show ? CullHint.Never : CullHint.Always); if (darkenStats != null) { @@ -142,17 +141,17 @@ public void initialize(AppStateManager stateManager, Application app) { this.app = app; if (app instanceof SimpleApplication) { - SimpleApplication simpleApp = (SimpleApplication)app; + SimpleApplication simpleApp = (SimpleApplication) app; if (guiNode == null) { guiNode = simpleApp.guiNode; } - if (guiFont == null ) { + if (guiFont == null) { guiFont = simpleApp.guiFont; } } if (guiNode == null) { - throw new RuntimeException( "No guiNode specific and cannot be automatically determined." ); + throw new RuntimeException("No guiNode specific and cannot be automatically determined."); } if (guiFont == null) { @@ -187,8 +186,8 @@ public void loadFpsText() { */ public void loadStatsView() { statsView = new StatsView("Statistics View", - app.getAssetManager(), - app.getRenderer().getStatistics()); + app.getAssetManager(), + app.getRenderer().getStatistics()); // move it up so it appears above fps text statsView.setLocalTranslation(0, fpsText.getLineHeight(), 0); statsView.setEnabled(showStats); @@ -198,7 +197,7 @@ public void loadStatsView() { public void loadDarken() { Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); - mat.setColor("Color", new ColorRGBA(0,0,0,0.5f)); + mat.setColor("Color", new ColorRGBA(0, 0, 0, 0.5f)); mat.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); darkenFps = new Geometry("StatsDarken", new Quad(200, fpsText.getLineHeight())); @@ -237,7 +236,7 @@ public void setEnabled(boolean enabled) { public void update(float tpf) { if (showFps) { secondCounter += app.getTimer().getTimePerFrame(); - frameCounter ++; + frameCounter++; if (secondCounter >= 1.0f) { int fps = (int) (frameCounter / secondCounter); fpsText.setText("Frames per second: " + fps); @@ -256,6 +255,4 @@ public void cleanup() { guiNode.detachChild(darkenFps); guiNode.detachChild(darkenStats); } - - } diff --git a/jme3-core/src/main/java/com/jme3/app/StatsView.java b/jme3-core/src/main/java/com/jme3/app/StatsView.java index 2ebba3b744..f6b28fb642 100644 --- a/jme3-core/src/main/java/com/jme3/app/StatsView.java +++ b/jme3-core/src/main/java/com/jme3/app/StatsView.java @@ -60,7 +60,6 @@ * */ public class StatsView extends Node implements Control, JmeCloneable { - final private BitmapText statText; final private Statistics statistics; @@ -71,7 +70,7 @@ public class StatsView extends Node implements Control, JmeCloneable { private final StringBuilder stringBuilder = new StringBuilder(); - public StatsView(String name, AssetManager manager, Statistics stats){ + public StatsView(String name, AssetManager manager, Statistics stats) { super(name); setQueueBucket(Bucket.Gui); @@ -97,7 +96,6 @@ public float getHeight() { @Override public void update(float tpf) { - if (!isEnabled()) return; @@ -122,14 +120,14 @@ public void update(float tpf) { public Control cloneForSpatial(Spatial spatial) { throw new UnsupportedOperationException(); } - + @Override public StatsView jmeClone() { throw new UnsupportedOperationException("Not yet implemented."); } @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { throw new UnsupportedOperationException("Not yet implemented."); } @@ -149,5 +147,4 @@ public boolean isEnabled() { @Override public void render(RenderManager rm, ViewPort vp) { } - } diff --git a/jme3-core/src/main/java/com/jme3/app/state/AbstractAppState.java b/jme3-core/src/main/java/com/jme3/app/state/AbstractAppState.java index 4f4b4a2bfe..4d0e8606d2 100644 --- a/jme3-core/src/main/java/com/jme3/app/state/AbstractAppState.java +++ b/jme3-core/src/main/java/com/jme3/app/state/AbstractAppState.java @@ -51,11 +51,11 @@ public abstract class AbstractAppState implements AppState { protected boolean initialized = false; private boolean enabled = true; private String id; - - protected AbstractAppState() { + + protected AbstractAppState() { } - - protected AbstractAppState( String id ) { + + protected AbstractAppState(String id) { this.id = id; } @@ -76,7 +76,7 @@ public boolean isInitialized() { * * @param id the desired ID */ - protected void setId( String id ) { + protected void setId(String id) { this.id = id; } @@ -89,7 +89,7 @@ public String getId() { public void setEnabled(boolean enabled) { this.enabled = enabled; } - + @Override public boolean isEnabled() { return enabled; @@ -112,12 +112,11 @@ public void render(RenderManager rm) { } @Override - public void postRender(){ + public void postRender() { } @Override public void cleanup() { initialized = false; } - } diff --git a/jme3-core/src/main/java/com/jme3/app/state/AppStateManager.java b/jme3-core/src/main/java/com/jme3/app/state/AppStateManager.java index 03d24d19db..3a86894765 100644 --- a/jme3-core/src/main/java/com/jme3/app/state/AppStateManager.java +++ b/jme3-core/src/main/java/com/jme3/app/state/AppStateManager.java @@ -30,7 +30,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.app.state; - + import com.jme3.app.Application; import com.jme3.renderer.RenderManager; import com.jme3.util.SafeArrayList; @@ -58,29 +58,28 @@ * render thread and it is not necessarily safe to modify * the scene graph, etc.. *
  • cleanup() : called ONCE on the render thread at the beginning of the next update - * after the state has been detached or when the application is - * terminating. - * + * after the state has been detached or when the application is + * terminating. + * * * @author Kirill Vainer, Paul Speed */ public class AppStateManager { - /** * List holding the attached app states that are pending * initialization. Once initialized they will be added to - * the running app states. + * the running app states. */ private final SafeArrayList initializing = new SafeArrayList<>(AppState.class); - + /** - * Holds the active states once they are initialized. + * Holds the active states once they are initialized. */ private final SafeArrayList states = new SafeArrayList<>(AppState.class); - + /** * List holding the detached app states that are pending - * cleanup. + * cleanup. */ private final SafeArrayList terminating = new SafeArrayList<>(AppState.class); @@ -89,20 +88,20 @@ public class AppStateManager { * an ID. */ private final ConcurrentMap stateIndex = new ConcurrentHashMap<>(); - + // All of the above lists need to be thread-safe, but access will be // synchronized separately.... but always on the states list. This // is to avoid deadlocking. Anyway, the most common use case // is that they are all modified from the same thread. - + private final Application app; - public AppStateManager(Application app){ + public AppStateManager(Application app) { this.app = app; } /** - * Returns the Application to which this AppStateManager belongs. + * Returns the Application to which this AppStateManager belongs. * * @return the pre-existing instance */ @@ -110,41 +109,41 @@ public Application getApplication() { return app; } - protected AppState[] getInitializing() { - synchronized (states){ + protected AppState[] getInitializing() { + synchronized (states) { return initializing.getArray(); } - } + } - protected AppState[] getTerminating() { - synchronized (states){ + protected AppState[] getTerminating() { + synchronized (states) { return terminating.getArray(); } - } + } - protected AppState[] getStates(){ - synchronized (states){ + protected AppState[] getStates() { + synchronized (states) { return states.getArray(); } } /** * Attach a state to the AppStateManager, the same state cannot be attached - * twice. Throws an IllegalArgumentException if the state has an ID and that - * ID has already been associated with another AppState. + * twice. Throws an IllegalArgumentException if the state has an ID and that + * ID has already been associated with another AppState. * * @param state The state to attach * @return True if the state was successfully attached, false if the state * was already attached. */ - public boolean attach(AppState state){ - synchronized (states){ - if( state.getId() != null && stateIndex.putIfAbsent(state.getId(), state) != null ) { - throw new IllegalArgumentException("ID:" + state.getId() - + " is already being used by another state:" + public boolean attach(AppState state) { + synchronized (states) { + if (state.getId() != null && stateIndex.putIfAbsent(state.getId(), state) != null) { + throw new IllegalArgumentException("ID:" + state.getId() + + " is already being used by another state:" + stateIndex.get(state.getId())); } - if (!states.contains(state) && !initializing.contains(state)){ + if (!states.contains(state) && !initializing.contains(state)) { state.stateAttached(this); initializing.add(state); return true; @@ -161,7 +160,7 @@ public boolean attach(AppState state){ * * @param states The states to attach */ - public void attachAll(AppState... states){ + public void attachAll(AppState... states) { attachAll(Arrays.asList(states)); } @@ -172,39 +171,39 @@ public void attachAll(AppState... states){ * * @param states The states to attach */ - public void attachAll(Iterable states){ - synchronized (this.states){ - for( AppState state : states ) { + public void attachAll(Iterable states) { + synchronized (this.states) { + for (AppState state : states) { attach(state); } } } /** - * Detaches the state from the AppStateManager. + * Detaches the state from the AppStateManager. * * @param state The state to detach * @return True if the state was detached successfully, false - * if the state was not attached in the first place. + * if the state was not attached in the first place. */ - public boolean detach(AppState state){ - synchronized (states){ - + public boolean detach(AppState state) { + synchronized (states) { + // Remove it from the index if it exists. // Note: we remove it directly from the values() in case // the state has changed its ID since registered. stateIndex.values().remove(state); - - if (states.contains(state)){ + + if (states.contains(state)) { state.stateDetached(this); states.remove(state); terminating.add(state); return true; - } else if(initializing.contains(state)){ + } else if (initializing.contains(state)) { state.stateDetached(this); initializing.remove(state); return true; - }else{ + } else { return false; } } @@ -215,11 +214,11 @@ public boolean detach(AppState state){ * * @param state The state to check * @return True if the state is currently attached to this AppStateManager. - * + * * @see AppStateManager#attach(com.jme3.app.state.AppState) */ - public boolean hasState(AppState state){ - synchronized (states){ + public boolean hasState(AppState state) { + synchronized (states) { return states.contains(state) || initializing.contains(state); } } @@ -231,140 +230,140 @@ public boolean hasState(AppState state){ * @param stateClass the desired type of AppState * @return First attached state that is an instance of stateClass */ - public T getState(Class stateClass){ + public T getState(Class stateClass) { return getState(stateClass, false); } - + /** * Returns the first state that is an instance of subclass of the specified class. * * @param the desired type of AppState * @param stateClass the desired type of AppState * @param failOnMiss true to throw an exception, false to return null - * @return First attached state that is an instance of stateClass. If failOnMiss is true - * then an IllegalArgumentException is thrown if the state is not attached. + * @return First attached state that is an instance of stateClass. If failOnMiss is true + * then an IllegalArgumentException is thrown if the state is not attached. */ @SuppressWarnings("unchecked") - public T getState(Class stateClass, boolean failOnMiss){ - synchronized (states){ + public T getState(Class stateClass, boolean failOnMiss) { + synchronized (states) { AppState[] array = getStates(); for (AppState state : array) { - if (stateClass.isAssignableFrom(state.getClass())){ + if (stateClass.isAssignableFrom(state.getClass())) { return (T) state; } } - + // This may be more trouble than it's worth, but I think // it's necessary for proper decoupling of states and provides // similar behavior to before where a state could be looked // up even if it wasn't initialized. -pspeed array = getInitializing(); for (AppState state : array) { - if (stateClass.isAssignableFrom(state.getClass())){ + if (stateClass.isAssignableFrom(state.getClass())) { return (T) state; } } } - - if(failOnMiss) { + + if (failOnMiss) { throw new IllegalArgumentException("State not found for:" + stateClass); - } + } return null; } /** - * Returns the state associated with the specified ID at the time it was - * attached or null if not state was attached with that ID. + * Returns the state associated with the specified ID at the time it was + * attached or null if not state was attached with that ID. * * @param the desired type of AppState * @param id the AppState ID * @param stateClass the desired type of AppState * @return the pre-existing instance, or null if not found */ - public T getState( String id, Class stateClass ) { + public T getState(String id, Class stateClass) { return stateClass.cast(stateIndex.get(id)); } - + /** - * Returns true if there is currently a state associated with the specified - * ID. + * Returns true if there is currently a state associated with the specified + * ID. * * @param id the AppState ID * @return true if found, otherwise false */ - public boolean hasState( String id ) { + public boolean hasState(String id) { return stateIndex.containsKey(id); } - + /** * Returns the state associated with the specified ID at the time it - * was attached or throws an IllegalArgumentException if the ID was + * was attached or throws an IllegalArgumentException if the ID was * not found. * * @param the desired type of AppState * @param id the AppState ID * @param stateClass the desired type of AppState * @return the pre-existing instance (not null) - */ - public T stateForId( String id, Class stateClass ) { + */ + public T stateForId(String id, Class stateClass) { T result = getState(id, stateClass); - if( result == null ) { + if (result == null) { throw new IllegalArgumentException("State not found for:" + id); } return stateClass.cast(result); - } + } - protected void initializePending(){ + protected void initializePending() { AppState[] array = getInitializing(); if (array.length == 0) return; - - synchronized( states ) { + + synchronized (states) { // Move the states that will be initialized // into the active array. In all but one case the // order doesn't matter but if we do this here then // a state can detach itself in initialize(). If we // did it after then it couldn't. - List transfer = Arrays.asList(array); + List transfer = Arrays.asList(array); states.addAll(transfer); initializing.removeAll(transfer); - } + } for (AppState state : array) { state.initialize(this, app); } } - - protected void terminatePending(){ + + protected void terminatePending() { AppState[] array = getTerminating(); if (array.length == 0) return; - + for (AppState state : array) { state.cleanup(); - } - synchronized( states ) { + } + synchronized (states) { // Remove just the states that were terminated... // which might now be a subset of the total terminating // list. - terminating.removeAll(Arrays.asList(array)); + terminating.removeAll(Arrays.asList(array)); } - } + } /** * Calls update for attached states, do not call directly. * @param tpf Time per frame. */ - public void update(float tpf){ - + public void update(float tpf) { + // Cleanup any states pending terminatePending(); // Initialize any states pending initializePending(); - // Update enabled states + // Update enabled states AppState[] array = getStates(); - for (AppState state : array){ + for (AppState state : array) { if (state.isEnabled()) { if (app.getAppProfiler() != null) { app.getAppProfiler().appSubStep(state.getClass().getSimpleName()); @@ -378,9 +377,9 @@ public void update(float tpf){ * Calls render for all attached and initialized states, do not call directly. * @param rm The RenderManager */ - public void render(RenderManager rm){ + public void render(RenderManager rm) { AppState[] array = getStates(); - for (AppState state : array){ + for (AppState state : array) { if (state.isEnabled()) { if (app.getAppProfiler() != null) { app.getAppProfiler().appSubStep(state.getClass().getSimpleName()); @@ -393,9 +392,9 @@ public void render(RenderManager rm){ /** * Calls render for all attached and initialized states, do not call directly. */ - public void postRender(){ + public void postRender() { AppState[] array = getStates(); - for (AppState state : array){ + for (AppState state : array) { if (state.isEnabled()) { if (app.getAppProfiler() != null) { app.getAppProfiler().appSubStep(state.getClass().getSimpleName()); @@ -408,10 +407,10 @@ public void postRender(){ /** * Calls cleanup on attached states, do not call directly. */ - public void cleanup(){ + public void cleanup() { AppState[] array = getStates(); - for (AppState state : array){ + for (AppState state : array) { state.cleanup(); } - } + } } diff --git a/jme3-core/src/main/java/com/jme3/app/state/BaseAppState.java b/jme3-core/src/main/java/com/jme3/app/state/BaseAppState.java index 625067f8fe..e172d4cd16 100644 --- a/jme3-core/src/main/java/com/jme3/app/state/BaseAppState.java +++ b/jme3-core/src/main/java/com/jme3/app/state/BaseAppState.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - + package com.jme3.app.state; import com.jme3.app.Application; @@ -37,8 +37,6 @@ import java.util.logging.Level; import java.util.logging.Logger; - - /** * A base app state implementation the provides more built-in * management convenience than AbstractAppState, including methods @@ -46,9 +44,9 @@ * The abstract onEnable() and onDisable() methods are called * appropriately during initialize(), cleanup(), or setEnabled() * depending on the mutual state of "initialized" and "enabled". - * + * *

    initialize() and cleanup() can be used by subclasses to - * manage resources that should exist the entire time that the + * manage resources that should exist the entire time that the * app state is attached. This is useful for resources that might * be expensive to create or load.

    * @@ -61,7 +59,7 @@ * will always be called after initialize() if the state is enable(). * onEnable()/onDisable() are also called appropriate when setEnabled() * is called that changes the enabled state AND if the state is attached. - * In other words, onEnable()/onDisable() are only ever called on an already + * In other words, onEnable()/onDisable() are only ever called on an already * attached state.

    * *

    It is technically safe to do all initialization and cleanup in @@ -72,7 +70,6 @@ * @author Paul Speed */ public abstract class BaseAppState implements AppState { - private static final Logger log = Logger.getLogger(BaseAppState.class.getName()); private Application app; @@ -82,8 +79,8 @@ public abstract class BaseAppState implements AppState { protected BaseAppState() { } - - protected BaseAppState( String id ) { + + protected BaseAppState(String id) { this.id = id; } @@ -92,8 +89,8 @@ protected BaseAppState( String id ) { * attached and before onEnable() is called. * @param app the application */ - protected abstract void initialize( Application app ); - + protected abstract void initialize(Application app); + /** * Called after the app state is detached or during * application shutdown if the state is still attached. @@ -101,15 +98,15 @@ protected BaseAppState( String id ) { * the state is enabled at the time of cleanup. * @param app the application */ - protected abstract void cleanup( Application app ); - + protected abstract void cleanup(Application app); + /** * Called when the state is fully enabled, ie: is attached * and isEnabled() is true or when the setEnabled() status * changes after the state is attached. */ protected abstract void onEnable(); - + /** * Called when the state was previously enabled but is * now disabled either because setEnabled(false) was called @@ -118,19 +115,19 @@ protected BaseAppState( String id ) { protected abstract void onDisable(); /** - * Do not call directly: Called by the state manager to initialize this + * Do not call directly: Called by the state manager to initialize this * state post-attachment. * This implementation calls initialize(app) and then onEnable() if the * state is enabled. */ @Override - public final void initialize( AppStateManager stateManager, Application app ) { + public final void initialize(AppStateManager stateManager, Application app) { log.log(Level.FINEST, "initialize():{0}", this); this.app = app; initialized = true; initialize(app); - if( isEnabled() ) { + if (isEnabled()) { log.log(Level.FINEST, "onEnable():{0}", this); onEnable(); } @@ -148,7 +145,7 @@ public final boolean isInitialized() { * * @param id the desired ID */ - protected void setId( String id ) { + protected void setId(String id) { this.id = id; } @@ -165,34 +162,33 @@ public final AppStateManager getStateManager() { return app.getStateManager(); } - public final T getState( Class type ) { - return getState( type, false ); + public final T getState(Class type) { + return getState(type, false); } - - public final T getState( Class type, boolean failOnMiss ) { - return getStateManager().getState( type, failOnMiss ); + + public final T getState(Class type, boolean failOnMiss) { + return getStateManager().getState(type, failOnMiss); } - public final T getState( String id, Class type ) { + public final T getState(String id, Class type) { return getState(id, type, false); } - - public final T getState( String id, Class type, boolean failOnMiss ) { - if( failOnMiss ) { + + public final T getState(String id, Class type, boolean failOnMiss) { + if (failOnMiss) { return getStateManager().stateForId(id, type); } return getStateManager().getState(id, type); } @Override - public final void setEnabled( boolean enabled ) - { - if( this.enabled == enabled ) + public final void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; this.enabled = enabled; - if( !isInitialized() ) + if (!isInitialized()) return; - if( enabled ) { + if (enabled) { log.log(Level.FINEST, "onEnable():{0}", this); onEnable(); } else { @@ -207,19 +203,19 @@ public final boolean isEnabled() { } @Override - public void stateAttached( AppStateManager stateManager ) { + public void stateAttached(AppStateManager stateManager) { } @Override - public void stateDetached( AppStateManager stateManager ) { + public void stateDetached(AppStateManager stateManager) { } @Override - public void update( float tpf ) { + public void update(float tpf) { } @Override - public void render( RenderManager rm ) { + public void render(RenderManager rm) { } @Override @@ -227,7 +223,7 @@ public void postRender() { } /** - * Do not call directly: Called by the state manager to terminate this + * Do not call directly: Called by the state manager to terminate this * state post-detachment or during state manager termination. * This implementation calls onDisable() if the state is enabled and * then cleanup(app). @@ -236,7 +232,7 @@ public void postRender() { public final void cleanup() { log.log(Level.FINEST, "cleanup():{0}", this); - if( isEnabled() ) { + if (isEnabled()) { log.log(Level.FINEST, "onDisable():{0}", this); onDisable(); } diff --git a/jme3-core/src/main/java/com/jme3/app/state/ConstantVerifierState.java b/jme3-core/src/main/java/com/jme3/app/state/ConstantVerifierState.java index ca55a44b4d..956818e3d5 100644 --- a/jme3-core/src/main/java/com/jme3/app/state/ConstantVerifierState.java +++ b/jme3-core/src/main/java/com/jme3/app/state/ConstantVerifierState.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - + package com.jme3.app.state; import java.util.Arrays; @@ -64,10 +64,13 @@ public class ConstantVerifierState extends BaseAppState { new Checker(Vector3f.UNIT_Y, new Vector3f(0, 1, 0)), new Checker(Vector3f.UNIT_Z, new Vector3f(0, 0, 1)), new Checker(Vector3f.UNIT_XYZ, new Vector3f(1, 1, 1)), - new Checker(Vector3f.POSITIVE_INFINITY, new Vector3f(POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY)), - new Checker(Vector3f.NEGATIVE_INFINITY, new Vector3f(NEGATIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_INFINITY)), + new Checker(Vector3f.POSITIVE_INFINITY, + new Vector3f(POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY)), + new Checker(Vector3f.NEGATIVE_INFINITY, + new Vector3f(NEGATIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_INFINITY)), new Checker(Quaternion.IDENTITY, new Quaternion()), - new Checker(Quaternion.DIRECTION_Z, new Quaternion().fromAxes(Vector3f.UNIT_X, Vector3f.UNIT_Y, Vector3f.UNIT_Z)), + new Checker(Quaternion.DIRECTION_Z, + new Quaternion().fromAxes(Vector3f.UNIT_X, Vector3f.UNIT_Y, Vector3f.UNIT_Z)), new Checker(Quaternion.ZERO, new Quaternion(0, 0, 0, 0)), new Checker(Vector2f.ZERO, new Vector2f(0f, 0f)), new Checker(Vector2f.UNIT_XY, new Vector2f(1f, 1f)), @@ -78,8 +81,10 @@ public class ConstantVerifierState extends BaseAppState { new Checker(Vector4f.UNIT_Z, new Vector4f(0, 0, 1, 0)), new Checker(Vector4f.UNIT_W, new Vector4f(0, 0, 0, 1)), new Checker(Vector4f.UNIT_XYZW, new Vector4f(1, 1, 1, 1)), - new Checker(Vector4f.POSITIVE_INFINITY, new Vector4f(POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY)), - new Checker(Vector4f.NEGATIVE_INFINITY, new Vector4f(NEGATIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_INFINITY)), + new Checker(Vector4f.POSITIVE_INFINITY, + new Vector4f(POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY, POSITIVE_INFINITY)), + new Checker(Vector4f.NEGATIVE_INFINITY, + new Vector4f(NEGATIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_INFINITY)), new Checker(Matrix3f.ZERO, new Matrix3f(0, 0, 0, 0, 0, 0, 0, 0, 0)), new Checker(Matrix3f.IDENTITY, new Matrix3f()), new Checker(Matrix4f.ZERO, new Matrix4f(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), @@ -96,112 +101,113 @@ public enum ErrorType { Assert, Exception, Log }; * constant checks using asserts. */ public ConstantVerifierState() { - this(ErrorType.Assert); + this(ErrorType.Assert); } - + /** * Creates a verifier app state that will check all of the default * constant checks using the specified error reporting mechanism. - * + * * @param errorType the mechanism to use */ - public ConstantVerifierState( ErrorType errorType ) { + public ConstantVerifierState(ErrorType errorType) { this(errorType, DEFAULT_CHECKS); } /** * Creates a verifier app state that will check all of the specified * checks and report errors using the specified error type. - * + * * @param errorType the mechanism to use * @param checkers which checks to perform */ - private ConstantVerifierState( ErrorType errorType, Checker... checkers ) { + private ConstantVerifierState(ErrorType errorType, Checker... checkers) { this.errorType = errorType; this.checkers.addAll(Arrays.asList(checkers)); } - - public void addChecker( Object constant, Object goodValue ) { + + public void addChecker(Object constant, Object goodValue) { checkers.add(new Checker(constant, goodValue)); } - - public void setErrorType( ErrorType errorType ) { + + public void setErrorType(ErrorType errorType) { this.errorType = errorType; } - + public ErrorType getErrorType() { return errorType; } - + @Override - protected void initialize( Application app ) { + protected void initialize(Application app) { } - + @Override - protected void cleanup( Application app ) { + protected void cleanup(Application app) { } - + @Override protected void onEnable() { } - + @Override protected void onDisable() { } - + @Override public void postRender() { // Check as late in the frame as possible. Subclasses can check earlier // if they like. checkValues(); } - + protected void checkValues() { - for( Checker checker : checkers.getArray() ) { - switch( errorType ) { + for (Checker checker : checkers.getArray()) { + switch (errorType) { default: case Assert: assert checker.isValid() : checker.toString(); break; case Exception: - if( !checker.isValid() ) { + if (!checker.isValid()) { throw new RuntimeException("Constant has changed, " + checker.toString()); } break; case Log: - if( !checker.isValid() ) { + if (!checker.isValid()) { log.severe("Constant has changed, " + checker.toString()); } break; } } } - + /** * Checks the specified 'constant' value against its known good * value. These should obviously be different instances for this to * mean anything. - */ + */ private static class Checker { private Object constant; private Object goodValue; - - public Checker( Object constant, Object goodValue ) { - if( constant == null ) { + + public Checker(Object constant, Object goodValue) { + if (constant == null) { throw new IllegalArgumentException("Constant cannot be null"); } - if( !constant.equals(goodValue) ) { - throw new IllegalArgumentException("Constant value:" + constant + " does not match value:" + goodValue); + if (!constant.equals(goodValue)) { + throw new IllegalArgumentException( + "Constant value:" + constant + " does not match value:" + goodValue); } this.constant = constant; this.goodValue = goodValue; } - + public boolean isValid() { return constant.equals(goodValue); } - - @Override + + @Override public String toString() { return "Constant:" + constant + ", correct value:" + goodValue + ", type:" + goodValue.getClass(); } diff --git a/jme3-core/src/main/java/com/jme3/app/state/RootNodeAppState.java b/jme3-core/src/main/java/com/jme3/app/state/RootNodeAppState.java index 4b0e6e42de..482dc098a6 100644 --- a/jme3-core/src/main/java/com/jme3/app/state/RootNodeAppState.java +++ b/jme3-core/src/main/java/com/jme3/app/state/RootNodeAppState.java @@ -93,7 +93,7 @@ public RootNodeAppState(ViewPort viewPort, Node rootNode) { * @param viewPort An existing ViewPort * @param rootNode An existing root Node */ - public RootNodeAppState( String id, ViewPort viewPort, Node rootNode ) { + public RootNodeAppState(String id, ViewPort viewPort, Node rootNode) { super(id); this.viewPort = viewPort; this.rootNode = rootNode; @@ -115,12 +115,12 @@ public void initialize(AppStateManager stateManager, Application app) { public void update(float tpf) { super.update(tpf); rootNode.updateLogicalState(tpf); - + // FIXME: I'm 99% sure that updateGeometricState() should be // called in render() so that it is done as late as possible. - // In complicated app state setups, cross-state chatter could - // cause nodes (or their children) to be updated after this - // app state's update has been called. -pspeed:2019-09-15 + // In complicated app state setups, cross-state chatter could + // cause nodes (or their children) to be updated after this + // app state's update has been called. -pspeed:2019-09-15 rootNode.updateGeometricState(); } diff --git a/jme3-core/src/main/java/com/jme3/app/state/ScreenshotAppState.java b/jme3-core/src/main/java/com/jme3/app/state/ScreenshotAppState.java index a8310a7afd..462971a91c 100644 --- a/jme3-core/src/main/java/com/jme3/app/state/ScreenshotAppState.java +++ b/jme3-core/src/main/java/com/jme3/app/state/ScreenshotAppState.java @@ -116,7 +116,7 @@ public ScreenshotAppState(String filePath, String fileName) { * default storage folder. * @param filePath The screenshot file path to use. Include the separator at the end of the path. * @param shotIndex The base index for screenshots. The first screenshot will have - * shotIndex + 1 appended, the next shotIndex + 2, and so on. + * shotIndex + 1 appended, the next shotIndex + 2, and so on. */ public ScreenshotAppState(String filePath, long shotIndex) { this.filePath = filePath; @@ -132,14 +132,14 @@ public ScreenshotAppState(String filePath, long shotIndex) { * @param filePath The screenshot file path to use. Include the separator at the end of the path. * @param fileName The name of the file to save the screenshot as. * @param shotIndex The base index for screenshots. The first screenshot will have - * shotIndex + 1 appended, the next shotIndex + 2, and so on. + * shotIndex + 1 appended, the next shotIndex + 2, and so on. */ public ScreenshotAppState(String filePath, String fileName, long shotIndex) { this.filePath = filePath; this.shotName = fileName; this.shotIndex = shotIndex; } - + /** * Set the file path to store the screenshot. * Include the separator at the end of the path. @@ -169,7 +169,7 @@ public void setShotIndex(long index) { } /** - * Sets if the filename should be appended with a number representing the + * Sets if the filename should be appended with a number representing the * current sequence. * @param numberedWanted If numbering is wanted. */ @@ -234,7 +234,7 @@ public void cleanup() { @Override public void onAction(String name, boolean value, float tpf) { - if (value){ + if (value) { capture = true; } } @@ -274,7 +274,7 @@ public void postQueue(RenderQueue rq) { @Override public void postFrame(FrameBuffer out) { - if (capture){ + if (capture) { capture = false; Camera curCamera = rm.getCurrentCamera(); @@ -310,7 +310,7 @@ public void postFrame(FrameBuffer out) { writeImageFile(file); } catch (IOException ex) { logger.log(Level.SEVERE, "Error while saving screenshot", ex); - } + } } } @@ -320,17 +320,17 @@ public void setProfiler(AppProfiler profiler) { } /** - * Called by postFrame() once the screen has been captured to outBuf. - * + * Called by postFrame() once the screen has been captured to outBuf. + * * @param file the output file * @throws IOException if an I/O error occurs */ - protected void writeImageFile( File file ) throws IOException { + protected void writeImageFile(File file) throws IOException { OutputStream outStream = new FileOutputStream(file); try { JmeSystem.writeImageFile(outStream, "png", outBuf, width, height); } finally { outStream.close(); } - } + } } diff --git a/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java b/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java index d33ca1b301..be2c834ea9 100644 --- a/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java +++ b/jme3-core/src/main/java/com/jme3/asset/AssetConfig.java @@ -54,9 +54,9 @@ public final class AssetConfig { private static final Logger logger = Logger.getLogger(AssetConfig.class.getName()); - + private AssetConfig() { } - + private static Class acquireClass(String name) { try { return Class.forName(name); @@ -64,24 +64,24 @@ private static Class acquireClass(String name) { return null; } } - + @SuppressWarnings("unchecked") - public static void loadText(AssetManager assetManager, URL configUrl) throws IOException{ + public static void loadText(AssetManager assetManager, URL configUrl) throws IOException { InputStream in = configUrl.openStream(); try { Scanner scan = new Scanner(in, "UTF-8"); scan.useLocale(Locale.US); // Fix commas / periods ?? - while (scan.hasNext()){ + while (scan.hasNext()) { String cmd = scan.next(); - if (cmd.equals("LOADER")){ + if (cmd.equals("LOADER")) { String loaderClass = scan.next(); String colon = scan.next(); - if (!colon.equals(":")){ - throw new IOException("Expected ':', got '"+colon+"'"); + if (!colon.equals(":")) { + throw new IOException("Expected ':', got '" + colon + "'"); } String extensionsList = scan.nextLine(); String[] extensions = extensionsList.split(","); - for (int i = 0; i < extensions.length; i++){ + for (int i = 0; i < extensions.length; i++) { extensions[i] = extensions[i].trim(); } Class clazz = acquireClass(loaderClass); @@ -115,7 +115,8 @@ public static void loadText(AssetManager assetManager, URL configUrl) throws IOE } } } finally { - if (in != null) in.close(); + if (in != null) + in.close(); } } } diff --git a/jme3-core/src/main/java/com/jme3/asset/AssetInfo.java b/jme3-core/src/main/java/com/jme3/asset/AssetInfo.java index 34cd8c5abc..6148e72dae 100644 --- a/jme3-core/src/main/java/com/jme3/asset/AssetInfo.java +++ b/jme3-core/src/main/java/com/jme3/asset/AssetInfo.java @@ -58,7 +58,7 @@ public AssetManager getManager() { } @Override - public String toString(){ + public String toString() { return getClass().getName() + "[" + "key=" + key + "]"; } @@ -68,9 +68,8 @@ public String toString(){ *

    * Each invocation of this method should return a new stream to the * asset data, starting at the beginning of the file. - * + * * @return The asset data. */ public abstract InputStream openStream(); - } diff --git a/jme3-core/src/main/java/com/jme3/asset/AssetKey.java b/jme3-core/src/main/java/com/jme3/asset/AssetKey.java index 8395105bfb..ec158690f1 100644 --- a/jme3-core/src/main/java/com/jme3/asset/AssetKey.java +++ b/jme3-core/src/main/java/com/jme3/asset/AssetKey.java @@ -41,7 +41,7 @@ /** * AssetKey is a key that is used to - * look up a resource from a cache. + * look up a resource from a cache. * This class should be immutable. */ public class AssetKey implements Savable, Cloneable { @@ -49,13 +49,13 @@ public class AssetKey implements Savable, Cloneable { protected String name; protected transient String folder; protected transient String extension; - - public AssetKey(String name){ + + public AssetKey(String name) { this.name = reducePath(name); this.extension = getExtension(this.name); } - public AssetKey(){ + public AssetKey() { } @Override @@ -67,7 +67,7 @@ public AssetKey clone() { throw new AssertionError(); } } - + protected static String getExtension(String name) { int idx = name.lastIndexOf('.'); //workaround for filenames ending with xml and another dot ending before that (my.mesh.xml) @@ -110,13 +110,13 @@ public String getExtension() { /** * @return The folder in which the asset is located in. - * E.g. if the {@link #getName() name} is "Models/MyModel/MyModel.j3o" + * E.g. if the {@link #getName() name} is "Models/MyModel/MyModel.j3o" * then "Models/MyModel/" is returned. */ - public String getFolder(){ + public String getFolder() { if (folder == null) folder = getFolder(name); - + return folder; } @@ -125,18 +125,18 @@ public String getFolder(){ * if caching is to be disabled. By default, the * {@link SimpleAssetCache} is returned. */ - public Class getCacheType(){ + public Class getCacheType() { return SimpleAssetCache.class; } - + /** * @return The preferred processor type for this asset type. Specify "null" * if no processing is required. */ - public Class getProcessorType(){ + public Class getProcessorType() { return null; } - + /** * Removes all relative elements of a path (A/B/../C.png and A/./C.png). * @param path The path containing relative elements @@ -157,7 +157,8 @@ public static String reducePath(String path) { list.removeLast(); } else { list.add(".."); - Logger.getLogger(AssetKey.class.getName()).log(Level.SEVERE, "Asset path \"{0}\" is outside the asset manager root", path); + Logger.getLogger(AssetKey.class.getName()) + .log(Level.SEVERE, "Asset path \"{0}\" is outside the asset manager root", path); } } else { list.add(string); @@ -173,22 +174,22 @@ public static String reducePath(String path) { } return builder.toString(); } - + @Override - public boolean equals(Object other){ - if (!(other instanceof AssetKey)){ + public boolean equals(Object other) { + if (!(other instanceof AssetKey)) { return false; } - return name.equals(((AssetKey)other).name); + return name.equals(((AssetKey) other).name); } @Override - public int hashCode(){ + public int hashCode() { return name.hashCode(); } @Override - public String toString(){ + public String toString() { return name; } @@ -204,5 +205,4 @@ public void read(JmeImporter im) throws IOException { name = reducePath(ic.readString("name", null)); extension = getExtension(name); } - } diff --git a/jme3-core/src/main/java/com/jme3/asset/AssetLoadException.java b/jme3-core/src/main/java/com/jme3/asset/AssetLoadException.java index 770640e04c..38aa38e3ff 100644 --- a/jme3-core/src/main/java/com/jme3/asset/AssetLoadException.java +++ b/jme3-core/src/main/java/com/jme3/asset/AssetLoadException.java @@ -39,10 +39,11 @@ * @author Kirill Vainer */ public class AssetLoadException extends RuntimeException { - public AssetLoadException(String message){ + public AssetLoadException(String message) { super(message); } - public AssetLoadException(String message, Throwable cause){ + + public AssetLoadException(String message, Throwable cause) { super(message, cause); } } diff --git a/jme3-core/src/main/java/com/jme3/asset/AssetNotFoundException.java b/jme3-core/src/main/java/com/jme3/asset/AssetNotFoundException.java index acee6db727..6c6968aff8 100644 --- a/jme3-core/src/main/java/com/jme3/asset/AssetNotFoundException.java +++ b/jme3-core/src/main/java/com/jme3/asset/AssetNotFoundException.java @@ -39,10 +39,11 @@ * @author Kirill Vainer */ public class AssetNotFoundException extends RuntimeException { - public AssetNotFoundException(String message){ + public AssetNotFoundException(String message) { super(message); } - public AssetNotFoundException(String message, Exception ex){ + + public AssetNotFoundException(String message, Exception ex) { super(message, ex); } } diff --git a/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java b/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java index 50e372a6f7..c81e56fec5 100644 --- a/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java +++ b/jme3-core/src/main/java/com/jme3/asset/DesktopAssetManager.java @@ -67,27 +67,27 @@ public class DesktopAssetManager implements AssetManager { private static final Logger logger = Logger.getLogger(AssetManager.class.getName()); private ShaderGenerator shaderGenerator; - + private final ImplHandler handler = new ImplHandler(this); - final private CopyOnWriteArrayList eventListeners = + final private CopyOnWriteArrayList eventListeners = new CopyOnWriteArrayList<>(); - + final private List classLoaders = Collections.synchronizedList(new ArrayList<>()); - public DesktopAssetManager(){ + public DesktopAssetManager() { this(null); } - - public DesktopAssetManager(boolean usePlatformConfig){ + + public DesktopAssetManager(boolean usePlatformConfig) { this(usePlatformConfig ? JmeSystem.getPlatformAssetConfigURL() : null); } - public DesktopAssetManager(URL configFile){ - if (configFile != null){ + public DesktopAssetManager(URL configFile) { + if (configFile != null) { loadConfigFile(configFile); - } + } logger.fine("DesktopAssetManager created."); } @@ -98,22 +98,22 @@ private void loadConfigFile(URL configFile) { logger.log(Level.SEVERE, "Failed to load asset config", ex); } } - + @Override public void addClassLoader(ClassLoader loader) { classLoaders.add(loader); } - + @Override public void removeClassLoader(ClassLoader loader) { classLoaders.remove(loader); } @Override - public List getClassLoaders(){ + public List getClassLoaders() { return Collections.unmodifiableList(classLoaders); } - + @Override public void addAssetEventListener(AssetEventListener listener) { eventListeners.add(listener); @@ -128,85 +128,85 @@ public void removeAssetEventListener(AssetEventListener listener) { public void clearAssetEventListeners() { eventListeners.clear(); } - - public void setAssetEventListener(AssetEventListener listener){ + + public void setAssetEventListener(AssetEventListener listener) { eventListeners.clear(); eventListeners.add(listener); } @Override - public void registerLoader(Class loader, String ... extensions){ + public void registerLoader(Class loader, String ... extensions) { handler.addLoader(loader, extensions); - if (logger.isLoggable(Level.FINER)){ + if (logger.isLoggable(Level.FINER)) { logger.log(Level.FINER, "Registered loader: {0} for extensions {1}", - new Object[]{loader.getSimpleName(), Arrays.toString(extensions)}); + new Object[]{loader.getSimpleName(), Arrays.toString(extensions)}); } } @SuppressWarnings("unchecked") - public void registerLoader(String clsName, String ... extensions){ + public void registerLoader(String clsName, String ... extensions) { Class clazz = null; - try{ + try { clazz = (Class) Class.forName(clsName); } catch (ClassNotFoundException | NoClassDefFoundError ex) { - logger.log(Level.WARNING, "Failed to find loader: "+clsName, ex); + logger.log(Level.WARNING, "Failed to find loader: " + clsName, ex); } - if (clazz != null){ + if (clazz != null) { registerLoader(clazz, extensions); } } - + @Override public void unregisterLoader(Class loaderClass) { handler.removeLoader(loaderClass); - if (logger.isLoggable(Level.FINER)){ + if (logger.isLoggable(Level.FINER)) { logger.log(Level.FINER, "Unregistered loader: {0}", loaderClass.getSimpleName()); } } @Override - public void registerLocator(String rootPath, Class locatorClass){ + public void registerLocator(String rootPath, Class locatorClass) { handler.addLocator(locatorClass, rootPath); - if (logger.isLoggable(Level.FINER)){ + if (logger.isLoggable(Level.FINER)) { logger.log(Level.FINER, "Registered locator: {0}", locatorClass.getSimpleName()); } } @SuppressWarnings("unchecked") - public void registerLocator(String rootPath, String clsName){ + public void registerLocator(String rootPath, String clsName) { Class clazz = null; - try{ + try { clazz = (Class) Class.forName(clsName); - }catch (ClassNotFoundException ex){ - logger.log(Level.WARNING, "Failed to find locator: "+clsName, ex); - }catch (NoClassDefFoundError ex){ - logger.log(Level.WARNING, "Failed to find loader: "+clsName, ex); + } catch (ClassNotFoundException ex) { + logger.log(Level.WARNING, "Failed to find locator: " + clsName, ex); + } catch (NoClassDefFoundError ex) { + logger.log(Level.WARNING, "Failed to find loader: " + clsName, ex); } - if (clazz != null){ + if (clazz != null) { registerLocator(rootPath, clazz); } } - + @Override - public void unregisterLocator(String rootPath, Class clazz){ + public void unregisterLocator(String rootPath, Class clazz) { handler.removeLocator(clazz, rootPath); - if (logger.isLoggable(Level.FINER)){ + if (logger.isLoggable(Level.FINER)) { logger.log(Level.FINER, "Unregistered locator: {0}", clazz.getSimpleName()); } } - + @Override - public AssetInfo locateAsset(AssetKey key){ + public AssetInfo locateAsset(AssetKey key) { AssetInfo info = handler.tryLocate(key); - if (info == null){ + if (info == null) { logger.log(Level.WARNING, "Cannot locate resource: {0}", key); } return info; } - + @Override public T getFromCache(AssetKey key) { AssetCache cache = handler.getCache(key.getCacheType()); @@ -221,7 +221,7 @@ public T getFromCache(AssetKey key) { throw new IllegalArgumentException("Key " + key + " specifies no cache."); } } - + @Override public void addToCache(AssetKey key, T asset) { AssetCache cache = handler.getCache(key.getCacheType()); @@ -232,7 +232,7 @@ public void addToCache(AssetKey key, T asset) { throw new IllegalArgumentException("Key " + key + " specifies no cache."); } } - + @Override public boolean deleteFromCache(AssetKey key) { AssetCache cache = handler.getCache(key.getCacheType()); @@ -242,11 +242,11 @@ public boolean deleteFromCache(AssetKey key) { throw new IllegalArgumentException("Key " + key + " specifies no cache."); } } - + @Override - public void clearCache(){ + public void clearCache() { handler.clearCache(); - if (logger.isLoggable(Level.FINER)){ + if (logger.isLoggable(Level.FINER)) { logger.log(Level.FINER, "All asset caches cleared."); } } @@ -259,7 +259,7 @@ public void clearCache(){ * @param proc AssetProcessor to use, or null to disable processing * @param cache The cache to store the asset in, or null to disable caching * @return The loaded asset - * + * * @throws AssetLoadException If failed to load asset due to exception or * other error. */ @@ -301,22 +301,22 @@ protected T loadLocatedAsset(AssetKey key, AssetInfo info, AssetProcessor return (T) obj; } } - + /** * Clones the asset using the given processor and registers the clone * with the cache. - * + * * @param The asset type * @param key The asset key - * @param obj The asset to clone / register, must implement - * {@link CloneableSmartAsset}. + * @param obj The asset to clone / register, must implement + * {@link CloneableSmartAsset}. * @param proc The processor which will generate the clone, cannot be null * @param cache The cache to register the clone with, cannot be null. * @return The cloned asset, cannot be the same as the given asset since - * it is a clone. - * - * @throws IllegalStateException If asset does not implement - * {@link CloneableSmartAsset}, if the cache is null, or if the + * it is a clone. + * + * @throws IllegalStateException If asset does not implement + * {@link CloneableSmartAsset}, if the cache is null, or if the * processor did not clone the asset. */ @SuppressWarnings("unchecked") @@ -339,118 +339,118 @@ protected T registerAndCloneSmartAsset(AssetKey key, T obj, AssetProcesso return clone; } } - + @Override public T loadAssetFromStream(AssetKey key, InputStream inputStream) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } - - for (AssetEventListener listener : eventListeners){ + + for (AssetEventListener listener : eventListeners) { listener.assetRequested(key); } - + AssetProcessor proc = handler.getProcessor(key.getProcessorType()); StreamAssetInfo info = new StreamAssetInfo(this, key, inputStream); return loadLocatedAsset(key, info, proc, null); } - + @Override @SuppressWarnings("unchecked") - public T loadAsset(AssetKey key){ + public T loadAsset(AssetKey key) { if (key == null) throw new IllegalArgumentException("key cannot be null"); - - for (AssetEventListener listener : eventListeners){ + + for (AssetEventListener listener : eventListeners) { listener.assetRequested(key); } - + AssetCache cache = handler.getCache(key.getCacheType()); AssetProcessor proc = handler.getProcessor(key.getProcessorType()); - + Object obj = cache != null ? cache.getFromCache(key) : null; - if (obj == null){ + if (obj == null) { // Asset not in cache, load it from file system. AssetInfo info = handler.tryLocate(key); - if (info == null){ - if (handler.getParentKey() != null){ + if (info == null) { + if (handler.getParentKey() != null) { // Inform event listener that an asset has failed to load. // If the parent AssetLoader chooses not to propagate // the exception, this is the only means of finding // that something went wrong. - for (AssetEventListener listener : eventListeners){ + for (AssetEventListener listener : eventListeners) { listener.assetDependencyNotFound(handler.getParentKey(), key); } } throw new AssetNotFoundException(key.toString()); } - + obj = loadLocatedAsset(key, info, proc, cache); } T clone = (T) obj; - + if (obj instanceof CloneableSmartAsset) { clone = registerAndCloneSmartAsset(key, clone, proc, cache); } - + return clone; } @Override - public Object loadAsset(String name){ + public Object loadAsset(String name) { return loadAsset(new AssetKey<>(name)); } @Override - public Texture loadTexture(TextureKey key){ + public Texture loadTexture(TextureKey key) { return loadAsset(key); } @Override - public Material loadMaterial(String name){ + public Material loadMaterial(String name) { return loadAsset(new MaterialKey(name)); } @Override - public Texture loadTexture(String name){ + public Texture loadTexture(String name) { TextureKey key = new TextureKey(name, true); key.setGenerateMips(true); return loadTexture(key); } @Override - public AudioData loadAudio(AudioKey key){ + public AudioData loadAudio(AudioKey key) { return loadAsset(key); } @Override - public AudioData loadAudio(String name){ + public AudioData loadAudio(String name) { return loadAudio(new AudioKey(name, false)); } @Override - public BitmapFont loadFont(String name){ + public BitmapFont loadFont(String name) { return loadAsset(new AssetKey(name)); } @Override - public Spatial loadModel(ModelKey key){ + public Spatial loadModel(ModelKey key) { return loadAsset(key); } @Override - public Spatial loadModel(String name){ + public Spatial loadModel(String name) { return loadModel(new ModelKey(name)); } @Override - public FilterPostProcessor loadFilter(FilterKey key){ + public FilterPostProcessor loadFilter(FilterKey key) { return loadAsset(key); } @Override - public FilterPostProcessor loadFilter(String name){ + public FilterPostProcessor loadFilter(String name) { return loadFilter(new FilterKey(name)); } @@ -460,11 +460,11 @@ public FilterPostProcessor loadFilter(String name){ @Override public ShaderGenerator getShaderGenerator(EnumSet caps) { if (shaderGenerator == null) { - if(caps.contains(Caps.OpenGLES30) && caps.contains(Caps.GLSL300)){ + if (caps.contains(Caps.OpenGLES30) && caps.contains(Caps.GLSL300)) { shaderGenerator = new Glsl300ShaderGenerator(this); - }else if(caps.contains(Caps.GLSL150)) { + } else if (caps.contains(Caps.GLSL150)) { shaderGenerator = new Glsl150ShaderGenerator(this); - }else{ + } else { shaderGenerator = new Glsl100ShaderGenerator(this); } } @@ -478,6 +478,4 @@ public ShaderGenerator getShaderGenerator(EnumSet caps) { public void setShaderGenerator(ShaderGenerator shaderGenerator) { this.shaderGenerator = shaderGenerator; } - - } diff --git a/jme3-core/src/main/java/com/jme3/asset/FilterKey.java b/jme3-core/src/main/java/com/jme3/asset/FilterKey.java index 1bb1f60f03..8edbfe60af 100644 --- a/jme3-core/src/main/java/com/jme3/asset/FilterKey.java +++ b/jme3-core/src/main/java/com/jme3/asset/FilterKey.java @@ -36,7 +36,7 @@ /** * Used to load FilterPostProcessors which are not cached. - * + * * @author Andrew Wason */ public class FilterKey extends AssetKey { @@ -50,7 +50,7 @@ public FilterKey() { } @Override - public Class getCacheType(){ + public Class getCacheType() { // Do not cache filter processors return null; } diff --git a/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java b/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java index e8763d491f..0706c52262 100644 --- a/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java +++ b/jme3-core/src/main/java/com/jme3/asset/ImplHandler.java @@ -53,26 +53,26 @@ final class ImplHandler { private static final Logger logger = Logger.getLogger(ImplHandler.class.getName()); private final AssetManager assetManager; - - private final ThreadLocal parentAssetKey + + private final ThreadLocal parentAssetKey = new ThreadLocal<>(); - + private final CopyOnWriteArrayList> locatorsList = - new CopyOnWriteArrayList<>(); - - private final HashMap, ImplThreadLocal> classToLoaderMap = - new HashMap<>(); + new CopyOnWriteArrayList<>(); + + private final HashMap, ImplThreadLocal> classToLoaderMap = + new HashMap<>(); private final ConcurrentHashMap> extensionToLoaderMap = - new ConcurrentHashMap<>(); - + new ConcurrentHashMap<>(); + private final ConcurrentHashMap, AssetProcessor> classToProcMap = - new ConcurrentHashMap<>(); - + new ConcurrentHashMap<>(); + private final ConcurrentHashMap, AssetCache> classToCacheMap = - new ConcurrentHashMap<>(); + new ConcurrentHashMap<>(); - public ImplHandler(AssetManager assetManager){ + public ImplHandler(AssetManager assetManager) { this.assetManager = assetManager; } @@ -82,48 +82,48 @@ protected static class ImplThreadLocal extends ThreadLocal { private final String path; private final String[] extensions; - public ImplThreadLocal(Class type, String[] extensions){ + public ImplThreadLocal(Class type, String[] extensions) { this.type = type; this.extensions = extensions.clone(); this.path = null; } - public ImplThreadLocal(Class type, String path){ + public ImplThreadLocal(Class type, String path) { this.type = type; this.path = path; this.extensions = null; } - public ImplThreadLocal(Class type){ + public ImplThreadLocal(Class type) { this.type = type; this.path = null; this.extensions = null; } - + public String getPath() { return path; } - - public String[] getExtensions(){ + + public String[] getExtensions() { return extensions; } - - public Class getTypeClass(){ + + public Class getTypeClass() { return type; } @Override - protected T initialValue(){ + protected T initialValue() { try { T obj = type.newInstance(); if (path != null) { - ((AssetLocator)obj).setRootPath(path); + ((AssetLocator) obj).setRootPath(path); } return obj; } catch (InstantiationException | IllegalAccessException ex) { - logger.log(Level.SEVERE,"Cannot create locator of type {0}, does" - + " the class have an empty and publicly accessible"+ - " constructor?", type.getName()); + logger.log(Level.SEVERE, "Cannot create locator of type {0}, does" + + " the class have an empty and publicly accessible" + + " constructor?", type.getName()); logger.throwing(type.getName(), "", ex); } return null; @@ -135,51 +135,51 @@ protected T initialValue(){ * that have failed to load. When set, the {@link DesktopAssetManager} * gets a hint that it should suppress {@link AssetNotFoundException}s * and instead call the listener callback (if set). - * - * @param parentKey The parent key + * + * @param parentKey The parent key */ - public void establishParentKey(AssetKey parentKey){ - if (parentAssetKey.get() == null){ + public void establishParentKey(AssetKey parentKey) { + if (parentAssetKey.get() == null) { parentAssetKey.set(parentKey); } } - - public void releaseParentKey(AssetKey parentKey){ - if (parentAssetKey.get() == parentKey){ + + public void releaseParentKey(AssetKey parentKey) { + if (parentAssetKey.get() == parentKey) { parentAssetKey.set(null); } } - - public AssetKey getParentKey(){ + + public AssetKey getParentKey() { return parentAssetKey.get(); } - + /** * Attempts to locate the given resource name. * @param key The full name of the resource. * @return The AssetInfo containing resource information required for * access, or null if not found. */ - public AssetInfo tryLocate(AssetKey key){ - if (locatorsList.isEmpty()){ - logger.warning("There are no locators currently"+ - " registered. Use AssetManager."+ - "registerLocator() to register a"+ - " locator."); + public AssetInfo tryLocate(AssetKey key) { + if (locatorsList.isEmpty()) { + logger.warning("There are no locators currently" + + " registered. Use AssetManager." + + "registerLocator() to register a" + + " locator."); return null; } - - for (ImplThreadLocal local : locatorsList){ + + for (ImplThreadLocal local : locatorsList) { AssetInfo info = local.get().locate(assetManager, key); if (info != null) { return info; } } - + return null; } - public int getLocatorCount(){ + public int getLocatorCount() { return locatorsList.size(); } @@ -188,32 +188,32 @@ public int getLocatorCount(){ * of the current thread. * @return AssetLoader registered with addLoader. */ - public AssetLoader aquireLoader(AssetKey key){ + public AssetLoader aquireLoader(AssetKey key) { // No need to synchronize() against map, its concurrent ImplThreadLocal local = extensionToLoaderMap.get(key.getExtension()); - if (local == null){ - throw new AssetLoadException("No loader registered for type \"" + - key.getExtension() + "\""); + if (local == null) { + throw new AssetLoadException("No loader registered for type \"" + + key.getExtension() + "\""); } return (AssetLoader) local.get(); } - - public void clearCache(){ + + public void clearCache() { // The iterator over the values collection is thread-safe. synchronized (classToCacheMap) { - for (AssetCache cache : classToCacheMap.values()){ + for (AssetCache cache : classToCacheMap.values()) { cache.clearCache(); } } } - + @SuppressWarnings("unchecked") public T getCache(Class cacheClass) { if (cacheClass == null) { return null; } - + T cache = (T) classToCacheMap.get(cacheClass); if (cache == null) { synchronized (classToCacheMap) { @@ -234,15 +234,15 @@ public T getCache(Class cacheClass) { } return cache; } - + @SuppressWarnings("unchecked") - public T getProcessor(Class procClass){ + public T getProcessor(Class procClass) { if (procClass == null) return null; - + T proc = (T) classToProcMap.get(procClass); - if (proc == null){ - synchronized(classToProcMap){ + if (proc == null) { + synchronized (classToProcMap) { proc = (T) classToProcMap.get(procClass); if (proc == null) { try { @@ -260,55 +260,55 @@ public T getProcessor(Class procClass){ } return proc; } - + @SuppressWarnings("unchecked") - public void addLoader(final Class loaderType, String ... extensions){ + public void addLoader(final Class loaderType, String ... extensions) { // Synchronized access must be used for any ops on classToLoaderMap ImplThreadLocal local = new ImplThreadLocal(loaderType, extensions); - for (String extension : extensions){ + for (String extension : extensions) { extension = extension.toLowerCase(); - synchronized (classToLoaderMap){ + synchronized (classToLoaderMap) { classToLoaderMap.put(loaderType, local); extensionToLoaderMap.put(extension, local); } } } - public void removeLoader(final Class loaderType){ + public void removeLoader(final Class loaderType) { // Synchronized access must be used for any ops on classToLoaderMap // Find the loader ImplThreadLocal for this class - synchronized (classToLoaderMap){ + synchronized (classToLoaderMap) { // Remove it from the class->loader map ImplThreadLocal local = classToLoaderMap.remove(loaderType); - if (local == null) return; + if (local == null) + return; // Remove it from the extension->loader map - for (String extension : local.getExtensions()){ + for (String extension : local.getExtensions()) { extensionToLoaderMap.remove(extension); } } } - + @SuppressWarnings("unchecked") - public void addLocator(final Class locatorType, String rootPath){ + public void addLocator(final Class locatorType, String rootPath) { locatorsList.add(new ImplThreadLocal(locatorType, rootPath)); } - public void removeLocator(final Class locatorType, String rootPath){ + public void removeLocator(final Class locatorType, String rootPath) { ArrayList> locatorsToRemove = new ArrayList<>(); Iterator> it = locatorsList.iterator(); - - while (it.hasNext()){ + + while (it.hasNext()) { ImplThreadLocal locator = it.next(); - if (locator.getPath().equals(rootPath) && - locator.getTypeClass().equals(locatorType)){ + if (locator.getPath().equals(rootPath) + && locator.getTypeClass().equals(locatorType)) { //it.remove(); // copy on write list doesn't support iterator remove, // must use temporary list locatorsToRemove.add(locator); } } - + locatorsList.removeAll(locatorsToRemove); } - } diff --git a/jme3-core/src/main/java/com/jme3/asset/ModelKey.java b/jme3-core/src/main/java/com/jme3/asset/ModelKey.java index fa47df6485..1223c5f24a 100644 --- a/jme3-core/src/main/java/com/jme3/asset/ModelKey.java +++ b/jme3-core/src/main/java/com/jme3/asset/ModelKey.java @@ -39,9 +39,9 @@ * Used to load model files, such as OBJ or Blender models. * This uses cloneable smart asset management, so that when all clones of * this model become unreachable, the original asset is purged from the cache, - * allowing textures, materials, shaders, etc referenced by the model to + * allowing textures, materials, shaders, etc referenced by the model to * become collected. - * + * * @author Kirill Vainer */ public class ModelKey extends AssetKey { @@ -53,14 +53,14 @@ public ModelKey(String name) { public ModelKey() { super(); } - + @Override - public Class getCacheType(){ + public Class getCacheType() { return WeakRefCloneAssetCache.class; } - + @Override - public Class getProcessorType(){ + public Class getProcessorType() { return CloneableAssetProcessor.class; } } diff --git a/jme3-core/src/main/java/com/jme3/asset/TextureKey.java b/jme3-core/src/main/java/com/jme3/asset/TextureKey.java index cb5450b359..be096de5da 100644 --- a/jme3-core/src/main/java/com/jme3/asset/TextureKey.java +++ b/jme3-core/src/main/java/com/jme3/asset/TextureKey.java @@ -44,14 +44,14 @@ import java.io.IOException; /** - * Used to load textures from image files such as JPG or PNG. + * Used to load textures from image files such as JPG or PNG. * Note that texture loaders actually load the asset as an {@link Image} - * object, which is then converted to a {@link Texture} in the - * {@link TextureProcessor#postProcess(com.jme3.asset.AssetKey, java.lang.Object) } + * object, which is then converted to a {@link Texture} in the + * {@link TextureProcessor#postProcess(com.jme3.asset.AssetKey, java.lang.Object)} * method. Since textures are cloneable smart assets, the texture stored * in the cache will be collected when all clones of the texture become * unreachable. - * + * * @author Kirill Vainer */ public class TextureKey extends AssetKey { @@ -96,17 +96,17 @@ public String toString() { } return name + (flipY ? " (Flipped)" : "") + type + (generateMips ? " (Mipmapped)" : ""); } - + @Override - public Class getCacheType(){ + public Class getCacheType() { return WeakRefCloneAssetCache.class; } @Override - public Class getProcessorType(){ + public Class getProcessorType() { return TextureProcessor.class; } - + public boolean isFlipY() { return flipY; } @@ -114,7 +114,7 @@ public boolean isFlipY() { public void setFlipY(boolean flipY) { this.flipY = flipY; } - + public int getAnisotropy() { return anisotropy; } @@ -133,7 +133,7 @@ public void setGenerateMips(boolean generateMips) { /** * The type of texture expected to be returned. - * + * * @return type of texture expected to be returned. */ public Type getTextureTypeHint() { @@ -142,13 +142,13 @@ public Type getTextureTypeHint() { /** * Hints the loader as to which type of texture is expected. - * + * * @param textureTypeHint The type of texture expected to be loaded. */ public void setTextureTypeHint(Type textureTypeHint) { this.textureTypeHint = textureTypeHint; } - + @Override public boolean equals(Object obj) { if (obj == null) { @@ -186,7 +186,7 @@ public int hashCode() { hash = 17 * hash + (this.textureTypeHint != null ? this.textureTypeHint.hashCode() : 0); return hash; } - + @Override public void write(JmeExporter ex) throws IOException { super.write(ex); @@ -195,7 +195,7 @@ public void write(JmeExporter ex) throws IOException { oc.write(generateMips, "generate_mips", false); oc.write(anisotropy, "anisotropy", 0); oc.write(textureTypeHint, "tex_type", Type.TwoDimensional); - + // Backwards compat oc.write(textureTypeHint == Type.CubeMap, "as_cubemap", false); } @@ -208,7 +208,7 @@ public void read(JmeImporter im) throws IOException { generateMips = ic.readBoolean("generate_mips", false); anisotropy = ic.readInt("anisotropy", 0); boolean asCube = ic.readBoolean("as_cubemap", false); - + if (asCube) { // Backwards compat textureTypeHint = Type.CubeMap; diff --git a/jme3-core/src/main/java/com/jme3/asset/ThreadingManager.java b/jme3-core/src/main/java/com/jme3/asset/ThreadingManager.java index 43299a550a..4d8dfc7d7b 100644 --- a/jme3-core/src/main/java/com/jme3/asset/ThreadingManager.java +++ b/jme3-core/src/main/java/com/jme3/asset/ThreadingManager.java @@ -37,18 +37,18 @@ * ThreadingManager manages the threads used to load content * within the Content Manager system. A pool of threads and a task queue * is used to load resource data and perform I/O while the application's - * render thread is active. + * render thread is active. */ public class ThreadingManager { protected final ExecutorService executor = - Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), - new LoadingThreadFactory()); + Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), + new LoadingThreadFactory()); protected final AssetManager owner; protected int nextThreadId = 0; - public ThreadingManager(AssetManager owner){ + public ThreadingManager(AssetManager owner) { this.owner = owner; } @@ -83,6 +83,4 @@ public Future loadAsset(AssetKey assetKey) { public static boolean isLoadingThread() { return Thread.currentThread().getName().startsWith("jME3-threadpool"); } - - } diff --git a/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefAssetCache.java b/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefAssetCache.java index 79e3e215e0..08631731d7 100644 --- a/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefAssetCache.java +++ b/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefAssetCache.java @@ -42,52 +42,53 @@ /** * A garbage collector bound asset cache that handles non-cloneable objects. * This cache assumes that the asset given to the user is the same asset - * that has been stored in the cache, in other words, + * that has been stored in the cache, in other words, * {@link AssetProcessor#createClone(java.lang.Object) } for that asset * returns the same object as the argument. - * This implementation will remove the asset from the cache + * This implementation will remove the asset from the cache * once the asset is no longer referenced in user code and memory is low, * e.g. the VM feels like purging the weak references for that asset. - * + * * @author Kirill Vainer */ public class WeakRefAssetCache implements AssetCache { private static final Logger logger = Logger.getLogger(WeakRefAssetCache.class.getName()); - + private final ReferenceQueue refQueue = new ReferenceQueue<>(); - - private final ConcurrentHashMap assetCache + + private final ConcurrentHashMap assetCache = new ConcurrentHashMap<>(); private static class AssetRef extends WeakReference { - + private final AssetKey assetKey; - - public AssetRef(AssetKey assetKey, Object originalAsset, ReferenceQueue refQueue){ + + public AssetRef(AssetKey assetKey, Object originalAsset, ReferenceQueue refQueue) { super(originalAsset, refQueue); this.assetKey = assetKey; } } - - private void removeCollectedAssets(){ + + private void removeCollectedAssets() { int removedAssets = 0; - for (AssetRef ref; (ref = (AssetRef)refQueue.poll()) != null;){ - // Asset was collected, note that at this point the asset cache + for (AssetRef ref; (ref = (AssetRef) refQueue.poll()) != null;) { + // Asset was collected, note that at this point the asset cache // might not even have this asset anymore, it is OK. - if (assetCache.remove(ref.assetKey) != null){ - removedAssets ++; + if (assetCache.remove(ref.assetKey) != null) { + removedAssets++; } } if (removedAssets >= 1) { - logger.log(Level.FINE, "WeakRefAssetCache: {0} assets were purged from the cache.", removedAssets); + logger.log(Level.FINE, + "WeakRefAssetCache: {0} assets were purged from the cache.", removedAssets); } } - + @Override public void addToCache(AssetKey key, T obj) { removeCollectedAssets(); - + // NOTE: Some thread issues can happen if another // thread is loading an asset with the same key. AssetRef ref = new AssetRef(key, obj, refQueue); @@ -98,9 +99,9 @@ public void addToCache(AssetKey key, T obj) { @SuppressWarnings("unchecked") public T getFromCache(AssetKey key) { AssetRef ref = assetCache.get(key); - if (ref != null){ + if (ref != null) { return (T) ref.get(); - }else{ + } else { return null; } } @@ -114,11 +115,11 @@ public boolean deleteFromCache(AssetKey key) { public void clearCache() { assetCache.clear(); } - + @Override public void registerAssetClone(AssetKey key, T clone) { } - + @Override public void notifyNoAssetClone() { } diff --git a/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java b/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java index 39f233a07b..5e0a90c173 100644 --- a/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java +++ b/jme3-core/src/main/java/com/jme3/asset/cache/WeakRefCloneAssetCache.java @@ -45,39 +45,39 @@ * WeakRefCloneAssetCache caches cloneable assets in a weak-key * cache, allowing them to be collected when memory is low. * The cache stores weak references to the asset keys, so that - * when all clones of the original asset are collected, will cause the + * when all clones of the original asset are collected, will cause the * asset to be automatically removed from the cache. - * -* @author Kirill Vainer + * + * @author Kirill Vainer */ public class WeakRefCloneAssetCache implements AssetCache { private static final Logger logger = Logger.getLogger(WeakRefAssetCache.class.getName()); - + private final ReferenceQueue refQueue = new ReferenceQueue<>(); - + /** - * Maps cloned key to AssetRef which has a weak ref to the original + * Maps cloned key to AssetRef which has a weak ref to the original * key and a strong ref to the original asset. */ - private final ConcurrentHashMap smartCache + private final ConcurrentHashMap smartCache = new ConcurrentHashMap<>(); - + /** * Stored in the ReferenceQueue to find out when originalKey is collected * by GC. Once collected, the clonedKey is used to remove the asset * from the cache. */ private static final class KeyRef extends PhantomReference { - + AssetKey clonedKey; - + public KeyRef(AssetKey originalKey, ReferenceQueue refQueue) { super(originalKey, refQueue); clonedKey = originalKey.clone(); } } - + /** * Stores the original key and original asset. * The asset info contains a cloneable asset (e.g. the original, from @@ -94,50 +94,51 @@ public AssetRef(CloneableSmartAsset originalAsset, AssetKey originalKey) { } } - private final ThreadLocal> assetLoadStack + private final ThreadLocal> assetLoadStack = new ThreadLocal>() { @Override protected ArrayList initialValue() { return new ArrayList<>(); } }; - - private void removeCollectedAssets(){ + + private void removeCollectedAssets() { int removedAssets = 0; - for (KeyRef ref; (ref = (KeyRef)refQueue.poll()) != null;){ + for (KeyRef ref; (ref = (KeyRef) refQueue.poll()) != null;) { // (Cannot use ref.get() since it was just collected by GC!) AssetKey key = ref.clonedKey; - - // Asset was collected, note that at this point the asset cache + + // Asset was collected, note that at this point the asset cache // might not even have this asset anymore, it is OK. - if (smartCache.remove(key) != null){ - removedAssets ++; + if (smartCache.remove(key) != null) { + removedAssets++; } } if (removedAssets >= 1) { - logger.log(Level.FINE, "WeakRefCloneAssetCache: {0} assets were purged from the cache.", removedAssets); + logger.log(Level.FINE, + "WeakRefCloneAssetCache: {0} assets were purged from the cache.", removedAssets); } } - + @Override public void addToCache(AssetKey originalKey, T obj) { // Make room for new asset removeCollectedAssets(); - + CloneableSmartAsset asset = (CloneableSmartAsset) obj; - - // No circular references, since the original asset is + + // No circular references, since the original asset is // strongly referenced, we don't want the key strongly referenced. - asset.setKey(null); - + asset.setKey(null); + // Start tracking the collection of originalKey // (this adds the KeyRef to the ReferenceQueue) KeyRef ref = new KeyRef(originalKey, refQueue); - - // Place the asset in the cache, but use a clone of + + // Place the asset in the cache, but use a clone of // the original key. smartCache.put(ref.clonedKey, new AssetRef(asset, originalKey)); - + // Push the original key used to load the asset // so that it can be set on the clone later ArrayList loadStack = assetLoadStack.get(); @@ -147,9 +148,9 @@ public void addToCache(AssetKey originalKey, T obj) { @Override public void registerAssetClone(AssetKey key, T clone) { ArrayList loadStack = assetLoadStack.get(); - ((CloneableSmartAsset)clone).setKey(loadStack.remove(loadStack.size() - 1)); + ((CloneableSmartAsset) clone).setKey(loadStack.remove(loadStack.size() - 1)); } - + @Override public void notifyNoAssetClone() { ArrayList loadStack = assetLoadStack.get(); @@ -167,17 +168,17 @@ public T getFromCache(AssetKey key) { // can check this and determine that the asset clone // belongs to the asset retrieved here. AssetKey keyForTheClone = smartInfo.get(); - if (keyForTheClone == null){ + if (keyForTheClone == null) { // The asset was JUST collected by GC // (between here and smartCache.get) return null; } - + // Prevent original key from getting collected // while an asset is loaded for it. ArrayList loadStack = assetLoadStack.get(); loadStack.add(keyForTheClone); - + return (T) smartInfo.asset; } } @@ -185,24 +186,24 @@ public T getFromCache(AssetKey key) { @Override public boolean deleteFromCache(AssetKey key) { ArrayList loadStack = assetLoadStack.get(); - - if (!loadStack.isEmpty()){ + + if (!loadStack.isEmpty()) { throw new UnsupportedOperationException("Cache cannot be modified" - + "while assets are being loaded"); + + "while assets are being loaded"); } - + return smartCache.remove(key) != null; } - + @Override public void clearCache() { ArrayList loadStack = assetLoadStack.get(); - - if (!loadStack.isEmpty()){ + + if (!loadStack.isEmpty()) { throw new UnsupportedOperationException("Cache cannot be modified" - + "while assets are being loaded"); + + "while assets are being loaded"); } - + smartCache.clear(); } } diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioBuffer.java b/jme3-core/src/main/java/com/jme3/audio/AudioBuffer.java index df4f213f36..80f5f63040 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioBuffer.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioBuffer.java @@ -51,11 +51,11 @@ public class AudioBuffer extends AudioData { */ protected ByteBuffer audioData; - public AudioBuffer(){ + public AudioBuffer() { super(); } - - protected AudioBuffer(int id){ + + protected AudioBuffer(int id) { super(id); } @@ -69,7 +69,7 @@ public DataType getDataType() { * that audio is uncompressed. */ @Override - public float getDuration(){ + public float getDuration() { int bytesPerSec = (bitsPerSample / 8) * channels * sampleRate; if (audioData != null) return (float) audioData.limit() / bytesPerSec; @@ -78,10 +78,10 @@ public float getDuration(){ } @Override - public String toString(){ - return getClass().getSimpleName() + - "[id="+id+", ch="+channels+", bits="+bitsPerSample + - ", rate="+sampleRate+", duration="+getDuration()+"]"; + public String toString() { + return getClass().getSimpleName() + + "[id=" + id + ", ch=" + channels + ", bits=" + bitsPerSample + + ", rate=" + sampleRate + ", duration=" + getDuration() + "]"; } /** @@ -90,7 +90,7 @@ public String toString(){ * @param data the audio data provided (not null, direct, alias created) * @throws IllegalArgumentException if the provided buffer is not a direct buffer */ - public void updateData(ByteBuffer data){ + public void updateData(ByteBuffer data) { if (!data.isDirect()) { throw new IllegalArgumentException( "Currently only direct buffers are allowed"); @@ -103,7 +103,7 @@ public void updateData(ByteBuffer data){ /** * @return The buffered audio data. */ - public ByteBuffer getData(){ + public ByteBuffer getData() { return audioData; } @@ -119,10 +119,10 @@ protected void deleteNativeBuffers() { BufferUtils.destroyDirectBuffer(audioData); } } - + @Override public void deleteObject(Object rendererObject) { - ((AudioRenderer)rendererObject).deleteAudioData(this); + ((AudioRenderer) rendererObject).deleteAudioData(this); } @Override @@ -132,6 +132,6 @@ public NativeObject createDestructableClone() { @Override public long getUniqueId() { - return ((long)OBJTYPE_AUDIOBUFFER << 32) | ((long)id); + return ((long) OBJTYPE_AUDIOBUFFER << 32) | ((long) id); } } diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioContext.java b/jme3-core/src/main/java/com/jme3/audio/AudioContext.java index cde3fec239..a819b93351 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioContext.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioContext.java @@ -39,17 +39,17 @@ public class AudioContext { final private static ThreadLocal audioRenderer = new ThreadLocal(); - + /** * A private constructor to inhibit instantiation of this class. */ private AudioContext() { } - public static void setAudioRenderer( AudioRenderer ar ) { - audioRenderer.set(ar); + public static void setAudioRenderer(AudioRenderer ar) { + audioRenderer.set(ar); } - + public static AudioRenderer getAudioRenderer() { return audioRenderer.get(); } diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioData.java b/jme3-core/src/main/java/com/jme3/audio/AudioData.java index bfd1b80b51..6a0f1953aa 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioData.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioData.java @@ -51,15 +51,15 @@ public enum DataType { Buffer, Stream } - - public AudioData(){ + + public AudioData() { super(); } - protected AudioData(int id){ + protected AudioData(int id) { super(id); } - + /** * @return The data type, either Buffer or Stream. */ @@ -69,7 +69,7 @@ protected AudioData(int id){ * @return the duration in seconds of the audio clip. */ public abstract float getDuration(); - + /** * @return Bits per single sample from a channel. */ @@ -97,7 +97,7 @@ public int getSampleRate() { * @param bitsPerSample Bits per sample, e.g 8 bits, 16 bits. * @param sampleRate Sample rate, 44100, 22050, etc. */ - public void setupFormat(int channels, int bitsPerSample, int sampleRate){ + public void setupFormat(int channels, int bitsPerSample, int sampleRate) { if (id != -1) throw new IllegalStateException("Already set up"); diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioKey.java b/jme3-core/src/main/java/com/jme3/audio/AudioKey.java index 071d9c2e5f..6e4ee356c8 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioKey.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioKey.java @@ -53,20 +53,20 @@ public class AudioKey extends AssetKey { /** * Create a new AudioKey. - * + * * @param name Name of the asset * @param stream If true, the audio will be streamed. * Otherwise, it will be buffered entirely and then played. * @param streamCache If stream is true, then this specifies if * the stream cache is used. When enabled, the audio stream will - * be read entirely but not decoded, allowing features such as + * be read entirely but not decoded, allowing features such as * seeking, determining duration and looping. */ - public AudioKey(String name, boolean stream, boolean streamCache){ + public AudioKey(String name, boolean stream, boolean streamCache) { this(name, stream); this.streamCache = streamCache; } - + /** * Create a new AudioKey * @@ -74,26 +74,24 @@ public AudioKey(String name, boolean stream, boolean streamCache){ * @param stream If true, the audio will be streamed. * Otherwise, it will be buffered entirely and then played. */ - public AudioKey(String name, boolean stream){ + public AudioKey(String name, boolean stream) { super(name); this.stream = stream; } - public AudioKey(String name){ + public AudioKey(String name) { super(name); this.stream = false; } - public AudioKey(){ + public AudioKey() { } @Override - public String toString(){ - return name + (stream ? - (streamCache ? - " (Stream/Cache)" : - " (Stream)") : - " (Buffer)"); + public String toString() { + return name + (stream + ? (streamCache ? " (Stream/Cache)" : " (Stream)") + : " (Buffer)"); } /** @@ -103,17 +101,17 @@ public String toString(){ public boolean isStream() { return stream; } - + /** - * Specifies if the stream cache is used. - * + * Specifies if the stream cache is used. + * * When enabled, the audio stream will - * be read entirely but not decoded, allowing features such as + * be read entirely but not decoded, allowing features such as * seeking, looping and determining duration. - * + * * @return true if stream cache is in use, otherwise false */ - public boolean useStreamCache(){ + public boolean useStreamCache() { return streamCache; } @@ -157,14 +155,14 @@ public int hashCode() { hash = 67 * hash + (this.streamCache ? 1 : 0); return hash; } - + @Override public Class getProcessorType() { return null; } - + @Override - public void write(JmeExporter ex) throws IOException{ + public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); oc.write(stream, "do_stream", false); @@ -172,11 +170,10 @@ public void write(JmeExporter ex) throws IOException{ } @Override - public void read(JmeImporter im) throws IOException{ + public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); stream = ic.readBoolean("do_stream", false); streamCache = ic.readBoolean("use_stream_cache", false); } - } diff --git a/jme3-core/src/main/java/com/jme3/audio/AudioNode.java b/jme3-core/src/main/java/com/jme3/audio/AudioNode.java index d7b6099b13..67ac7cba2f 100644 --- a/jme3-core/src/main/java/com/jme3/audio/AudioNode.java +++ b/jme3-core/src/main/java/com/jme3/audio/AudioNode.java @@ -60,14 +60,14 @@ * play stereo assets. * * The "positional" property of an AudioNode can be set via - * {@link AudioNode#setPositional(boolean) }. + * {@link AudioNode#setPositional(boolean)}. * * @author normenhansen * @author Kirill Vainer */ public class AudioNode extends Node implements AudioSource { - //Version #1 : AudioKey is now stored into "audio_key" instead of "key" + // Version #1 : AudioKey is now stored into "audio_key" instead of "key" public static final int SAVABLE_VERSION = 1; protected boolean loop = false; protected float volume = 1; @@ -137,8 +137,9 @@ public AudioNode(AudioData audioData, AudioKey audioKey) { * Creates a new AudioNode with the given audio file. * @param assetManager The asset manager to use to load the audio file * @param name The filename of the audio file - * @param type The type. If {@link com.jme3.audio.AudioData.DataType}.Stream, the audio will be streamed gradually from disk, - * otherwise it will be buffered ({@link com.jme3.audio.AudioData.DataType}.Buffer) + * @param type The type. If {@link com.jme3.audio.AudioData.DataType}.Stream, + * the audio will be streamed gradually from disk, + * otherwise it will be buffered ({@link com.jme3.audio.AudioData.DataType}.Buffer) */ public AudioNode(AssetManager assetManager, String name, DataType type) { this(assetManager, name, type == DataType.Stream, true); @@ -150,13 +151,14 @@ public AudioNode(AssetManager assetManager, String name, DataType type) { * @param assetManager The asset manager to use to load the audio file * @param name The filename of the audio file * @param stream If true, the audio will be streamed gradually from disk, - * otherwise, it will be buffered. + * otherwise, it will be buffered. * @param streamCache If stream is also true, then this specifies if - * the stream cache is used. When enabled, the audio stream will - * be read entirely but not decoded, allowing features such as - * seeking, looping and determining duration. + * the stream cache is used. When enabled, the audio stream will + * be read entirely but not decoded, allowing features such as + * seeking, looping and determining duration. * - * @deprecated Use {@link AudioNode#AudioNode(com.jme3.asset.AssetManager, java.lang.String, com.jme3.audio.AudioData.DataType)} instead + * @deprecated Use {@link AudioNode#AudioNode(com.jme3.asset.AssetManager, java.lang.String, + * com.jme3.audio.AudioData.DataType)} instead */ @Deprecated public AudioNode(AssetManager assetManager, String name, boolean stream, boolean streamCache) { @@ -170,9 +172,10 @@ public AudioNode(AssetManager assetManager, String name, boolean stream, boolean * @param assetManager The asset manager to use to load the audio file * @param name The filename of the audio file * @param stream If true, the audio will be streamed gradually from disk, - * otherwise, it will be buffered. + * otherwise, it will be buffered. * - * @deprecated Use {@link AudioNode#AudioNode(com.jme3.asset.AssetManager, java.lang.String, com.jme3.audio.AudioData.DataType)} instead + * @deprecated Use {@link AudioNode#AudioNode(com.jme3.asset.AssetManager, java.lang.String, + * com.jme3.audio.AudioData.DataType)} instead */ @Deprecated public AudioNode(AssetManager assetManager, String name, boolean stream) { @@ -198,7 +201,8 @@ public AudioNode(AudioRenderer audioRenderer, AssetManager assetManager, String * * @param assetManager The asset manager to use to load the audio file * @param name The filename of the audio file - * @deprecated Use {@link AudioNode#AudioNode(com.jme3.asset.AssetManager, java.lang.String, com.jme3.audio.AudioData.DataType) } instead + * @deprecated Use {@link AudioNode#AudioNode(com.jme3.asset.AssetManager, java.lang.String, + * com.jme3.audio.AudioData.DataType) } instead */ @Deprecated public AudioNode(AssetManager assetManager, String name) { @@ -207,15 +211,16 @@ public AudioNode(AssetManager assetManager, String name) { protected AudioRenderer getRenderer() { AudioRenderer result = AudioContext.getAudioRenderer(); - if( result == null ) - throw new IllegalStateException( "No audio renderer available, make sure call is being performed on render thread." ); + if (result == null) + throw new IllegalStateException( + "No audio renderer available, make sure call is being performed on render thread."); return result; } /** * Start playing the audio. */ - public void play(){ + public void play() { if (positional && data.getChannels() > 1) { throw new IllegalStateException("Only mono audio is supported for positional audio nodes"); } @@ -228,7 +233,7 @@ public void play(){ * that changes to the parameters of this AudioNode will not affect the * instances already playing. */ - public void playInstance(){ + public void playInstance() { if (positional && data.getChannels() > 1) { throw new IllegalStateException("Only mono audio is supported for positional audio nodes"); } @@ -238,14 +243,14 @@ public void playInstance(){ /** * Stop playing the audio that was started with {@link AudioNode#play() }. */ - public void stop(){ + public void stop() { getRenderer().stopSource(this); } /** * Pause the audio that was started with {@link AudioNode#play() }. */ - public void pause(){ + public void pause() { getRenderer().pauseSource(this); } @@ -454,7 +459,7 @@ public void setTimeOffset(float timeOffset) { this.timeOffset = timeOffset; if (data instanceof AudioStream) { ((AudioStream) data).setTime(timeOffset); - }else if(status == AudioSource.Status.Playing){ + } else if (status == AudioSource.Status.Playing) { stop(); play(); } @@ -602,7 +607,7 @@ public float getRefDistance() { * audio node will be exactly half of its volume. * * @param refDistance The reference playing distance. - * @throws IllegalArgumentException If refDistance is negative + * @throws IllegalArgumentException If refDistance is negative */ public void setRefDistance(float refDistance) { if (refDistance < 0) { @@ -749,12 +754,14 @@ public void updateLogicalState(float tpf) { @Override public void updateGeometricState() { super.updateGeometricState(); - if (channel < 0) return; + if (channel < 0) + return; Vector3f currentWorldTranslation = worldTransform.getTranslation(); if (!previousWorldTranslation.equals(currentWorldTranslation)) { getRenderer().updateSourceParam(this, AudioParam.Position); if (velocityFromTranslation && !Float.isNaN(previousWorldTranslation.x)) { - velocity.set(currentWorldTranslation).subtractLocal(previousWorldTranslation).multLocal(1f / lastTpf); + velocity.set(currentWorldTranslation) + .subtractLocal(previousWorldTranslation).multLocal(1f / lastTpf); getRenderer().updateSourceParam(this, AudioParam.Velocity); } previousWorldTranslation.set(currentWorldTranslation); @@ -762,21 +769,21 @@ public void updateGeometricState() { } @Override - public AudioNode clone(){ + public AudioNode clone() { AudioNode clone = (AudioNode) super.clone(); return clone; } /** - * Called internally by com.jme3.util.clone.Cloner. Do not call directly. + * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { - super.cloneFields(cloner, original); + public void cloneFields(Cloner cloner, Object original) { + super.cloneFields(cloner, original); - this.direction=cloner.clone(direction); - this.velocity=velocityFromTranslation?new Vector3f():cloner.clone(velocity); - this.previousWorldTranslation=Vector3f.NAN.clone(); + this.direction = cloner.clone(direction); + this.velocity = velocityFromTranslation ? new Vector3f() : cloner.clone(velocity); + this.previousWorldTranslation = Vector3f.NAN.clone(); // Change in behavior: the filters were not cloned before meaning // that two cloned audio nodes would share the same filter instance. @@ -826,9 +833,9 @@ public void read(JmeImporter im) throws IOException { // NOTE: In previous versions of jME3, audioKey was actually // written with the name "key". This has been changed // to "audio_key" in case Spatial's key will be written as "key". - if (ic.getSavableVersion(AudioNode.class) == 0){ + if (ic.getSavableVersion(AudioNode.class) == 0) { audioKey = (AudioKey) ic.readSavable("key", null); - }else{ + } else { audioKey = (AudioKey) ic.readSavable("audio_key", null); } @@ -855,8 +862,9 @@ public void read(JmeImporter im) throws IOException { if (audioKey != null) { try { data = im.getAssetManager().loadAsset(audioKey); - } catch (AssetNotFoundException ex){ - Logger.getLogger(AudioNode.class.getName()).log(Level.FINE, "Cannot locate {0} for audio node {1}", new Object[]{audioKey, key}); + } catch (AssetNotFoundException ex) { + Logger.getLogger(AudioNode.class.getName()) + .log(Level.FINE, "Cannot locate {0} for audio node {1}", new Object[]{audioKey, key}); data = PlaceholderAssets.getPlaceholderAudio(); } } diff --git a/jme3-core/src/main/java/com/jme3/audio/Environment.java b/jme3-core/src/main/java/com/jme3/audio/Environment.java index 72327ef00c..7cb5485aca 100644 --- a/jme3-core/src/main/java/com/jme3/audio/Environment.java +++ b/jme3-core/src/main/java/com/jme3/audio/Environment.java @@ -69,12 +69,12 @@ public class Environment { Closet = new Environment(1, 1, 1, 1, .15f, 1, .6f, .0025f, .5f, .0006f); } - private static float eaxDbToAmp(float eaxDb){ + private static float eaxDbToAmp(float eaxDb) { float dB = eaxDb / 2000f; return FastMath.pow(10f, dB); } - public Environment(){ + public Environment() { } public Environment(Environment source) { @@ -95,7 +95,7 @@ public Environment(Environment source) { public Environment(float density, float diffusion, float gain, float gainHf, float decayTime, float decayHf, float reflGain, - float reflDelay, float lateGain, float lateDelay){ + float reflDelay, float lateGain, float lateDelay) { this.decayTime = decayTime; this.decayHFRatio = decayHf; this.density = density; @@ -108,7 +108,7 @@ public Environment(float density, float diffusion, float gain, float gainHf, this.reflectGain = reflGain; } - public Environment(float[] e){ + public Environment(float[] e) { if (e.length != 28) throw new IllegalArgumentException("Not an EAX preset"); diff --git a/jme3-core/src/main/java/com/jme3/audio/Filter.java b/jme3-core/src/main/java/com/jme3/audio/Filter.java index 9faa1f051b..83bc99e753 100644 --- a/jme3-core/src/main/java/com/jme3/audio/Filter.java +++ b/jme3-core/src/main/java/com/jme3/audio/Filter.java @@ -39,14 +39,14 @@ public abstract class Filter extends NativeObject implements Savable { - public Filter(){ + public Filter() { super(); } - - protected Filter(int id){ + + protected Filter(int id) { super(id); } - + @Override public void write(JmeExporter ex) throws IOException { // nothing to save @@ -65,7 +65,7 @@ public void resetObject() { @Override public void deleteObject(Object rendererObject) { - ((AudioRenderer)rendererObject).deleteFilter(this); + ((AudioRenderer) rendererObject).deleteFilter(this); } @Override diff --git a/jme3-core/src/main/java/com/jme3/audio/Listener.java b/jme3-core/src/main/java/com/jme3/audio/Listener.java index afd08a7303..5ef28b4f09 100644 --- a/jme3-core/src/main/java/com/jme3/audio/Listener.java +++ b/jme3-core/src/main/java/com/jme3/audio/Listener.java @@ -42,20 +42,20 @@ public class Listener { private float volume = 1; private AudioRenderer renderer; - public Listener(){ + public Listener() { location = new Vector3f(); velocity = new Vector3f(); rotation = new Quaternion(); } - - public Listener(Listener source){ + + public Listener(Listener source) { location = source.location.clone(); velocity = source.velocity.clone(); rotation = source.rotation.clone(); volume = source.volume; } - public void setRenderer(AudioRenderer renderer){ + public void setRenderer(AudioRenderer renderer) { this.renderer = renderer; } @@ -68,7 +68,7 @@ public void setVolume(float volume) { if (renderer != null) renderer.updateListenerParam(this, ListenerParam.Volume); } - + public Vector3f getLocation() { return location; } @@ -81,18 +81,18 @@ public Vector3f getVelocity() { return velocity; } - public Vector3f getLeft(){ + public Vector3f getLeft() { return rotation.getRotationColumn(0); } - public Vector3f getUp(){ + public Vector3f getUp() { return rotation.getRotationColumn(1); } - public Vector3f getDirection(){ + public Vector3f getDirection() { return rotation.getRotationColumn(2); } - + public void setLocation(Vector3f location) { this.location.set(location); if (renderer != null) diff --git a/jme3-core/src/main/java/com/jme3/audio/LowPassFilter.java b/jme3-core/src/main/java/com/jme3/audio/LowPassFilter.java index 8ce385773c..aaf1f5b69b 100644 --- a/jme3-core/src/main/java/com/jme3/audio/LowPassFilter.java +++ b/jme3-core/src/main/java/com/jme3/audio/LowPassFilter.java @@ -47,8 +47,8 @@ public LowPassFilter(float volume, float highFreqVolume) { setVolume(volume); setHighFreqVolume(highFreqVolume); } - - protected LowPassFilter(int id){ + + protected LowPassFilter(int id) { super(id); } @@ -71,13 +71,13 @@ public float getVolume() { public void setVolume(float volume) { if (volume < 0 || volume > 1) throw new IllegalArgumentException("Volume must be between 0 and 1"); - + this.volume = volume; this.updateNeeded = true; } @Override - public void write(JmeExporter ex) throws IOException{ + public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); oc.write(volume, "volume", 0); @@ -85,7 +85,7 @@ public void write(JmeExporter ex) throws IOException{ } @Override - public void read(JmeImporter im) throws IOException{ + public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); volume = ic.readFloat("volume", 0); @@ -99,6 +99,6 @@ public NativeObject createDestructableClone() { @Override public long getUniqueId() { - return ((long)OBJTYPE_FILTER << 32) | ((long)id); + return ((long) OBJTYPE_FILTER << 32) | ((long) id); } } diff --git a/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java b/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java index 29ce483aca..a0f1bdb3ab 100644 --- a/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java +++ b/jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java @@ -47,9 +47,9 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { private static final Logger logger = Logger.getLogger(ALAudioRenderer.class.getName()); - + private static final String THREAD_NAME = "jME3 Audio Decoder"; - + private final NativeObjectManager objManager = new NativeObjectManager(); // When multiplied by STREAMING_BUFFER_COUNT, will equal 44100 * 2 * 2 // which is exactly 1 second of audio. @@ -72,7 +72,7 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { private int auxSends = 0; private int reverbFx = -1; private int reverbFxSlot = -1; - + // Fill streaming sources every 50 ms private static final float UPDATE_RATE = 0.05f; private final Thread decoderThread = new Thread(this, THREAD_NAME); @@ -81,13 +81,13 @@ public class ALAudioRenderer implements AudioRenderer, Runnable { private final AL al; private final ALC alc; private final EFX efx; - + public ALAudioRenderer(AL al, ALC alc, EFX efx) { this.al = al; this.alc = alc; this.efx = efx; } - + private void initOpenAL() { try { if (!alc.isCreated()) { @@ -120,15 +120,15 @@ private void initOpenAL() { final String deviceName = alc.alcGetString(ALC.ALC_DEVICE_SPECIFIER); - logger.log(Level.INFO, "Audio Renderer Information\n" + - " * Device: {0}\n" + - " * Vendor: {1}\n" + - " * Renderer: {2}\n" + - " * Version: {3}\n" + - " * Supported channels: {4}\n" + - " * ALC extensions: {5}\n" + - " * AL extensions: {6}", - new Object[]{ + logger.log(Level.INFO, "Audio Renderer Information\n" + + " * Device: {0}\n" + + " * Vendor: {1}\n" + + " * Renderer: {2}\n" + + " * Version: {3}\n" + + " * Supported channels: {4}\n" + + " * ALC extensions: {5}\n" + + " * AL extensions: {6}", + new Object[] { deviceName, al.alGetString(AL_VENDOR), al.alGetString(AL_RENDERER), @@ -181,7 +181,7 @@ private void initOpenAL() { logger.log(Level.WARNING, "OpenAL EFX not available! Audio effects won't work."); } } - + private void destroyOpenAL() { if (audioDisabled) { alc.destroyALC(); @@ -224,7 +224,7 @@ public void initialize() { if (decoderThread.isAlive()) { throw new IllegalStateException("Initialize already called"); } - + // Initialize OpenAL context. initOpenAL(); @@ -279,13 +279,13 @@ public void cleanup() { if (!decoderThread.isAlive()) { return; } - + decoderThread.interrupt(); try { decoderThread.join(); } catch (InterruptedException ex) { } - + // destroy OpenAL context destroyOpenAL(); } @@ -321,51 +321,51 @@ public float getSourcePlaybackTime(AudioSource src) { if (audioDisabled) { return 0; } - + // See comment in updateSourceParam(). if (src.getChannel() < 0) { return 0; } - + int id = channels[src.getChannel()]; AudioData data = src.getAudioData(); int playbackOffsetBytes = 0; - + if (data instanceof AudioStream) { - // Because audio streams are processed in buffer chunks, + // Because audio streams are processed in buffer chunks, // we have to compute the amount of time the stream was already // been playing based on the number of buffers that were processed. AudioStream stream = (AudioStream) data; - + // NOTE: the assumption is that all enqueued buffers are the same size. // this is currently enforced by fillBuffer(). - + // The number of unenqueued bytes that the decoder thread // keeps track of. int unqueuedBytes = stream.getUnqueuedBufferBytes(); - + // Additional processed buffers that the decoder thread // did not unenqueue yet (it only updates 20 times per second). int unqueuedBytesExtra = al.alGetSourcei(id, AL_BUFFERS_PROCESSED) * BUFFER_SIZE; - + // Total additional bytes that need to be considered. playbackOffsetBytes = unqueuedBytes; // + unqueuedBytesExtra; } - + // Add byte offset from source (for both streams and buffers) playbackOffsetBytes += al.alGetSourcei(id, AL_BYTE_OFFSET); - + // Compute time value from bytes // E.g. for 44100 source with 2 channels and 16 bits per sample: // (44100 * 2 * 16 / 8) = 176400 - int bytesPerSecond = (data.getSampleRate() * - data.getChannels() * - data.getBitsPerSample() / 8); - - return (float)playbackOffsetBytes / bytesPerSecond; + int bytesPerSecond = (data.getSampleRate() + * data.getChannels() + * data.getBitsPerSample() / 8); + + return (float) playbackOffsetBytes / bytesPerSecond; } } - + @Override public void updateSourceParam(AudioSource src, AudioParam param) { checkDead(); @@ -381,7 +381,7 @@ public void updateSourceParam(AudioSource src, AudioParam param) { // still has a channel value but the audio thread may // clear that channel before setVolume() gets to call // updateSourceParam() (because the audio stopped playing - // on its own right as the volume was set). In this case, + // on its own right as the volume was set). In this case, // it should be safe to just ignore the update. if (src.getChannel() < 0) { return; @@ -453,7 +453,7 @@ public void updateSourceParam(AudioSource src, AudioParam param) { al.alSourcei(id, AL_SOURCE_RELATIVE, AL_TRUE); al.alSource3f(id, AL_POSITION, 0, 0, 0); al.alSource3f(id, AL_VELOCITY, 0, 0, 0); - + // Disable reverb al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX.AL_FILTER_NULL); } else { @@ -717,34 +717,34 @@ private boolean fillStreamingSource(int sourceId, AudioStream stream, boolean lo boolean success = false; int processed = al.alGetSourcei(sourceId, AL_BUFFERS_PROCESSED); int unqueuedBufferBytes = 0; - + for (int i = 0; i < processed; i++) { int buffer; ib.position(0).limit(1); al.alSourceUnqueueBuffers(sourceId, 1, ib); buffer = ib.get(0); - - // XXX: assume that reading from AudioStream always + + // XXX: assume that reading from AudioStream always // gives BUFFER_SIZE amount of bytes! This might not always // be the case... unqueuedBufferBytes += BUFFER_SIZE; - + boolean active = fillBuffer(stream, buffer); - + if (!active && !stream.isEOF()) { throw new AssertionError(); } - + if (!active && looping) { stream.setTime(0); active = fillBuffer(stream, buffer); if (!active) { - throw new IllegalStateException("Looping streaming source " + - "was rewound but could not be filled"); + throw new IllegalStateException("Looping streaming source " + + "was rewound but could not be filled"); } } - + if (active) { ib.position(0).limit(1); ib.put(0, buffer); @@ -756,7 +756,7 @@ private boolean fillStreamingSource(int sourceId, AudioStream stream, boolean lo break; } } - + stream.setUnqueuedBufferBytes(stream.getUnqueuedBufferBytes() + unqueuedBufferBytes); return success; @@ -764,15 +764,15 @@ private boolean fillStreamingSource(int sourceId, AudioStream stream, boolean lo private void attachStreamToSource(int sourceId, AudioStream stream, boolean looping) { boolean success = false; - - // Reset the stream. Typically happens if it finished playing on - // its own and got reclaimed. + + // Reset the stream. Typically happens if it finished playing on + // its own and got reclaimed. // Note that AudioNode.stop() already resets the stream // since it might not be at the EOF when stopped. if (stream.isEOF()) { stream.setTime(0); } - + for (int id : stream.getIds()) { boolean active = fillBuffer(stream, id); if (!active && !stream.isEOF()) { @@ -782,8 +782,8 @@ private void attachStreamToSource(int sourceId, AudioStream stream, boolean loop stream.setTime(0); active = fillBuffer(stream, id); if (!active) { - throw new IllegalStateException("Looping streaming source " + - "was rewound but could not be filled"); + throw new IllegalStateException("Looping streaming source " + + "was rewound but could not be filled"); } } if (active) { @@ -793,7 +793,7 @@ private void attachStreamToSource(int sourceId, AudioStream stream, boolean loop success = true; } } - + if (!success) { // should never happen throw new IllegalStateException("No valid data could be read from stream"); @@ -822,7 +822,7 @@ private void clearChannel(int index) { int sourceId = channels[index]; al.alSourceStop(sourceId); - + // For streaming sources, this will clear all queued buffers. al.alSourcei(sourceId, AL_BUFFER, 0); @@ -840,7 +840,7 @@ private void clearChannel(int index) { chanSrcs[index] = null; } } - + private AudioSource.Status convertStatus(int oalStatus) { switch (oalStatus) { case AL_INITIAL: @@ -889,10 +889,10 @@ public void updateInRenderThread(float tpf) { if (audioDisabled) { return; } - + for (int i = 0; i < channels.length; i++) { AudioSource src = chanSrcs[i]; - + if (src == null) { continue; } @@ -900,11 +900,11 @@ public void updateInRenderThread(float tpf) { int sourceId = channels[i]; boolean boundSource = i == src.getChannel(); boolean reclaimChannel = false; - + Status oalStatus = convertStatus(al.alGetSourcei(sourceId, AL_SOURCE_STATE)); - + if (!boundSource) { - // Rules for instanced playback vary significantly. + // Rules for instanced playback vary significantly. // Handle it here. if (oalStatus == Status.Stopped) { // Instanced audio stopped playing. Reclaim channel. @@ -913,26 +913,26 @@ public void updateInRenderThread(float tpf) { } else if (oalStatus == Status.Paused) { throw new AssertionError("Instanced audio cannot be paused"); } - + continue; } - + Status jmeStatus = src.getStatus(); - + // Check if we need to sync JME status with OAL status. if (oalStatus != jmeStatus) { if (oalStatus == Status.Stopped && jmeStatus == Status.Playing) { // Maybe we need to reclaim the channel. if (src.getAudioData() instanceof AudioStream) { AudioStream stream = (AudioStream) src.getAudioData(); - + if (stream.isEOF() && !src.isLooping()) { // Stream finished playing reclaimChannel = true; } else { - // Stream still has data. + // Stream still has data. // Buffer starvation occurred. - // Audio decoder thread will fill the data + // Audio decoder thread will fill the data // and start the channel again. } } else { @@ -945,7 +945,7 @@ public void updateInRenderThread(float tpf) { reclaimChannel = true; } - + if (reclaimChannel) { src.setStatus(Status.Stopped); src.setChannel(-1); @@ -956,7 +956,7 @@ public void updateInRenderThread(float tpf) { // jME3 state does not match OAL state. // This is only relevant for bound sources. throw new AssertionError("Unexpected sound status. " - + "OAL: " + oalStatus + + "OAL: " + oalStatus + ", JME: " + jmeStatus); } } else { @@ -967,7 +967,7 @@ public void updateInRenderThread(float tpf) { } } } - + public void updateInDecoderThread(float tpf) { if (audioDisabled) { return; @@ -975,7 +975,7 @@ public void updateInDecoderThread(float tpf) { for (int i = 0; i < channels.length; i++) { AudioSource src = chanSrcs[i]; - + if (src == null || !(src.getAudioData() instanceof AudioStream)) { continue; } @@ -1030,13 +1030,13 @@ public void setListener(Listener listener) { setListenerParams(listener); } } - + @Override public void pauseAll() { if (!supportPauseDevice) { throw new UnsupportedOperationException("Pause device is NOT supported!"); } - + alc.alcDevicePauseSOFT(); } @@ -1045,7 +1045,7 @@ public void resumeAll() { if (!supportPauseDevice) { throw new UnsupportedOperationException("Pause device is NOT supported!"); } - + alc.alcDeviceResumeSOFT(); } @@ -1101,7 +1101,7 @@ public void playSource(AudioSource src) { // Assertion removed because it seems it's not possible to have // something different from -1 when first playing an AudioNode. // assert src.getChannel() != -1; - + // allocate channel to this source int index = newChannel(); if (index == -1) { @@ -1158,11 +1158,11 @@ public void stopSource(AudioSource src) { src.setChannel(-1); clearChannel(chan); freeChannel(chan); - + if (src.getAudioData() instanceof AudioStream) { // If the stream is seekable, then rewind it. // Otherwise, close it, as it is no longer valid. - AudioStream stream = (AudioStream)src.getAudioData(); + AudioStream stream = (AudioStream) src.getAudioData(); if (stream.isSeekable()) { stream.setTime(0); } else { diff --git a/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java b/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java index daa2952099..5b46846a23 100644 --- a/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java +++ b/jme3-core/src/main/java/com/jme3/bounding/BoundingSphere.java @@ -177,9 +177,9 @@ public void computeFromTris(Triangle[] tris, int start, int end) { * Calculates a minimum bounding sphere for the set of points. The algorithm * was originally found in C++ at
    * - * http://flipcode.com/archives/Smallest_Enclosing_Spheres.shtml
    + * http://flipcode.com/archives/Smallest_Enclosing_Spheres.shtml
    * and translated to java by Cep21 - * + * * @param points * The points to calculate the minimum bounds from. */ @@ -812,39 +812,39 @@ private int collideWithRay(Ray ray) { } return 1; } - + private int collideWithTri(Triangle tri, CollisionResults results) { TempVars tvars = TempVars.get(); try { - + // Much of this is based on adaptation from this algorithm: // http://realtimecollisiondetection.net/blog/?p=103 // ...mostly the stuff about eliminating sqrts wherever // possible. - + // Math is done in center-relative space. Vector3f a = tri.get1().subtract(center, tvars.vect1); Vector3f b = tri.get2().subtract(center, tvars.vect2); Vector3f c = tri.get3().subtract(center, tvars.vect3); - + Vector3f ab = b.subtract(a, tvars.vect4); Vector3f ac = c.subtract(a, tvars.vect5); - + // Check the plane... if it doesn't intersect the plane // then it doesn't intersect the triangle. Vector3f n = ab.cross(ac, tvars.vect6); float d = a.dot(n); - float e = n.dot(n); - if( d * d > radius * radius * e ) { + float e = n.dot(n); + if (d * d > radius * radius * e) { // Can't possibly intersect return 0; } - + // We intersect the verts, or the edges, or the face... - + // First check against the face since it's the most // specific. - + // Calculate the barycentric coordinates of the // sphere center Vector3f v0 = ac; @@ -852,163 +852,163 @@ private int collideWithTri(Triangle tri, CollisionResults results) { // a was P relative, so p.subtract(a) is just -a // instead of wasting a vector we'll just negate the // dot products below... it's all v2 is used for. - Vector3f v2 = a; - + Vector3f v2 = a; + float dot00 = v0.dot(v0); float dot01 = v0.dot(v1); float dot02 = -v0.dot(v2); float dot11 = v1.dot(v1); float dot12 = -v1.dot(v2); - + float invDenom = 1 / (dot00 * dot11 - dot01 * dot01); float u = (dot11 * dot02 - dot01 * dot12) * invDenom; float v = (dot00 * dot12 - dot01 * dot02) * invDenom; - - if( u >= 0 && v >= 0 && (u + v) <= 1 ) { + + if (u >= 0 && v >= 0 && (u + v) <= 1) { // We intersect... and we even know where Vector3f part1 = ac; Vector3f part2 = ab; - Vector3f p = center.add(a.add(part1.mult(u)).addLocal(part2.mult(v))); - + Vector3f p = center.add(a.add(part1.mult(u)).addLocal(part2.mult(v))); + CollisionResult r = new CollisionResult(); - Vector3f normal = n.normalize(); + Vector3f normal = n.normalize(); float dist = -normal.dot(a); // a is center relative, so -a points to center dist = dist - radius; - + r.setDistance(dist); r.setContactNormal(normal); r.setContactPoint(p); results.addCollision(r); return 1; } - + // Check the edges looking for the nearest point // that is also less than the radius. We don't care // about points that are farther away than that. Vector3f nearestPt = null; - float nearestDist = radius * radius; - + float nearestDist = radius * radius; + Vector3f base; Vector3f edge; float t; - + // Edge AB base = a; - edge = ab; - + edge = ab; + t = -edge.dot(base) / edge.dot(edge); - if( t >= 0 && t <= 1 ) { + if (t >= 0 && t <= 1) { Vector3f Q = base.add(edge.mult(t, tvars.vect7), tvars.vect8); float distSq = Q.dot(Q); // distance squared to origin - if( distSq < nearestDist ) { + if (distSq < nearestDist) { nearestPt = Q; nearestDist = distSq; } } - + // Edge AC base = a; edge = ac; - + t = -edge.dot(base) / edge.dot(edge); - if( t >= 0 && t <= 1 ) { + if (t >= 0 && t <= 1) { Vector3f Q = base.add(edge.mult(t, tvars.vect7), tvars.vect9); float distSq = Q.dot(Q); // distance squared to origin - if( distSq < nearestDist ) { + if (distSq < nearestDist) { nearestPt = Q; nearestDist = distSq; } } - + // Edge BC base = b; - Vector3f bc = c.subtract(b); - edge = bc; - + Vector3f bc = c.subtract(b); + edge = bc; + t = -edge.dot(base) / edge.dot(edge); - if( t >= 0 && t <= 1 ) { + if (t >= 0 && t <= 1) { Vector3f Q = base.add(edge.mult(t, tvars.vect7), tvars.vect10); float distSq = Q.dot(Q); // distance squared to origin - if( distSq < nearestDist ) { + if (distSq < nearestDist) { nearestPt = Q; nearestDist = distSq; } } - + // If we have a point at all then it is going to be // closer than any vertex to center distance... so we're - // done. - if( nearestPt != null ) { + // done. + if (nearestPt != null) { // We have a hit float dist = FastMath.sqrt(nearestDist); Vector3f cn = nearestPt.divide(-dist); - - CollisionResult r = new CollisionResult(); + + CollisionResult r = new CollisionResult(); r.setDistance(dist - radius); r.setContactNormal(cn); r.setContactPoint(nearestPt.add(center)); results.addCollision(r); - - return 1; + + return 1; } - + // Finally, check each of the triangle corners. - + // Vert A base = a; t = base.dot(base); // distance squared to origin - if( t < nearestDist ) { + if (t < nearestDist) { nearestDist = t; nearestPt = base; } - + // Vert B base = b; t = base.dot(base); // distance squared to origin - if( t < nearestDist ) { + if (t < nearestDist) { nearestDist = t; nearestPt = base; } - + // Vert C base = c; t = base.dot(base); // distance squared to origin - if( t < nearestDist ) { + if (t < nearestDist) { nearestDist = t; nearestPt = base; } - - if( nearestPt != null ) { + + if (nearestPt != null) { // We have a hit float dist = FastMath.sqrt(nearestDist); Vector3f cn = nearestPt.divide(-dist); - - CollisionResult r = new CollisionResult(); + + CollisionResult r = new CollisionResult(); r.setDistance(dist - radius); r.setContactNormal(cn); r.setContactPoint(nearestPt.add(center)); results.addCollision(r); - - return 1; + + return 1; } - - // Nothing hit... oh, well + + // Nothing hit... oh, well return 0; } finally { tvars.release(); } } - + @Override public int collideWith(Collidable other, CollisionResults results) { if (other instanceof Ray) { Ray ray = (Ray) other; return collideWithRay(ray, results); - } else if (other instanceof Triangle){ + } else if (other instanceof Triangle) { Triangle t = (Triangle) other; return collideWithTri(t, results); } else if (other instanceof BoundingVolume) { - if (intersects((BoundingVolume)other)) { + if (intersects((BoundingVolume) other)) { CollisionResult result = new CollisionResult(); results.addCollision(result); return 1; @@ -1026,16 +1026,15 @@ public int collideWith(Collidable other) { if (other instanceof Ray) { Ray ray = (Ray) other; return collideWithRay(ray); - } else if (other instanceof Triangle){ + } else if (other instanceof Triangle) { return super.collideWith(other); } else if (other instanceof BoundingVolume) { - return intersects((BoundingVolume)other) ? 1 : 0; + return intersects((BoundingVolume) other) ? 1 : 0; } else { throw new UnsupportedCollisionException(); } } - @Override public boolean contains(Vector3f point) { return center.distanceSquared(point) < (getRadius() * getRadius()); @@ -1075,4 +1074,4 @@ public void read(JmeImporter importer) throws IOException { public float getVolume() { return 4 * FastMath.ONE_THIRD * FastMath.PI * radius * radius * radius; } -} \ No newline at end of file +} diff --git a/jme3-core/src/main/java/com/jme3/bounding/Intersection.java b/jme3-core/src/main/java/com/jme3/bounding/Intersection.java index 50aaf4fcb3..bf7b056244 100644 --- a/jme3-core/src/main/java/com/jme3/bounding/Intersection.java +++ b/jme3-core/src/main/java/com/jme3/bounding/Intersection.java @@ -42,7 +42,7 @@ /** * This class includes some utility methods for computing intersection * between bounding volumes and triangles. - * + * * @author Kirill */ public final class Intersection { @@ -62,36 +62,40 @@ public static boolean intersect(BoundingSphere sphere, Vector3f center, float ra vars.release(); } } - + public static boolean intersect(BoundingBox bbox, Vector3f center, float radius) { assert Vector3f.isValidVector(center) && Vector3f.isValidVector(bbox.center); - // Arvo's algorithm + // Arvo's algorithm float distSqr = radius * radius; - + float minX = bbox.center.x - bbox.xExtent; float maxX = bbox.center.x + bbox.xExtent; - + float minY = bbox.center.y - bbox.yExtent; float maxY = bbox.center.y + bbox.yExtent; - + float minZ = bbox.center.z - bbox.zExtent; float maxZ = bbox.center.z + bbox.zExtent; - - if (center.x < minX) distSqr -= FastMath.sqr(center.x - minX); - else if (center.x > maxX) distSqr -= FastMath.sqr(center.x - maxX); - - - if (center.y < minY) distSqr -= FastMath.sqr(center.y - minY); - else if (center.y > maxY) distSqr -= FastMath.sqr(center.y - maxY); - - - if (center.z < minZ) distSqr -= FastMath.sqr(center.z - minZ); - else if (center.z > maxZ) distSqr -= FastMath.sqr(center.z - maxZ); - + + if (center.x < minX) + distSqr -= FastMath.sqr(center.x - minX); + else if (center.x > maxX) + distSqr -= FastMath.sqr(center.x - maxX); + + if (center.y < minY) + distSqr -= FastMath.sqr(center.y - minY); + else if (center.y > maxY) + distSqr -= FastMath.sqr(center.y - maxY); + + if (center.z < minZ) + distSqr -= FastMath.sqr(center.z - minZ); + else if (center.z > maxZ) + distSqr -= FastMath.sqr(center.z - maxZ); + return distSqr > 0; } - + private static final void findMinMax(float x0, float x1, float x2, Vector3f minMax) { minMax.set(x0, x0, 0); if (x1 < minMax.x) { @@ -108,7 +112,7 @@ private static final void findMinMax(float x0, float x1, float x2, Vector3f minM } } - public static boolean intersect(Camera camera, Vector3f center,float radius){ + public static boolean intersect(Camera camera, Vector3f center, float radius) { for (int i = 5; i >= 0; i--) { if (camera.getWorldPlane(i).pseudoDistance(center) <= -radius) { return false; @@ -145,7 +149,6 @@ public static boolean intersect(BoundingBox bbox, Vector3f v1, Vector3f v2, Vect TempVars vars = TempVars.get(); - Vector3f tmp0 = vars.vect1, tmp1 = vars.vect2, tmp2 = vars.vect3; @@ -179,8 +182,6 @@ public static boolean intersect(BoundingBox bbox, Vector3f v1, Vector3f v2, Vect float fey = FastMath.abs(e0.y); float fez = FastMath.abs(e0.z); - - //AXISTEST_X01(e0[Z], e0[Y], fez, fey); p0 = e0.z * tmp0.y - e0.y * tmp0.z; p2 = e0.z * tmp2.y - e0.y * tmp2.z; @@ -294,7 +295,6 @@ public static boolean intersect(BoundingBox bbox, Vector3f v1, Vector3f v2, Vect // that direction -- this is equivalent to testing a minimal AABB around // the triangle against the AABB - Vector3f minMax = vars.vect7; // test in X-direction diff --git a/jme3-core/src/main/java/com/jme3/cinematic/Cinematic.java b/jme3-core/src/main/java/com/jme3/cinematic/Cinematic.java index 92e787fe9a..b03850c255 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/Cinematic.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/Cinematic.java @@ -277,8 +277,8 @@ public void initialize(AppStateManager stateManager, Application app) { for (CinematicEvent cinematicEvent : cinematicEvents) { cinematicEvent.initEvent(app, this); } - if(!cameras.isEmpty()){ - for(CameraNode n : cameras.values()){ + if (!cameras.isEmpty()) { + for (CameraNode n : cameras.values()) { n.setCamera(app.getCamera()); } } @@ -302,7 +302,7 @@ public boolean isInitialized() { * * @param id the desired ID */ - protected void setId( String id ) { + protected void setId(String id) { this.id = id; } @@ -405,7 +405,7 @@ public void setTime(float time) { super.setTime(time); int keyFrameIndex = timeLine.getKeyFrameIndexFromTime(time); - //triggering all the event from start to "time" + //triggering all the event from start to "time" //then computing timeOffset for each event for (int i = 0; i <= keyFrameIndex; i++) { KeyFrame keyFrame = timeLine.get(i); @@ -697,8 +697,8 @@ public void removeEventData(String type, Object key) { */ public void setScene(Node scene) { this.scene = scene; - if(!cameras.isEmpty()){ - for(CameraNode n : cameras.values()){ + if (!cameras.isEmpty()) { + for (CameraNode n : cameras.values()) { this.scene.attachChild(n); } } diff --git a/jme3-core/src/main/java/com/jme3/cinematic/KeyFrame.java b/jme3-core/src/main/java/com/jme3/cinematic/KeyFrame.java index d217f3e33e..55dab48f52 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/KeyFrame.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/KeyFrame.java @@ -43,10 +43,9 @@ */ public class KeyFrame implements Savable { - public KeyFrame(){ - + public KeyFrame() { } - + List cinematicEvents = new ArrayList<>(); private int index; @@ -64,8 +63,8 @@ public List trigger() { } return cinematicEvents; } - - public boolean isEmpty(){ + + public boolean isEmpty() { return cinematicEvents.isEmpty(); } @@ -81,7 +80,7 @@ public void write(JmeExporter ex) throws IOException { public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); cinematicEvents = ic.readSavableArrayList("cinematicEvents", null); - index=ic.readInt("index", 0); + index = ic.readInt("index", 0); } public int getIndex() { @@ -91,6 +90,4 @@ public int getIndex() { public void setIndex(int index) { this.index = index; } - - } diff --git a/jme3-core/src/main/java/com/jme3/cinematic/MotionPath.java b/jme3-core/src/main/java/com/jme3/cinematic/MotionPath.java index f455c42416..7a139a43a4 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/MotionPath.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/MotionPath.java @@ -69,7 +69,7 @@ public MotionPath() { } /** - * interpolate the path giving the time since the beginning and the motionControl + * interpolate the path giving the time since the beginning and the motionControl * this methods sets the new localTranslation to the spatial of the MotionEvent control. * @param time the time since the animation started * @param control the control over the moving spatial @@ -87,7 +87,7 @@ public float interpolatePath(float time, MotionEvent control, float tpf) { traveledDistance = time * (getLength() / control.getInitialDuration()); //getting waypoint index and current value from new traveled distance - v = getWayPointIndexForDistance(traveledDistance,v); + v = getWayPointIndexForDistance(traveledDistance, v); //setting values control.setCurrentWayPoint((int) v.x); @@ -108,7 +108,7 @@ public float interpolatePath(float time, MotionEvent control, float tpf) { public void checkWayPoint(MotionEvent control, float tpf) { //Epsilon varies with the tpf to avoid missing a waypoint on low framerate. - float epsilon = tpf * 4f; + float epsilon = tpf * 4f; if (control.getCurrentWayPoint() != prevWayPoint) { if (control.getCurrentValue() >= 0f && control.getCurrentValue() < epsilon) { triggerWayPointReach(control.getCurrentWayPoint(), control); @@ -175,7 +175,6 @@ public void write(JmeExporter ex) throws IOException { public void read(JmeImporter im) throws IOException { InputCapsule in = im.getCapsule(this); spline = (Spline) in.readSavable("spline", null); - } /** @@ -187,7 +186,7 @@ public void read(JmeImporter im) throws IOException { */ public Vector2f getWayPointIndexForDistance(float distance, Vector2f store) { float sum = 0; - if(spline.getTotalLength() == 0){ + if (spline.getTotalLength() == 0) { store.set(0, 0); return store; } diff --git a/jme3-core/src/main/java/com/jme3/cinematic/TimeLine.java b/jme3-core/src/main/java/com/jme3/cinematic/TimeLine.java index 40bc538b3d..b6faaf27aa 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/TimeLine.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/TimeLine.java @@ -81,8 +81,6 @@ public void removeKeyFrame(int keyFrameIndex) { } } } - - public void removeKeyFrame(float time) { removeKeyFrame(getKeyFrameIndexFromTime(time)); @@ -91,9 +89,9 @@ public void removeKeyFrame(float time) { public int getKeyFrameIndexFromTime(float time) { return Math.round(time * keyFramesPerSeconds); } - + public float getKeyFrameTime(KeyFrame keyFrame) { - return keyFrame.getIndex()/(float)keyFramesPerSeconds; + return keyFrame.getIndex() / (float) keyFramesPerSeconds; } public Collection getAllKeyFrames() { diff --git a/jme3-core/src/main/java/com/jme3/cinematic/events/AbstractCinematicEvent.java b/jme3-core/src/main/java/com/jme3/cinematic/events/AbstractCinematicEvent.java index 59d870d091..85bae7c857 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/events/AbstractCinematicEvent.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/events/AbstractCinematicEvent.java @@ -47,8 +47,8 @@ /** * This call contains the basic behavior of a cinematic event. * Every cinematic event must extend this class. - * - * A cinematic event must be given an initial duration in seconds + * + * A cinematic event must be given an initial duration in seconds * (duration of the event at speed = 1). Default is 10 sec. * @author Nehon */ @@ -60,7 +60,7 @@ public abstract class AbstractCinematicEvent implements CinematicEvent { protected float speed = 1; protected float time = 0; protected boolean resuming = false; - + /** * The list of listeners. */ @@ -100,15 +100,15 @@ public AbstractCinematicEvent(float initialDuration, LoopMode loopMode) { this.initialDuration = initialDuration; this.loopMode = loopMode; } - + /** - * Implement this method if the event needs different handling when + * Implement this method if the event needs different handling when * stopped naturally (when the event reach its end), * or when it was force-stopped during playback. * By default, this method just calls regular stop(). */ @Override - public void forceStop(){ + public void forceStop() { stop(); } @@ -117,7 +117,7 @@ public void forceStop(){ */ @Override public void play() { - onPlay(); + onPlay(); playState = PlayState.Playing; if (listeners != null) { for (int i = 0; i < listeners.size(); i++) { @@ -139,17 +139,17 @@ public void play() { @Override public void internalUpdate(float tpf) { if (playState == PlayState.Playing) { - time = time + (tpf * speed); + time = time + (tpf * speed); onUpdate(tpf); if (time >= initialDuration && loopMode == LoopMode.DontLoop) { stop(); - } else if(time >= initialDuration && loopMode == LoopMode.Loop){ + } else if (time >= initialDuration && loopMode == LoopMode.Loop) { setTime(0); - }else{ + } else { time = AnimationUtils.clampWrapTime(time, initialDuration, loopMode); - if(time<0){ - speed = - speed; - time = - time; + if (time < 0) { + speed = -speed; + time = -time; } } } @@ -157,14 +157,14 @@ public void internalUpdate(float tpf) { } /** - * Implement this method with the code that you want to execute on update + * Implement this method with the code that you want to execute on update * (only called when the event is playing). * @param tpf time per frame */ protected abstract void onUpdate(float tpf); /** - * Stops the animation. + * Stops the animation. * Next time when play() is called, the animation starts from the beginning. */ @Override @@ -322,7 +322,7 @@ public void initEvent(Application app, Cinematic cinematic) { /** * Returns the list of CinematicEventListeners added to this event. - * @return + * @return */ private List getListeners() { if (listeners == null) { @@ -356,7 +356,7 @@ public void removeListener(CinematicEventListener listener) { */ @Override public void setTime(float time) { - this.time = time ; + this.time = time; } /** @@ -368,8 +368,6 @@ public float getTime() { } @Override - public void dispose() { + public void dispose() { } - - } diff --git a/jme3-core/src/main/java/com/jme3/cinematic/events/AnimationEvent.java b/jme3-core/src/main/java/com/jme3/cinematic/events/AnimationEvent.java index e388ee503f..6511da701b 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/events/AnimationEvent.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/events/AnimationEvent.java @@ -56,7 +56,7 @@ @Deprecated public class AnimationEvent extends AbstractCinematicEvent { - // Version #2: directly keeping track on the model instead of trying to retrieve + // Version #2: directly keeping track on the model instead of trying to retrieve //it from the scene according to its name, because the name is not supposed to be unique //For backward compatibility, if the model is null it's looked up into the scene public static final int SAVABLE_VERSION = 2; @@ -79,7 +79,7 @@ public class AnimationEvent extends AbstractCinematicEvent { protected AnimationEvent() { super(); } - + /** * creates an animation event * @@ -202,7 +202,7 @@ public AnimationEvent(Spatial model, String animationName, float initialDuration * @param loopMode the loopMode * @see LoopMode * @param channelIndex the index of the channel default is 0. Events on the - * same channelIndex will use the same channel. + * same channelIndex will use the same channel. */ public AnimationEvent(Spatial model, String animationName, LoopMode loopMode, int channelIndex) { super(loopMode); @@ -219,7 +219,7 @@ public AnimationEvent(Spatial model, String animationName, LoopMode loopMode, in * @param model the model on which the animation will be played * @param animationName the name of the animation to play * @param channelIndex the index of the channel default is 0. Events on the - * same channelIndex will use the same channel. + * same channelIndex will use the same channel. */ public AnimationEvent(Spatial model, String animationName, int channelIndex) { this.model = model; @@ -228,7 +228,7 @@ public AnimationEvent(Spatial model, String animationName, int channelIndex) { initialDuration = model.getControl(AnimControl.class).getAnimationLength(animationName); this.channelIndex = channelIndex; } - + /** * creates an animation event * @@ -237,7 +237,7 @@ public AnimationEvent(Spatial model, String animationName, int channelIndex) { * @param loopMode the desired mode (Loop/DontLoop/Cycle) * @param channelIndex the index of the channel default is 0. Events on the * @param blendTime the time interval during which the animation will be blended - * same channelIndex will use the same channel. + * same channelIndex will use the same channel. */ public AnimationEvent(Spatial model, String animationName, LoopMode loopMode, int channelIndex, float blendTime) { this.model = model; @@ -256,7 +256,7 @@ public AnimationEvent(Spatial model, String animationName, LoopMode loopMode, in * @param animationName the name of the animation to play * @param initialDuration the initial duration of the event * @param channelIndex the index of the channel default is 0. Events on the - * same channelIndex will use the same channel. + * same channelIndex will use the same channel. */ public AnimationEvent(Spatial model, String animationName, float initialDuration, int channelIndex) { super(initialDuration); @@ -275,7 +275,7 @@ public AnimationEvent(Spatial model, String animationName, float initialDuration * @param loopMode the loopMode * @see LoopMode * @param channelIndex the index of the channel default is 0. Events on the - * same channelIndex will use the same channel. + * same channelIndex will use the same channel. */ public AnimationEvent(Spatial model, String animationName, float initialDuration, LoopMode loopMode, int channelIndex) { super(initialDuration, loopMode); @@ -295,8 +295,9 @@ public void initEvent(Application app, Cinematic cinematic) { if (s == null) { s = new HashMap(); int numChannels = model.getControl(AnimControl.class).getNumChannels(); - for(int i = 0; i < numChannels; i++){ - ((HashMap)s).put(i, model.getControl(AnimControl.class).getChannel(i)); + for (int i = 0; i < numChannels; i++) { + ((HashMap) s) + .put(i, model.getControl(AnimControl.class).getChannel(i)); } cinematic.putEventData(MODEL_CHANNELS, model, s); } @@ -311,9 +312,9 @@ public void initEvent(Application app, Cinematic cinematic) { model = cinematic.getScene().getChild(modelName); } if (model != null) { - if(cinematic.getScene() != null){ + if (cinematic.getScene() != null) { Spatial sceneModel = cinematic.getScene().getChild(model.getName()); - if(sceneModel != null){ + if (sceneModel != null) { Node parent = sceneModel.getParent(); parent.detachChild(sceneModel); sceneModel = model; @@ -322,15 +323,14 @@ public void initEvent(Application app, Cinematic cinematic) { cinematic.getScene().attachChild(model); } } - + channel = model.getControl(AnimControl.class).createChannel(); map.put(channelIndex, channel); } else { //it's an error throw new UnsupportedOperationException("model should not be null"); } - } - + } } } @@ -365,7 +365,6 @@ public void setTime(float time) { channel.setTime(t); channel.getControl().update(0); } - } @Override @@ -429,7 +428,6 @@ public void write(JmeExporter ex) throws IOException { oc.write(animationName, "animationName", ""); oc.write(blendTime, "blendTime", 0f); oc.write(channelIndex, "channelIndex", 0); - } @Override @@ -437,14 +435,14 @@ public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); // if (im.getFormatVersion() == 0) { - modelName = ic.readString("modelName", ""); + modelName = ic.readString("modelName", ""); // } //FIXME always the same issue, because of the cloning of assets, this won't work - //we have to somehow store userdata in the spatial and then recurse the + //we have to somehow store userdata in the spatial and then recurse the //scene sub scenegraph to find the correct instance of the model //This brings a reflection about the cinematic being an appstate, //shouldn't it be a control over the scene - // this would allow to use the cloneForSpatial method and automatically + // this would allow to use the cloneForSpatial method and automatically //rebind cloned references of original objects. //for now as nobody probably ever saved a cinematic, this is not a critical issue model = (Spatial) ic.readSavable("model", null); diff --git a/jme3-core/src/main/java/com/jme3/cinematic/events/CameraEvent.java b/jme3-core/src/main/java/com/jme3/cinematic/events/CameraEvent.java index 9a9478490d..08b2e8fe46 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/events/CameraEvent.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/events/CameraEvent.java @@ -43,7 +43,7 @@ * * @author Rickard (neph1 @ github) */ -public class CameraEvent extends AbstractCinematicEvent{ +public class CameraEvent extends AbstractCinematicEvent { private String cameraName; private Cinematic cinematic; @@ -56,27 +56,26 @@ public void setCameraName(String cameraName) { this.cameraName = cameraName; } - public CameraEvent(){ - + public CameraEvent() { } - - public CameraEvent(Cinematic parentEvent, String cameraName){ + + public CameraEvent(Cinematic parentEvent, String cameraName) { this.cinematic = parentEvent; this.cameraName = cameraName; } - - @Override + + @Override public void initEvent(Application app, Cinematic cinematic) { super.initEvent(app, cinematic); this.cinematic = cinematic; } - + @Override public void play() { super.play(); stop(); } - + @Override public void onPlay() { cinematic.setActiveCamera(cameraName); @@ -110,9 +109,7 @@ public Cinematic getCinematic() { public void setCinematic(Cinematic cinematic) { this.cinematic = cinematic; } - - - + /** * used internally for serialization * diff --git a/jme3-core/src/main/java/com/jme3/cinematic/events/MotionEvent.java b/jme3-core/src/main/java/com/jme3/cinematic/events/MotionEvent.java index 7f36178d87..2bd4485768 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/events/MotionEvent.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/events/MotionEvent.java @@ -111,7 +111,7 @@ public enum Direction { public MotionEvent() { super(); } - + /** * Creates a MotionPath for the given spatial on the given motion path. * @@ -179,7 +179,7 @@ public void internalUpdate(float tpf) { time = time + (tpf * speed); if (loopMode == LoopMode.Loop && time < 0) { time = initialDuration; - } + } if ((time >= initialDuration || time < 0) && loopMode == LoopMode.DontLoop) { if (time >= initialDuration) { path.triggerWayPointReach(path.getNbWayPoints() - 1, this); @@ -187,9 +187,9 @@ public void internalUpdate(float tpf) { stop(); } else { time = AnimationUtils.clampWrapTime(time, initialDuration, loopMode); - if(time<0){ - speed = - speed; - time = - time; + if (time < 0) { + speed = -speed; + time = -time; } onUpdate(tpf); } @@ -290,7 +290,7 @@ public Control cloneForSpatial(Spatial spatial) { throw new UnsupportedOperationException(); } - @Override + @Override public Object jmeClone() { MotionEvent control = new MotionEvent(); control.path = path; @@ -308,13 +308,13 @@ public Object jmeClone() { control.spatial = spatial; return control; - } + } - @Override - public void cloneFields( Cloner cloner, Object original ) { + @Override + public void cloneFields(Cloner cloner, Object original) { this.spatial = cloner.clone(spatial); } - + @Override public void onPlay() { traveledDistance = 0; @@ -373,16 +373,16 @@ public Vector3f getDirection() { /** * Sets the direction of the spatial, using the Y axis as the up vector. - * Use MotionEvent#setDirection((Vector3f direction,Vector3f upVector) if + * Use MotionEvent#setDirection((Vector3f direction,Vector3f upVector) if * you want a custom up vector. * This method is used by the motion path. * * @param direction the desired forward direction (not null, unaffected) */ public void setDirection(Vector3f direction) { - setDirection(direction, Vector3f.UNIT_Y); - } - + setDirection(direction, Vector3f.UNIT_Y); + } + /** * Sets the direction of the spatial with the given up vector. * This method is used by the motion path. @@ -390,7 +390,7 @@ public void setDirection(Vector3f direction) { * @param direction the desired forward direction (not null, unaffected) * @param upVector the up vector to consider for this direction. */ - public void setDirection(Vector3f direction,Vector3f upVector) { + public void setDirection(Vector3f direction, Vector3f upVector) { this.direction.set(direction); this.upVector.set(upVector); } diff --git a/jme3-core/src/main/java/com/jme3/cinematic/events/SoundEvent.java b/jme3-core/src/main/java/com/jme3/cinematic/events/SoundEvent.java index fe31678c3b..ba236214c6 100644 --- a/jme3-core/src/main/java/com/jme3/cinematic/events/SoundEvent.java +++ b/jme3-core/src/main/java/com/jme3/cinematic/events/SoundEvent.java @@ -86,7 +86,7 @@ public SoundEvent(String path, boolean stream, float initialDuration) { * creates a sound track from the given resource path * @param path the path to an audio file (ie : "Sounds/mySound.wav") * @param stream true to make the audio data streamed - * @param loopMode the loopMode + * @param loopMode the loopMode * @see LoopMode */ public SoundEvent(String path, boolean stream, LoopMode loopMode) { @@ -95,12 +95,12 @@ public SoundEvent(String path, boolean stream, LoopMode loopMode) { this.stream = stream; } - /** + /** * creates a sound track from the given resource path * @param path the path to an audio file (ie : "Sounds/mySound.wav") * @param stream true to make the audio data streamed * @param initialDuration the initial duration of the event - * @param loopMode the loopMode + * @param loopMode the loopMode * @see LoopMode */ public SoundEvent(String path, boolean stream, float initialDuration, LoopMode loopMode) { @@ -109,9 +109,9 @@ public SoundEvent(String path, boolean stream, float initialDuration, LoopMode l this.stream = stream; } - /** + /** * creates a sound track from the given resource path - * @param path the path to an audio file (ie : "Sounds/mySound.wav") + * @param path the path to an audio file (ie : "Sounds/mySound.wav") * @param initialDuration the initial duration of the event */ public SoundEvent(String path, float initialDuration) { @@ -119,10 +119,10 @@ public SoundEvent(String path, float initialDuration) { this.path = path; } - /** + /** * creates a sound track from the given resource path - * @param path the path to an audio file (ie : "Sounds/mySound.wav") - * @param loopMode the loopMode + * @param path the path to an audio file (ie : "Sounds/mySound.wav") + * @param loopMode the loopMode * @see LoopMode */ public SoundEvent(String path, LoopMode loopMode) { @@ -130,11 +130,11 @@ public SoundEvent(String path, LoopMode loopMode) { this.path = path; } - /** + /** * creates a sound track from the given resource path - * @param path the path to an audio file (ie : "Sounds/mySound.wav") + * @param path the path to an audio file (ie : "Sounds/mySound.wav") * @param initialDuration the initial duration of the event - * @param loopMode the loopMode + * @param loopMode the loopMode * @see LoopMode */ public SoundEvent(String path, float initialDuration, LoopMode loopMode) { @@ -162,9 +162,9 @@ public void initEvent(Application app, Cinematic cinematic) { public void setTime(float time) { super.setTime(time); //can occur on rewind - if (time < 0f) { + if (time < 0f) { stop(); - }else{ + } else { audioNode.setTimeOffset(time); } } @@ -177,7 +177,6 @@ public void onPlay() { @Override public void onStop() { audioNode.stop(); - } @Override @@ -193,7 +192,7 @@ public void onUpdate(float tpf) { } /** - * Returns the underlying audio node of this sound track + * Returns the underlying audio node of this sound track * @return the pre-existing instance */ public AudioNode getAudioNode() { @@ -225,6 +224,5 @@ public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); path = ic.readString("path", ""); stream = ic.readBoolean("stream", false); - } } diff --git a/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java b/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java index d0f6cb91e5..95739f5a1c 100644 --- a/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java +++ b/jme3-core/src/main/java/com/jme3/collision/CollisionResult.java @@ -63,30 +63,30 @@ public CollisionResult(Vector3f contactPoint, float distance) { this.distance = distance; } - public CollisionResult(){ + public CollisionResult() { } - public void setGeometry(Geometry geom){ + public void setGeometry(Geometry geom) { this.geometry = geom; } - public void setContactNormal(Vector3f norm){ + public void setContactNormal(Vector3f norm) { this.contactNormal = norm; } - public void setContactPoint(Vector3f point){ + public void setContactPoint(Vector3f point) { this.contactPoint = point; } - public void setDistance(float dist){ + public void setDistance(float dist) { this.distance = dist; } - public void setTriangleIndex(int index){ + public void setTriangleIndex(int index) { this.triangleIndex = index; } - public Triangle getTriangle(Triangle store){ + public Triangle getTriangle(Triangle store) { if (store == null) store = new Triangle(); @@ -104,8 +104,8 @@ public int compareTo(CollisionResult other) { @Override public boolean equals(Object obj) { - if(obj instanceof CollisionResult){ - return ((CollisionResult)obj).compareTo(this) == 0; + if (obj instanceof CollisionResult) { + return ((CollisionResult) obj).compareTo(this) == 0; } return super.equals(obj); } diff --git a/jme3-core/src/main/java/com/jme3/collision/CollisionResults.java b/jme3-core/src/main/java/com/jme3/collision/CollisionResults.java index 185519a9fe..032e464307 100644 --- a/jme3-core/src/main/java/com/jme3/collision/CollisionResults.java +++ b/jme3-core/src/main/java/com/jme3/collision/CollisionResults.java @@ -37,9 +37,9 @@ import java.util.List; /** - * CollisionResults is a collection returned as a result of a + * CollisionResults is a collection returned as a result of a * collision detection operation done by {@link Collidable}. - * + * * @author Kirill Vainer */ public class CollisionResults implements Iterable { @@ -50,7 +50,7 @@ public class CollisionResults implements Iterable { /** * Clears all collision results added to this list */ - public void clear(){ + public void clear() { if (results != null) { results.clear(); } @@ -58,17 +58,17 @@ public void clear(){ /** * Iterator for iterating over the collision results. - * + * * @return the iterator */ @Override public Iterator iterator() { if (results == null) { - List dumbCompiler = Collections.emptyList(); + List dumbCompiler = Collections.emptyList(); return dumbCompiler.iterator(); } - - if (!sorted){ + + if (!sorted) { Collections.sort(results); sorted = true; } @@ -76,7 +76,7 @@ public Iterator iterator() { return results.iterator(); } - public void addCollision(CollisionResult result){ + public void addCollision(CollisionResult result) { if (results == null) { results = new ArrayList(); } @@ -84,18 +84,18 @@ public void addCollision(CollisionResult result){ sorted = false; } - public int size(){ + public int size() { if (results == null) { return 0; } return results.size(); } - public CollisionResult getClosestCollision(){ + public CollisionResult getClosestCollision() { if (results == null || size() == 0) return null; - if (!sorted){ + if (!sorted) { Collections.sort(results); sorted = true; } @@ -103,24 +103,24 @@ public CollisionResult getClosestCollision(){ return results.get(0); } - public CollisionResult getFarthestCollision(){ + public CollisionResult getFarthestCollision() { if (results == null || size() == 0) return null; - if (!sorted){ + if (!sorted) { Collections.sort(results); sorted = true; } - return results.get(size()-1); + return results.get(size() - 1); } - public CollisionResult getCollision(int index){ + public CollisionResult getCollision(int index) { if (results == null) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: 0"); } - - if (!sorted){ + + if (!sorted) { Collections.sort(results); sorted = true; } @@ -134,7 +134,7 @@ public CollisionResult getCollision(int index){ * @param index the zero-based index of the desired result * @return the pre-existing instance */ - public CollisionResult getCollisionDirect(int index){ + public CollisionResult getCollisionDirect(int index) { if (results == null) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: 0"); } @@ -142,19 +142,18 @@ public CollisionResult getCollisionDirect(int index){ } @Override - public String toString(){ + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("CollisionResults["); if (results != null) { - for (CollisionResult result : results){ + for (CollisionResult result : results) { sb.append(result).append(", "); } if (results.size() > 0) - sb.setLength(sb.length()-2); - } + sb.setLength(sb.length() - 2); + } sb.append("]"); return sb.toString(); } - } diff --git a/jme3-core/src/main/java/com/jme3/collision/SweepSphere.java b/jme3-core/src/main/java/com/jme3/collision/SweepSphere.java index 2070136957..42a62ea84f 100644 --- a/jme3-core/src/main/java/com/jme3/collision/SweepSphere.java +++ b/jme3-core/src/main/java/com/jme3/collision/SweepSphere.java @@ -68,17 +68,17 @@ public Vector3f getDimension() { public void setDimension(Vector3f dimension) { this.dimension.set(dimension); - this.invDim.set(1,1,1).divideLocal(dimension); + this.invDim.set(1, 1, 1).divideLocal(dimension); } - public void setDimension(float x, float y, float z){ - this.dimension.set(x,y,z); - this.invDim.set(1,1,1).divideLocal(dimension); + public void setDimension(float x, float y, float z) { + this.dimension.set(x, y, z); + this.invDim.set(1, 1, 1).divideLocal(dimension); } - public void setDimension(float dim){ + public void setDimension(float dim) { this.dimension.set(dim, dim, dim); - this.invDim.set(1,1,1).divideLocal(dimension); + this.invDim.set(1, 1, 1).divideLocal(dimension); } public Vector3f getVelocity() { @@ -106,16 +106,17 @@ private boolean pointsOnSameSide(Vector3f p1, Vector3f p2, Vector3f line1, Vecto } private boolean isPointInTriangle(Vector3f point, AbstractTriangle tri) { - if (pointsOnSameSide(point, tri.get1(), tri.get2(), tri.get3()) - && pointsOnSameSide(point, tri.get2(), tri.get1(), tri.get3()) - && pointsOnSameSide(point, tri.get3(), tri.get1(), tri.get2())) - return true; - return false; + if (pointsOnSameSide(point, tri.get1(), tri.get2(), tri.get3()) + && pointsOnSameSide(point, tri.get2(), tri.get1(), tri.get3()) + && pointsOnSameSide(point, tri.get3(), tri.get1(), tri.get2())) { + return true; + } + return false; } private static float getLowestRoot(float a, float b, float c, float maxR) { float determinant = b * b - 4f * a * c; - if (determinant < 0){ + if (determinant < 0) { return Float.NaN; } @@ -123,17 +124,17 @@ private static float getLowestRoot(float a, float b, float c, float maxR) { float r1 = (-b - sqrtDet) / (2f * a); float r2 = (-b + sqrtDet) / (2f * a); - if (r1 > r2){ + if (r1 > r2) { float temp = r2; r2 = r1; r1 = temp; } - if (r1 > 0 && r1 < maxR){ + if (r1 > 0 && r1 < maxR) { return r1; } - if (r2 > 0 && r2 < maxR){ + if (r2 > 0 && r2 < maxR) { return r2; } @@ -159,7 +160,7 @@ private float collideWithVertex(Vector3f sCenter, Vector3f sVelocity, // float newT = getLowestRoot(A, B, C, Float.MAX_VALUE); // if (newT > 1.0f) // newT = Float.NaN; - + return newT; } @@ -184,9 +185,9 @@ private float collideWithSegment(Vector3f sCenter, - (2f * EdotV * EdotB); float c = (edgeSquared * (1f - baseSquared)) + EdotB * EdotB; float newT = getLowestRoot(a, b, c, t); - if (!Float.isNaN(newT)){ + if (!Float.isNaN(newT)) { float f = (EdotV * newT - EdotB) / edgeSquared; - if (f >= 0f && f < 1f){ + if (f >= 0f && f < 1f) { store.scaleAdd(f, edge, l1); return newT; } @@ -194,7 +195,7 @@ private float collideWithSegment(Vector3f sCenter, return Float.NaN; } - private CollisionResult collideWithTriangle(AbstractTriangle tri){ + private CollisionResult collideWithTriangle(AbstractTriangle tri) { // scale scaledTriangle based on dimension scaledTri.get1().set(tri.get1()).multLocal(invDim); scaledTri.get2().set(tri.get2()).multLocal(invDim); @@ -216,12 +217,12 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ boolean embedded = false; float signedDistanceToPlane = triPlane.pseudoDistance(sCenter); - if (normalDotVelocity == 0.0f){ + if (normalDotVelocity == 0.0f) { // we are travelling exactly parallel to the plane - if (FastMath.abs(signedDistanceToPlane) >= 1.0f){ + if (FastMath.abs(signedDistanceToPlane) >= 1.0f) { // no collision possible return null; - }else{ + } else { // we are embedded t0 = 0; t1 = 1; @@ -229,17 +230,17 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ System.out.println("EMBEDDED"); return null; } - }else{ + } else { t0 = (-1f - signedDistanceToPlane) / normalDotVelocity; - t1 = ( 1f - signedDistanceToPlane) / normalDotVelocity; + t1 = (1f - signedDistanceToPlane) / normalDotVelocity; - if (t0 > t1){ + if (t0 > t1) { float tf = t1; t1 = t0; t0 = tf; } - if (t0 > 1.0f || t1 < 0.0f){ + if (t0 > 1.0f || t1 < 0.0f) { // collision is out of this sVelocity range return null; } @@ -254,35 +255,35 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ Vector3f contactPoint = new Vector3f(); Vector3f contactNormal = new Vector3f(); - -// if (!embedded){ - // check against the inside of the scaledTriangle - // contactPoint = sCenter - p.normal + t0 * sVelocity - contactPoint.set(sVelocity); - contactPoint.multLocal(t0); - contactPoint.addLocal(sCenter); - contactPoint.subtractLocal(triPlane.getNormal()); - // test to see if the collision is on a scaledTriangle interior - if (isPointInTriangle(contactPoint, scaledTri) && !embedded){ - foundCollision = true; +// if (!embedded){ + // check against the inside of the scaledTriangle + // contactPoint = sCenter - p.normal + t0 * sVelocity + contactPoint.set(sVelocity); + contactPoint.multLocal(t0); + contactPoint.addLocal(sCenter); + contactPoint.subtractLocal(triPlane.getNormal()); + + // test to see if the collision is on a scaledTriangle interior + if (isPointInTriangle(contactPoint, scaledTri) && !embedded) { + foundCollision = true; - minT = t0; + minT = t0; - // scale collision point back into R3 - contactPoint.multLocal(dimension); - contactNormal.set(velocity).multLocal(t0); - contactNormal.addLocal(center); - contactNormal.subtractLocal(contactPoint).normalizeLocal(); + // scale collision point back into R3 + contactPoint.multLocal(dimension); + contactNormal.set(velocity).multLocal(t0); + contactNormal.addLocal(center); + contactNormal.subtractLocal(contactPoint).normalizeLocal(); // contactNormal.set(triPlane.getNormal()); - - CollisionResult result = new CollisionResult(); - result.setContactPoint(contactPoint); - result.setContactNormal(contactNormal); - result.setDistance(minT * velocity.length()); - return result; - } + + CollisionResult result = new CollisionResult(); + result.setContactPoint(contactPoint); + result.setContactNormal(contactNormal); + result.setDistance(minT * velocity.length()); + return result; + } // } float velocitySquared = sVelocity.lengthSquared(); @@ -294,7 +295,7 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ // vertex 1 float newT; newT = collideWithVertex(sCenter, sVelocity, velocitySquared, v1, minT); - if (!Float.isNaN(newT)){ + if (!Float.isNaN(newT)) { minT = newT; contactPoint.set(v1); foundCollision = true; @@ -302,7 +303,7 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ // vertex 2 newT = collideWithVertex(sCenter, sVelocity, velocitySquared, v2, minT); - if (!Float.isNaN(newT)){ + if (!Float.isNaN(newT)) { minT = newT; contactPoint.set(v2); foundCollision = true; @@ -310,7 +311,7 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ // vertex 3 newT = collideWithVertex(sCenter, sVelocity, velocitySquared, v3, minT); - if (!Float.isNaN(newT)){ + if (!Float.isNaN(newT)) { minT = newT; contactPoint.set(v3); foundCollision = true; @@ -318,26 +319,26 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ // edge 1-2 newT = collideWithSegment(sCenter, sVelocity, velocitySquared, v1, v2, minT, contactPoint); - if (!Float.isNaN(newT)){ + if (!Float.isNaN(newT)) { minT = newT; foundCollision = true; } // edge 2-3 newT = collideWithSegment(sCenter, sVelocity, velocitySquared, v2, v3, minT, contactPoint); - if (!Float.isNaN(newT)){ + if (!Float.isNaN(newT)) { minT = newT; foundCollision = true; } // edge 3-1 newT = collideWithSegment(sCenter, sVelocity, velocitySquared, v3, v1, minT, contactPoint); - if (!Float.isNaN(newT)){ + if (!Float.isNaN(newT)) { minT = newT; foundCollision = true; } - if (foundCollision){ + if (foundCollision) { // compute contact normal based on minimum t contactPoint.multLocal(dimension); contactNormal.set(velocity).multLocal(t0); @@ -350,12 +351,12 @@ private CollisionResult collideWithTriangle(AbstractTriangle tri){ result.setDistance(minT * velocity.length()); return result; - }else{ + } else { return null; } } - public CollisionResult collideWithSweepSphere(SweepSphere other){ + public CollisionResult collideWithSweepSphere(SweepSphere other) { temp1.set(velocity).subtractLocal(other.velocity); temp2.set(center).subtractLocal(other.center); temp3.set(dimension).addLocal(other.dimension); @@ -387,11 +388,11 @@ public CollisionResult collideWithSweepSphere(SweepSphere other){ // temp3 is contact point temp3.set(temp2).multLocal(dimension).addLocal(temp1); result.setContactPoint(new Vector3f(temp3)); - + return result; } - public static void main(String[] args){ + public static void main(String[] args) { SweepSphere ss = new SweepSphere(); ss.setCenter(Vector3f.ZERO); ss.setDimension(1); @@ -404,37 +405,36 @@ public static void main(String[] args){ CollisionResults cr = new CollisionResults(); ss.collideWith(ss2, cr); - if (cr.size() > 0){ + if (cr.size() > 0) { CollisionResult c = cr.getClosestCollision(); - System.out.println("D = "+c.getDistance()); - System.out.println("P = "+c.getContactPoint()); - System.out.println("N = "+c.getContactNormal()); + System.out.println("D = " + c.getDistance()); + System.out.println("P = " + c.getContactPoint()); + System.out.println("N = " + c.getContactNormal()); } } @Override public int collideWith(Collidable other, CollisionResults results) throws UnsupportedCollisionException { - if (other instanceof AbstractTriangle){ + if (other instanceof AbstractTriangle) { AbstractTriangle tri = (AbstractTriangle) other; CollisionResult result = collideWithTriangle(tri); - if (result != null){ + if (result != null) { results.addCollision(result); return 1; } return 0; - }else if (other instanceof SweepSphere){ + } else if (other instanceof SweepSphere) { SweepSphere sph = (SweepSphere) other; CollisionResult result = collideWithSweepSphere(sph); - if (result != null){ + if (result != null) { results.addCollision(result); return 1; } return 0; - }else{ + } else { throw new UnsupportedCollisionException(); } } - } diff --git a/jme3-core/src/main/java/com/jme3/collision/bih/BIHTree.java b/jme3-core/src/main/java/com/jme3/collision/bih/BIHTree.java index c892861748..fca434f750 100644 --- a/jme3-core/src/main/java/com/jme3/collision/bih/BIHTree.java +++ b/jme3-core/src/main/java/com/jme3/collision/bih/BIHTree.java @@ -68,10 +68,10 @@ public class BIHTree implements CollisionData { private int numTris; private float[] pointData; private int[] triIndices; - + // private transient CollisionResults boundResults = new CollisionResults(); private transient float[] bihSwapTmp; - + private void initTriList(FloatBuffer vb, IndexBuffer ib) { pointData = new float[numTris * 3 * 3]; int p = 0; @@ -112,12 +112,12 @@ public BIHTree(Mesh mesh, int maxTrisPerNode) { bihSwapTmp = new float[9]; VertexBuffer vBuffer = mesh.getBuffer(Type.Position); - if(vBuffer == null){ + if (vBuffer == null) { throw new IllegalArgumentException("A mesh should at least contain a Position buffer"); - } + } IndexBuffer ib = mesh.getIndexBuffer(); FloatBuffer vb = (FloatBuffer) vBuffer.getData(); - + if (ib == null) { ib = new VirtualIndexBuffer(mesh.getVertexCount(), mesh.getMode()); } else if (mesh.getMode() != Mode.Triangles) { @@ -326,7 +326,7 @@ private BIHNode createNode(int l, int r, BoundingBox nodeBbox, int depth) { pivot = (r + l) / 2; } - //If one of the partitions is empty, continue with recursion: same level but different bbox + // If one of the partitions is empty, continue with recursion: same level but different bbox if (pivot < l) { //Only right BoundingBox rbbox = new BoundingBox(currentBox); @@ -338,21 +338,21 @@ private BIHNode createNode(int l, int r, BoundingBox nodeBbox, int depth) { setMinMax(lbbox, false, axis, split); return createNode(l, r, lbbox, depth + 1); } else { - //Build the node + // Build the node BIHNode node = new BIHNode(axis); - //Left child + // Left child BoundingBox lbbox = new BoundingBox(currentBox); setMinMax(lbbox, false, axis, split); - //The left node right border is the plane most right + // The left node right border is the plane most right node.setLeftPlane(getMinMax(createBox(l, max(l, pivot - 1)), false, axis)); node.setLeftChild(createNode(l, max(l, pivot - 1), lbbox, depth + 1)); //Recursive call - //Right Child + // Right Child BoundingBox rbbox = new BoundingBox(currentBox); setMinMax(rbbox, true, axis, split); - //The right node left border is the plane most left + // The right node left border is the plane most left node.setRightPlane(getMinMax(createBox(pivot, r), true, axis)); node.setRightChild(createNode(pivot, r, rbbox, depth + 1)); //Recursive call @@ -421,7 +421,7 @@ private int collideWithRay(Ray r, if (r.getLimit() < Float.POSITIVE_INFINITY) { tMax = Math.min(tMax, r.getLimit()); - if (tMin > tMax){ + if (tMin > tMax) { return 0; } } diff --git a/jme3-core/src/main/java/com/jme3/collision/bih/BIHTriangle.java b/jme3-core/src/main/java/com/jme3/collision/bih/BIHTriangle.java index bff45b5d86..67f11f6400 100644 --- a/jme3-core/src/main/java/com/jme3/collision/bih/BIHTriangle.java +++ b/jme3-core/src/main/java/com/jme3/collision/bih/BIHTriangle.java @@ -49,15 +49,15 @@ public BIHTriangle(Vector3f p1, Vector3f p2, Vector3f p3) { center.addLocal(pointb).addLocal(pointc).multLocal(FastMath.ONE_THIRD); } - public Vector3f get1(){ + public Vector3f get1() { return pointa; } - public Vector3f get2(){ + public Vector3f get2() { return pointb; } - public Vector3f get3(){ + public Vector3f get3() { return pointc; } @@ -65,40 +65,55 @@ public Vector3f getCenter() { return center; } - public Vector3f getNormal(){ + public Vector3f getNormal() { Vector3f normal = new Vector3f(pointb); - normal.subtractLocal(pointa).crossLocal(pointc.x-pointa.x, pointc.y-pointa.y, pointc.z-pointa.z); + normal.subtractLocal(pointa) + .crossLocal(pointc.x - pointa.x, pointc.y - pointa.y, pointc.z - pointa.z); normal.normalizeLocal(); return normal; } - public float getExtreme(int axis, boolean left){ + public float getExtreme(int axis, boolean left) { float v1, v2, v3; - switch (axis){ - case 0: v1 = pointa.x; v2 = pointb.x; v3 = pointc.x; break; - case 1: v1 = pointa.y; v2 = pointb.y; v3 = pointc.y; break; - case 2: v1 = pointa.z; v2 = pointb.z; v3 = pointc.z; break; - default: assert false; return 0; + switch (axis) { + case 0: + v1 = pointa.x; + v2 = pointb.x; + v3 = pointc.x; + break; + case 1: + v1 = pointa.y; + v2 = pointb.y; + v3 = pointc.y; + break; + case 2: + v1 = pointa.z; + v2 = pointb.z; + v3 = pointc.z; + break; + default: + assert false; + return 0; } - if (left){ - if (v1 < v2){ + if (left) { + if (v1 < v2) { if (v1 < v3) return v1; else return v3; - }else{ + } else { if (v2 < v3) return v2; else return v3; } - }else{ - if (v1 > v2){ + } else { + if (v1 > v2) { if (v1 > v3) return v1; else return v3; - }else{ + } else { if (v2 > v3) return v2; else @@ -106,5 +121,4 @@ public float getExtreme(int axis, boolean left){ } } } - } diff --git a/jme3-core/src/main/java/com/jme3/collision/bih/TriangleAxisComparator.java b/jme3-core/src/main/java/com/jme3/collision/bih/TriangleAxisComparator.java index e503a63340..a409eefb0f 100644 --- a/jme3-core/src/main/java/com/jme3/collision/bih/TriangleAxisComparator.java +++ b/jme3-core/src/main/java/com/jme3/collision/bih/TriangleAxisComparator.java @@ -38,7 +38,7 @@ public class TriangleAxisComparator implements Comparator { private final int axis; - public TriangleAxisComparator(int axis){ + public TriangleAxisComparator(int axis) { this.axis = axis; } @@ -47,11 +47,22 @@ public int compare(BIHTriangle o1, BIHTriangle o2) { float v1, v2; Vector3f c1 = o1.getCenter(); Vector3f c2 = o2.getCenter(); - switch (axis){ - case 0: v1 = c1.x; v2 = c2.x; break; - case 1: v1 = c1.y; v2 = c2.y; break; - case 2: v1 = c1.z; v2 = c2.z; break; - default: assert false; return 0; + switch (axis) { + case 0: + v1 = c1.x; + v2 = c2.x; + break; + case 1: + v1 = c1.y; + v2 = c2.y; + break; + case 2: + v1 = c1.z; + v2 = c2.z; + break; + default: + assert false; + return 0; } if (v1 > v2) return 1; @@ -60,4 +71,4 @@ else if (v1 < v2) else return 0; } -} \ No newline at end of file +} diff --git a/jme3-core/src/main/java/com/jme3/effect/ParticleEmitter.java b/jme3-core/src/main/java/com/jme3/effect/ParticleEmitter.java index eb60ca8fae..95d661bbee 100644 --- a/jme3-core/src/main/java/com/jme3/effect/ParticleEmitter.java +++ b/jme3-core/src/main/java/com/jme3/effect/ParticleEmitter.java @@ -131,13 +131,13 @@ public Control cloneForSpatial(Spatial spatial) { public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning", e); } } @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.parentEmitter = cloner.clone(parentEmitter); } @@ -179,7 +179,7 @@ public ParticleEmitter clone() { @Override public ParticleEmitter clone(boolean cloneMaterial) { - return (ParticleEmitter)super.clone(cloneMaterial); + return (ParticleEmitter) super.clone(cloneMaterial); } /** @@ -228,7 +228,7 @@ public ParticleEmitter oldClone(boolean cloneMaterial) { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); this.shape = cloner.clone(shape); @@ -418,7 +418,7 @@ public int getNumVisibleParticles() { * Calling this method many times is not recommended. * * @param numParticles the maximum amount of particles that - * can exist at the same time with this emitter. + * can exist at the same time with this emitter. */ public final void setNumParticles(int numParticles) { particles = new Particle[numParticles]; @@ -513,7 +513,7 @@ public void setRotateSpeed(float rotateSpeed) { * should have a random facing angle. * * @return true if every particle spawned - * should have a random facing angle. + * should have a random facing angle. * * @see ParticleEmitter#setRandomAngle(boolean) */ @@ -526,7 +526,7 @@ public boolean isRandomAngle() { * should have a random facing angle. * * @param randomAngle if every particle spawned - * should have a random facing angle. + * should have a random facing angle. */ public void setRandomAngle(boolean randomAngle) { this.randomAngle = randomAngle; @@ -537,7 +537,7 @@ public void setRandomAngle(boolean randomAngle) { * image. * * @return True if every particle spawned should get a random - * image. + * image. * * @see ParticleEmitter#setSelectRandomImage(boolean) */ @@ -559,7 +559,7 @@ public boolean isSelectRandomImage() { * the particle reaches its end of life. * * @param selectRandomImage True if every particle spawned should get a random - * image. + * image. */ public void setSelectRandomImage(boolean selectRandomImage) { this.selectRandomImage = selectRandomImage; @@ -772,7 +772,7 @@ public void setLowLife(float lowLife) { * second. * * @return the number of particles to spawn per - * second. + * second. * * @see ParticleEmitter#setParticlesPerSec(float) */ @@ -785,11 +785,12 @@ public float getParticlesPerSec() { * second. * * @param particlesPerSec the number of particles to spawn per - * second. + * second. */ public void setParticlesPerSec(float particlesPerSec) { this.particlesPerSec = particlesPerSec; - timeDifference = Math.min(timeDifference,1f / particlesPerSec); //prevent large accumulated timeDifference from causing a huge number of particles to be emitted + timeDifference = Math.min(timeDifference, 1f / particlesPerSec); + //prevent large accumulated timeDifference from causing a huge number of particles to be emitted } /** @@ -842,7 +843,7 @@ public void setStartSize(float startSize) { /** * @deprecated Use ParticleEmitter.getParticleInfluencer().getInitialVelocity() instead. - * + * * @return the pre-existing velocity vector */ @Deprecated @@ -852,17 +853,17 @@ public Vector3f getInitialVelocity() { /** * @param initialVelocity Set the initial velocity a particle is spawned with, - * the initial velocity given in the parameter will be varied according - * to the velocity variation set in {@link ParticleEmitter#setVelocityVariation(float) }. - * The particle will move with this velocity unless it is affected by - * gravity. + * the initial velocity given in the parameter will be varied according + * to the velocity variation set in {@link ParticleEmitter#setVelocityVariation(float) }. + * The particle will move with this velocity unless it is affected by + * gravity. * * @deprecated - * This method is deprecated. - * Use ParticleEmitter.getParticleInfluencer().setInitialVelocity(initialVelocity); instead. + * This method is deprecated. + * Use ParticleEmitter.getParticleInfluencer().setInitialVelocity(initialVelocity); instead. * * @see ParticleEmitter#setVelocityVariation(float) - * @see #setGravity(com.jme3.math.Vector3f) + * @see #setGravity(com.jme3.math.Vector3f) */ @Deprecated public void setInitialVelocity(Vector3f initialVelocity) { @@ -871,8 +872,8 @@ public void setInitialVelocity(Vector3f initialVelocity) { /** * @deprecated - * This method is deprecated. - * Use ParticleEmitter.getParticleInfluencer().getVelocityVariation(); instead. + * This method is deprecated. + * Use ParticleEmitter.getParticleInfluencer().getVelocityVariation(); instead. * @return the initial velocity variation factor */ @Deprecated @@ -882,15 +883,15 @@ public float getVelocityVariation() { /** * @param variation Set the variation by which the initial velocity - * of the particle is determined. variation should be a value - * from 0 to 1, where 0 means particles are to spawn with exactly - * the velocity specified in - * {@link com.jme3.effect.influencers.ParticleInfluencer#setInitialVelocity(com.jme3.math.Vector3f)}, - * and 1 means particles are to spawn with a completely random velocity. + * of the particle is determined. variation should be a value + * from 0 to 1, where 0 means particles are to spawn with exactly + * the velocity specified in + * {@link com.jme3.effect.influencers.ParticleInfluencer#setInitialVelocity(com.jme3.math.Vector3f)}, + * and 1 means particles are to spawn with a completely random velocity. * * @deprecated - * This method is deprecated. - * Use ParticleEmitter.getParticleInfluencer().setVelocityVariation(variation); instead. + * This method is deprecated. + * Use ParticleEmitter.getParticleInfluencer().setVelocityVariation(variation); instead. */ @Deprecated public void setVelocityVariation(float variation) { @@ -905,7 +906,8 @@ private Particle emitParticle(Vector3f min, Vector3f max) { Particle p = particles[idx]; if (selectRandomImage) { - p.imageIndex = FastMath.nextRandomInt(0, imagesY - 1) * imagesX + FastMath.nextRandomInt(0, imagesX - 1); + p.imageIndex = FastMath.nextRandomInt(0, imagesY - 1) + * imagesX + FastMath.nextRandomInt(0, imagesX - 1); } p.startlife = lowLife + FastMath.nextRandomFloat() * (highLife - lowLife); @@ -946,7 +948,7 @@ public void emitAllParticles() { /** * Instantly emits available particles, up to num. - * + * * @param num the maximum number of particles to emit */ public void emitParticles(int num) { @@ -970,8 +972,9 @@ public void emitParticles(int num) { max.set(Vector3f.NEGATIVE_INFINITY); } - for(int i=0;i interval){ + while (tpf > interval) { tpf -= interval; Particle p = emitParticle(min, max); - if (p != null){ + if (p != null) { p.life -= tpf; if (lastPos != null && isInWorldSpace()) { p.position.interpolateLocal(lastPos, 1 - tpf / originalTpf); } - if (p.life <= 0){ + if (p.life <= 0) { freeParticle(lastUsed); - }else{ + } else { updateParticle(p, tpf, min, max); } } @@ -1234,7 +1237,6 @@ public void read(JmeImporter im) throws IOException { meshType = ic.readEnum("meshType", ParticleMesh.Type.class, ParticleMesh.Type.Triangle); int numParticles = ic.readInt("numParticles", 0); - enabled = ic.readBoolean("enabled", true); particlesPerSec = ic.readFloat("particlesPerSec", 0); lowLife = ic.readFloat("lowLife", 0); @@ -1250,7 +1252,7 @@ public void read(JmeImporter im) throws IOException { worldSpace = ic.readBoolean("worldSpace", false); this.setIgnoreTransform(worldSpace); facingVelocity = ic.readBoolean("facingVelocity", false); - faceNormal = (Vector3f)ic.readSavable("faceNormal", new Vector3f(Vector3f.NAN)); + faceNormal = (Vector3f) ic.readSavable("faceNormal", new Vector3f(Vector3f.NAN)); selectRandomImage = ic.readBoolean("selectRandomImage", false); randomAngle = ic.readBoolean("randomAngle", false); rotateSpeed = ic.readFloat("rotateSpeed", 0); @@ -1300,7 +1302,6 @@ public void read(JmeImporter im) throws IOException { // loaded separately control = getControl(ParticleEmitterControl.class); control.parentEmitter = this; - } } } diff --git a/jme3-core/src/main/java/com/jme3/effect/ParticlePointMesh.java b/jme3-core/src/main/java/com/jme3/effect/ParticlePointMesh.java index b9c0f43d8b..10f7ace1b1 100644 --- a/jme3-core/src/main/java/com/jme3/effect/ParticlePointMesh.java +++ b/jme3-core/src/main/java/com/jme3/effect/ParticlePointMesh.java @@ -61,8 +61,8 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { // set positions FloatBuffer pb = BufferUtils.createVector3Buffer(numParticles); - - //if the buffer is already set only update the data + + // if the buffer is already set only update the data VertexBuffer buf = getBuffer(VertexBuffer.Type.Position); if (buf != null) { buf.updateData(pb); @@ -74,7 +74,7 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { // set colors ByteBuffer cb = BufferUtils.createByteBuffer(numParticles * 4); - + buf = getBuffer(VertexBuffer.Type.Color); if (buf != null) { buf.updateData(cb); @@ -87,7 +87,7 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { // set sizes FloatBuffer sb = BufferUtils.createFloatBuffer(numParticles); - + buf = getBuffer(VertexBuffer.Type.Size); if (buf != null) { buf.updateData(sb); @@ -98,8 +98,8 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { } // set UV-scale - FloatBuffer tb = BufferUtils.createFloatBuffer(numParticles*4); - + FloatBuffer tb = BufferUtils.createFloatBuffer(numParticles * 4); + buf = getBuffer(VertexBuffer.Type.TexCoord); if (buf != null) { buf.updateData(tb); @@ -108,7 +108,7 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { tvb.setupData(Usage.Stream, 4, Format.Float, tb); setBuffer(tvb); } - + updateCounts(); } @@ -133,9 +133,9 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers colors.rewind(); sizes.rewind(); texcoords.rewind(); - for (int i = 0; i < particles.length; i++){ + for (int i = 0; i < particles.length; i++) { Particle p = particles[i]; - + positions.put(p.position.x) .put(p.position.y) .put(p.position.z); @@ -144,12 +144,12 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers colors.putInt(p.color.asIntABGR()); int imgX = p.imageIndex % imagesX; - int imgY = p.imageIndex/imagesX; + int imgY = p.imageIndex / imagesX; float startX = ((float) imgX) / imagesX; float startY = ((float) imgY) / imagesY; - float endX = startX + (1f / imagesX); - float endY = startY + (1f / imagesY); + float endX = startX + (1f / imagesX); + float endY = startY + (1f / imagesY); texcoords.put(startX).put(startY).put(endX).put(endY); } diff --git a/jme3-core/src/main/java/com/jme3/effect/ParticleTriMesh.java b/jme3-core/src/main/java/com/jme3/effect/ParticleTriMesh.java index 16b9071d6d..f34dd7dc0d 100644 --- a/jme3-core/src/main/java/com/jme3/effect/ParticleTriMesh.java +++ b/jme3-core/src/main/java/com/jme3/effect/ParticleTriMesh.java @@ -72,7 +72,7 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { pvb.setupData(Usage.Stream, 3, Format.Float, pb); setBuffer(pvb); } - + // set colors ByteBuffer cb = BufferUtils.createByteBuffer(numParticles * 4 * 4); buf = getBuffer(VertexBuffer.Type.Color); @@ -88,14 +88,14 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { // set texcoords FloatBuffer tb = BufferUtils.createVector2Buffer(numParticles * 4); uniqueTexCoords = false; - for (int i = 0; i < numParticles; i++){ + for (int i = 0; i < numParticles; i++) { tb.put(0f).put(1f); tb.put(1f).put(1f); tb.put(0f).put(0f); tb.put(1f).put(0f); } tb.flip(); - + buf = getBuffer(VertexBuffer.Type.TexCoord); if (buf != null) { buf.updateData(tb); @@ -107,18 +107,18 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { // set indices ShortBuffer ib = BufferUtils.createShortBuffer(numParticles * 6); - for (int i = 0; i < numParticles; i++){ + for (int i = 0; i < numParticles; i++) { int startIdx = (i * 4); // triangle 1 - ib.put((short)(startIdx + 1)) - .put((short)(startIdx + 0)) - .put((short)(startIdx + 2)); + ib.put((short) (startIdx + 1)) + .put((short) (startIdx + 0)) + .put((short) (startIdx + 2)); // triangle 2 - ib.put((short)(startIdx + 1)) - .put((short)(startIdx + 2)) - .put((short)(startIdx + 3)); + ib.put((short) (startIdx + 1)) + .put((short) (startIdx + 2)) + .put((short) (startIdx + 3)); } ib.flip(); @@ -130,15 +130,15 @@ public void initParticleData(ParticleEmitter emitter, int numParticles) { ivb.setupData(Usage.Static, 3, Format.UnsignedShort, ib); setBuffer(ivb); } - + updateCounts(); } - + @Override public void setImagesXY(int imagesX, int imagesY) { this.imagesX = imagesX; this.imagesY = imagesY; - if (imagesX != 1 || imagesY != 1){ + if (imagesX != 1 || imagesY != 1) { uniqueTexCoords = true; getBuffer(VertexBuffer.Type.TexCoord).setUsage(Usage.Stream); } @@ -162,9 +162,9 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers VertexBuffer tvb = getBuffer(VertexBuffer.Type.TexCoord); FloatBuffer texcoords = (FloatBuffer) tvb.getData(); - Vector3f camUp = cam.getUp(); + Vector3f camUp = cam.getUp(); Vector3f camLeft = cam.getLeft(); - Vector3f camDir = cam.getDirection(); + Vector3f camDir = cam.getDirection(); inverseRotation.multLocal(camUp); inverseRotation.multLocal(camLeft); @@ -175,7 +175,7 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers Vector3f up = new Vector3f(), left = new Vector3f(); - if (!facingVelocity){ + if (!facingVelocity) { up.set(camUp); left.set(camLeft); } @@ -185,24 +185,24 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers colors.clear(); texcoords.clear(); Vector3f faceNormal = emitter.getFaceNormal(); - - for (int i = 0; i < particles.length; i++){ + + for (int i = 0; i < particles.length; i++) { Particle p = particles[i]; boolean dead = p.life == 0; - if (dead){ + if (dead) { positions.put(0).put(0).put(0); positions.put(0).put(0).put(0); positions.put(0).put(0).put(0); positions.put(0).put(0).put(0); continue; } - - if (facingVelocity){ + + if (facingVelocity) { left.set(p.velocity).normalizeLocal(); camDir.cross(left, up); up.multLocal(p.size); left.multLocal(p.size); - }else if (faceNormal != null){ + } else if (faceNormal != null) { up.set(faceNormal).crossLocal(Vector3f.UNIT_X); faceNormal.cross(up, left); up.multLocal(p.size); @@ -215,7 +215,7 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers vars.quat1.multLocal(up); vars.release(); } - }else if (p.angle != 0){ + } else if (p.angle != 0) { float cos = FastMath.cos(p.angle) * p.size; float sin = FastMath.sin(p.angle) * p.size; @@ -226,7 +226,7 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers up.x = camLeft.x * -sin + camUp.x * cos; up.y = camLeft.y * -sin + camUp.y * cos; up.z = camLeft.z * -sin + camUp.z * cos; - }else{ + } else { up.set(camUp); left.set(camLeft); up.multLocal(p.size); @@ -249,14 +249,14 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers .put(p.position.y - left.y - up.y) .put(p.position.z - left.z - up.z); - if (uniqueTexCoords){ + if (uniqueTexCoords) { int imgX = p.imageIndex % imagesX; int imgY = p.imageIndex / imagesX; float startX = ((float) imgX) / imagesX; float startY = ((float) imgY) / imagesY; - float endX = startX + (1f / imagesX); - float endY = startY + (1f / imagesY); + float endX = startX + (1f / imagesX); + float endY = startY + (1f / imagesY); texcoords.put(startX).put(endY); texcoords.put(endX).put(endY); @@ -275,7 +275,7 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers colors.clear(); if (!uniqueTexCoords) texcoords.clear(); - else{ + else { texcoords.clear(); tvb.updateData(texcoords); } @@ -284,5 +284,4 @@ public void updateParticleData(Particle[] particles, Camera cam, Matrix3f invers pvb.updateData(positions); cvb.updateData(colors); } - } diff --git a/jme3-core/src/main/java/com/jme3/effect/influencers/DefaultParticleInfluencer.java b/jme3-core/src/main/java/com/jme3/effect/influencers/DefaultParticleInfluencer.java index 09be6e1a24..d6d2c5ecf2 100644 --- a/jme3-core/src/main/java/com/jme3/effect/influencers/DefaultParticleInfluencer.java +++ b/jme3-core/src/main/java/com/jme3/effect/influencers/DefaultParticleInfluencer.java @@ -91,9 +91,9 @@ public void write(JmeExporter ex) throws IOException { public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); // NOTE: In previous versions of jME3, initialVelocity was called startVelocity - if (ic.getSavableVersion(DefaultParticleInfluencer.class) == 0){ + if (ic.getSavableVersion(DefaultParticleInfluencer.class) == 0) { initialVelocity = (Vector3f) ic.readSavable("startVelocity", Vector3f.ZERO.clone()); - }else{ + } else { initialVelocity = (Vector3f) ic.readSavable("initialVelocity", Vector3f.ZERO.clone()); } velocityVariation = ic.readFloat("variation", 0.2f); @@ -126,7 +126,7 @@ public Object jmeClone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.initialVelocity = cloner.clone(initialVelocity); // Change in behavior: I'm cloning 'for real' the 'temp' field because diff --git a/jme3-core/src/main/java/com/jme3/effect/influencers/EmptyParticleInfluencer.java b/jme3-core/src/main/java/com/jme3/effect/influencers/EmptyParticleInfluencer.java index 191bb7a120..398ee1fd9c 100644 --- a/jme3-core/src/main/java/com/jme3/effect/influencers/EmptyParticleInfluencer.java +++ b/jme3-core/src/main/java/com/jme3/effect/influencers/EmptyParticleInfluencer.java @@ -101,6 +101,6 @@ public Object jmeClone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { } } diff --git a/jme3-core/src/main/java/com/jme3/effect/influencers/RadialParticleInfluencer.java b/jme3-core/src/main/java/com/jme3/effect/influencers/RadialParticleInfluencer.java index 342ca2b8a1..6f62832dd1 100644 --- a/jme3-core/src/main/java/com/jme3/effect/influencers/RadialParticleInfluencer.java +++ b/jme3-core/src/main/java/com/jme3/effect/influencers/RadialParticleInfluencer.java @@ -125,14 +125,13 @@ public void setHorizontal(boolean horizontal) { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); // Change in behavior: the old origin was not cloned -pspeed this.origin = cloner.clone(origin); } - @Override public void write(JmeExporter ex) throws IOException { super.write(ex); diff --git a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterBoxShape.java b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterBoxShape.java index be9d0257da..12f6645809 100644 --- a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterBoxShape.java +++ b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterBoxShape.java @@ -103,7 +103,7 @@ public Object jmeClone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.min = cloner.clone(min); this.len = cloner.clone(len); } diff --git a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterMeshVertexShape.java b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterMeshVertexShape.java index 363d7865ca..cadb07ca48 100644 --- a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterMeshVertexShape.java +++ b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterMeshVertexShape.java @@ -185,7 +185,7 @@ public Object jmeClone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.vertices = cloner.clone(vertices); this.normals = cloner.clone(normals); } @@ -204,7 +204,7 @@ public void read(JmeImporter im) throws IOException { this.vertices = ic.readSavableArrayList("vertices", null); List> tmpNormals = ic.readSavableArrayList("normals", null); - if (tmpNormals != null){ + if (tmpNormals != null) { this.normals = tmpNormals; } } diff --git a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterPointShape.java b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterPointShape.java index fb89be826b..0eca81c226 100644 --- a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterPointShape.java +++ b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterPointShape.java @@ -76,7 +76,7 @@ public Object jmeClone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.point = cloner.clone(point); } diff --git a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterSphereShape.java b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterSphereShape.java index 015be8b835..a9d7dabca7 100644 --- a/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterSphereShape.java +++ b/jme3-core/src/main/java/com/jme3/effect/shapes/EmitterSphereShape.java @@ -88,7 +88,7 @@ public Object jmeClone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.center = cloner.clone(center); } diff --git a/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java b/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java index be855fb205..2f8ee78d9b 100644 --- a/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java +++ b/jme3-core/src/main/java/com/jme3/environment/EnvironmentCamera.java @@ -274,7 +274,7 @@ public void setPosition(final Vector3f position) { * Note that this will be null until after initialize() is called. * @return array of ViewPorts */ - public ViewPort[] getViewPorts(){ + public ViewPort[] getViewPorts() { return viewports; } @@ -310,7 +310,6 @@ protected void initialize(Application app) { } } - @Override protected void cleanup(Application app) { this.backGroundColor = null; @@ -320,7 +319,7 @@ protected void cleanup(Application app) { } for (final Image image : images) { - if( image != null){ + if (image != null) { image.dispose(); } } @@ -353,7 +352,8 @@ protected void onDisable() { * @param axisZ tha z axis * @return a new instance */ - protected Camera createOffCamera(final int mapSize, final Vector3f worldPos, final Vector3f axisX, final Vector3f axisY, final Vector3f axisZ) { + protected Camera createOffCamera(final int mapSize, final Vector3f worldPos, + final Vector3f axisX, final Vector3f axisY, final Vector3f axisZ) { final Camera offCamera = new Camera(mapSize, mapSize); offCamera.setLocation(worldPos); offCamera.setAxes(axisX, axisY, axisZ); diff --git a/jme3-core/src/main/java/com/jme3/environment/util/LightsDebugState.java b/jme3-core/src/main/java/com/jme3/environment/util/LightsDebugState.java index a0c38c90cc..e2a159bf04 100644 --- a/jme3-core/src/main/java/com/jme3/environment/util/LightsDebugState.java +++ b/jme3-core/src/main/java/com/jme3/environment/util/LightsDebugState.java @@ -48,7 +48,7 @@ /** * A debug state that will display Light gizmos on screen. * Still a wip and for now it only displays light probes. - * + * * @author nehon */ public class LightsDebugState extends BaseAppState { @@ -78,7 +78,7 @@ protected void initialize(Application app) { @Override public void update(float tpf) { - if(!isEnabled()){ + if (!isEnabled()) { return; } updateLights(scene); @@ -115,7 +115,7 @@ public void updateLights(Spatial scene) { break; } } - if( scene instanceof Node){ + if (scene instanceof Node) { Node n = (Node)scene; for (Spatial spatial : n.getChildren()) { updateLights(spatial); @@ -149,13 +149,12 @@ private void cleanProbes() { @Override public void render(RenderManager rm) { - if(!isEnabled()){ + if (!isEnabled()) { return; } rm.renderScene(debugNode, getApplication().getViewPort()); } - /** * returns the scale of the probe's debug sphere * @return the scale factor @@ -175,17 +174,13 @@ public void setProbeScale(float probeScale) { @Override protected void cleanup(Application app) { - } @Override protected void onEnable() { - } @Override protected void onDisable() { - } - } diff --git a/jme3-core/src/main/java/com/jme3/export/FormatVersion.java b/jme3-core/src/main/java/com/jme3/export/FormatVersion.java index 433941b758..7de953abcb 100644 --- a/jme3-core/src/main/java/com/jme3/export/FormatVersion.java +++ b/jme3-core/src/main/java/com/jme3/export/FormatVersion.java @@ -33,7 +33,7 @@ /** * Specifies the version of the format for jME3 object (j3o) files. - * + * * @author Kirill Vainer */ public final class FormatVersion { @@ -42,12 +42,12 @@ public final class FormatVersion { * Version number of the format */ public static final int VERSION = 2; - + /** * Signature of the format: currently, "JME3" as ASCII. */ public static final int SIGNATURE = 0x4A4D4533; - - private FormatVersion(){ + + private FormatVersion() { } } diff --git a/jme3-core/src/main/java/com/jme3/export/SavableClassUtil.java b/jme3-core/src/main/java/com/jme3/export/SavableClassUtil.java index 6ff09802d2..81887511cf 100644 --- a/jme3-core/src/main/java/com/jme3/export/SavableClassUtil.java +++ b/jme3-core/src/main/java/com/jme3/export/SavableClassUtil.java @@ -59,7 +59,7 @@ public class SavableClassUtil { private final static HashMap CLASS_REMAPPINGS = new HashMap<>(); - private static void addRemapping(String oldClass, Class newClass){ + private static void addRemapping(String oldClass, Class newClass) { CLASS_REMAPPINGS.put(oldClass, newClass.getName()); } @@ -95,13 +95,13 @@ private static String remapClass(String className) throws ClassNotFoundException } } - public static boolean isImplementingSavable(Class clazz){ + public static boolean isImplementingSavable(Class clazz) { boolean result = Savable.class.isAssignableFrom(clazz); return result; } @SuppressWarnings("unchecked") - public static int[] getSavableVersions(Class clazz) throws IOException{ + public static int[] getSavableVersions(Class clazz) throws IOException { ArrayList versionList = new ArrayList<>(); Class superclass = clazz; do { @@ -110,20 +110,20 @@ public static int[] getSavableVersions(Class clazz) throws IO } while (superclass != null && SavableClassUtil.isImplementingSavable(superclass)); int[] versions = new int[versionList.size()]; - for (int i = 0; i < versionList.size(); i++){ + for (int i = 0; i < versionList.size(); i++) { versions[i] = versionList.get(i); } return versions; } @SuppressWarnings("unchecked") - public static int getSavableVersion(Class clazz) throws IOException{ + public static int getSavableVersion(Class clazz) throws IOException { try { Field field = clazz.getField("SAVABLE_VERSION"); Class declaringClass = (Class) field.getDeclaringClass(); - if (declaringClass == clazz){ + if (declaringClass == clazz) { return field.getInt(null); - }else{ + } else { return 0; // This class doesn't declare this field, e.g. version == 0 } } catch (IllegalAccessException ex) { @@ -137,27 +137,28 @@ public static int getSavableVersion(Class clazz) throws IOExc } } - public static int getSavedSavableVersion(Object savable, Class desiredClass, int[] versions, int formatVersion){ + public static int getSavedSavableVersion(Object savable, + Class desiredClass, int[] versions, int formatVersion) { Class thisClass = savable.getClass(); int count = 0; while (thisClass != desiredClass) { thisClass = thisClass.getSuperclass(); - if (thisClass != null && SavableClassUtil.isImplementingSavable(thisClass)){ - count ++; - }else{ + if (thisClass != null && SavableClassUtil.isImplementingSavable(thisClass)) { + count++; + } else { break; } } - if (thisClass == null){ + if (thisClass == null) { throw new IllegalArgumentException(savable.getClass().getName() + " does not extend " + desiredClass.getName() + "!"); - }else if (count >= versions.length){ - if (formatVersion <= 1){ + } else if (count >= versions.length) { + if (formatVersion <= 1) { return 0; // for buggy versions of j3o - }else{ + } else { throw new IllegalArgumentException(savable.getClass().getName() + " cannot access version of " + desiredClass.getName() + diff --git a/jme3-core/src/main/java/com/jme3/font/BitmapCharacter.java b/jme3-core/src/main/java/com/jme3/font/BitmapCharacter.java index cf91dd385f..f398e71d03 100644 --- a/jme3-core/src/main/java/com/jme3/font/BitmapCharacter.java +++ b/jme3-core/src/main/java/com/jme3/font/BitmapCharacter.java @@ -50,9 +50,9 @@ public class BitmapCharacter implements Savable, Cloneable { private int xAdvance; private IntMap kerning = new IntMap<>(); private int page; - + public BitmapCharacter() {} - + public BitmapCharacter(char c) { this.c = c; } @@ -131,20 +131,20 @@ public void setPage(int page) { public int getPage() { return page; } - + public char getChar() { return c; } - + public void setChar(char c) { this.c = c; } - public void addKerning(int second, int amount){ + public void addKerning(int second, int amount) { kerning.put(second, amount); } - public int getKerning(int second){ + public int getKerning(int second) { Integer i = kerning.get(second); if (i == null) return 0; @@ -168,7 +168,7 @@ public void write(JmeExporter ex) throws IOException { int[] amounts = new int[seconds.length]; int i = 0; - for (Entry entry : kerning){ + for (Entry entry : kerning) { seconds[i] = entry.getKey(); amounts[i] = entry.getValue(); i++; @@ -193,7 +193,7 @@ public void read(JmeImporter im) throws IOException { int[] seconds = ic.readIntArray("seconds", null); int[] amounts = ic.readIntArray("amounts", null); - for (int i = 0; i < seconds.length; i++){ + for (int i = 0; i < seconds.length; i++) { kerning.put(seconds[i], amounts[i]); } } diff --git a/jme3-core/src/main/java/com/jme3/font/BitmapCharacterSet.java b/jme3-core/src/main/java/com/jme3/font/BitmapCharacterSet.java index a2671e4784..86e6a5fd8e 100644 --- a/jme3-core/src/main/java/com/jme3/font/BitmapCharacterSet.java +++ b/jme3-core/src/main/java/com/jme3/font/BitmapCharacterSet.java @@ -73,7 +73,7 @@ protected void writeCharset(OutputCapsule oc, int style, IntMap short[] indexes = new short[size]; BitmapCharacter[] chars = new BitmapCharacter[size]; int i = 0; - for (Entry chr : charset){ + for (Entry chr : charset) { indexes[i] = (short) chr.getKey(); chars[i] = chr.getValue(); i++; @@ -104,7 +104,7 @@ private IntMap readCharset(InputCapsule ic, int style) throws I short[] indexes = ic.readShortArray("indexes"+style, null); Savable[] chars = ic.readSavableArray("chars"+style, null); - for (int i = 0; i < indexes.length; i++){ + for (int i = 0; i < indexes.length; i++) { int index = indexes[i] & 0xFFFF; BitmapCharacter chr = (BitmapCharacter) chars[i]; charset.put(index, chr); @@ -116,11 +116,11 @@ public BitmapCharacterSet() { characters = new IntMap>(); } - public BitmapCharacter getCharacter(int index){ + public BitmapCharacter getCharacter(int index) { return getCharacter(index, 0); } - - public BitmapCharacter getCharacter(int index, int style){ + + public BitmapCharacter getCharacter(int index, int style) { IntMap map = getCharacterSet(style); return map.get(index); } @@ -132,7 +132,7 @@ private IntMap getCharacterSet(int style) { return characters.get(style); } - public void addCharacter(int index, BitmapCharacter ch){ + public void addCharacter(int index, BitmapCharacter ch) { getCharacterSet(0).put(index, ch); } @@ -175,7 +175,7 @@ public int getHeight() { public void setHeight(int height) { this.height = height; } - + /** * Merge two fonts. * If two font have the same style, merge will fail. @@ -197,7 +197,7 @@ public void merge(BitmapCharacterSet styleSet) { if (old != null) { throw new RuntimeException("Can't override old style"); } - + for (Entry charEntry : charset) { BitmapCharacter ch = charEntry.getValue(); ch.setPage(ch.getPage() + this.pageSize); diff --git a/jme3-core/src/main/java/com/jme3/font/BitmapFont.java b/jme3-core/src/main/java/com/jme3/font/BitmapFont.java index fdfdf6c6f2..0fec21364e 100644 --- a/jme3-core/src/main/java/com/jme3/font/BitmapFont.java +++ b/jme3-core/src/main/java/com/jme3/font/BitmapFont.java @@ -44,43 +44,43 @@ public class BitmapFont implements Savable { /** * Specifies horizontal alignment for text. - * - * @see BitmapText#setAlignment(com.jme3.font.BitmapFont.Align) + * + * @see BitmapText#setAlignment(com.jme3.font.BitmapFont.Align) */ public enum Align { - + /** * Align text on the left of the text block */ - Left, - + Left, + /** * Align text in the center of the text block */ - Center, - + Center, + /** * Align text on the right of the text block */ Right } - + /** * Specifies vertical alignment for text. - * - * @see BitmapText#setVerticalAlignment(com.jme3.font.BitmapFont.VAlign) + * + * @see BitmapText#setVerticalAlignment(com.jme3.font.BitmapFont.VAlign) */ public enum VAlign { /** * Align text on the top of the text block */ - Top, - + Top, + /** * Align text in the center of the text block */ - Center, - + Center, + /** * Align text at the bottom of the text block */ @@ -114,14 +114,14 @@ public void setRightToLeft(boolean rightToLeft) { public BitmapFont() { } - public BitmapText createLabel(String content){ + public BitmapText createLabel(String content) { BitmapText label = new BitmapText(this); label.setSize(getCharSet().getRenderedSize()); label.setText(content); return label; } - public float getPreferredSize(){ + public float getPreferredSize() { return getCharSet().getRenderedSize(); } @@ -175,7 +175,7 @@ float getLineHeight(StringBlock sb) { return charSet.getLineHeight() * (sb.getSize() / charSet.getRenderedSize()); } - public float getCharacterAdvance(char curChar, char nextChar, float size){ + public float getCharacterAdvance(char curChar, char nextChar, float size) { BitmapCharacter c = charSet.getCharacter(curChar); if (c == null) return 0f; @@ -212,8 +212,7 @@ public void read(JmeImporter im) throws IOException { glyphParser = (GlyphParser) ic.readSavable("glyphParser", null); } - public float getLineWidth(CharSequence text){ - + public float getLineWidth(CharSequence text) { // This method will probably always be a bit of a maintenance // nightmare since it bases its calculation on a different // routine than the Letters class. The ideal situation would @@ -224,8 +223,8 @@ public float getLineWidth(CharSequence text){ // than Letters does with the same text then it might be better // just to create a Letters object for the sole purpose of // getting a text size. It's less efficient but at least it - // would be accurate. - + // would be accurate. + // And here I am mucking around in here again... // // A font character has a few values that are pertinent to the @@ -242,11 +241,11 @@ public float getLineWidth(CharSequence text){ // So, a width should be calculated in a similar way. Start with // -xOffset + xAdvance for the first character and then each subsequent // character is just xAdvance more 'width'. - // + // // The kerning amount from one character to the next affects the - // cursor position of that next character and thus the ultimate width + // cursor position of that next character and thus the ultimate width // and so must be factored in also. - + float lineWidth = 0f; float maxLineWidth = 0f; char lastChar = 0; @@ -255,9 +254,9 @@ public float getLineWidth(CharSequence text){ float sizeScale = 1f; CharSequence characters = glyphParser != null ? glyphParser.parse(text) : text; - for (int i = 0; i < characters.length(); i++){ + for (int i = 0; i < characters.length(); i++) { char theChar = characters.charAt(i); - if (theChar == '\n'){ + if (theChar == '\n') { maxLineWidth = Math.max(maxLineWidth, lineWidth); lineWidth = 0f; firstCharOfLine = true; @@ -308,7 +307,7 @@ public float getLineWidth(CharSequence text){ // we just added by the appropriate amount. lineWidth += c.getXOffset() * sizeScale; } - } else { + } else { lineWidth += xAdvance; } } @@ -327,13 +326,13 @@ public void merge(BitmapFont newFont) { charSet.merge(newFont.charSet); final int size1 = this.pages.length; final int size2 = newFont.pages.length; - + Material[] tmp = new Material[size1+size2]; System.arraycopy(this.pages, 0, tmp, 0, size1); System.arraycopy(newFont.pages, 0, tmp, size1, size2); - + this.pages = tmp; - + // this.pages = Arrays.copyOf(this.pages, size1+size2); // System.arraycopy(newFont.pages, 0, this.pages, size1, size2); } diff --git a/jme3-core/src/main/java/com/jme3/font/BitmapText.java b/jme3-core/src/main/java/com/jme3/font/BitmapText.java index c48c2a9ab0..eee39bf482 100644 --- a/jme3-core/src/main/java/com/jme3/font/BitmapText.java +++ b/jme3-core/src/main/java/com/jme3/font/BitmapText.java @@ -91,14 +91,14 @@ public BitmapText clone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); textPages = textPages.clone(); - for( int i = 0; i < textPages.length; i++ ) { + for (int i = 0; i < textPages.length; i++) { textPages[i] = cloner.clone(textPages[i]); } - + // Cannot use the cloner to clone the StringBlock because it // is package private... so we'll forgo the (probably unnecessary) // reference fixup in this case and just clone it directly. @@ -276,7 +276,8 @@ public float getLineWidth() { if (textBox != null) { return Math.max(letters.getTotalWidth(), textBox.width); } - // Please note that BitmapText.getLineWidth() might differ from Font.getLineWidth() --> scale it with Font.getPreferredSize()/BitmapText.getSize() + // Please note that BitMaptext.getLineWidth() might differ from Font.getLineWidth() + // --> scale it with Font.getPreferredSize()/BitMaptext.getSize() return letters.getTotalWidth(); } diff --git a/jme3-core/src/main/java/com/jme3/font/BitmapTextPage.java b/jme3-core/src/main/java/com/jme3/font/BitmapTextPage.java index 877e8154c1..c4ac9b26f0 100644 --- a/jme3-core/src/main/java/com/jme3/font/BitmapTextPage.java +++ b/jme3-core/src/main/java/com/jme3/font/BitmapTextPage.java @@ -128,7 +128,7 @@ public BitmapTextPage clone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { Mesh originalMesh = this.mesh; @@ -138,7 +138,7 @@ public void cloneFields( Cloner cloner, Object original ) { // BitmapText instances will clobber one another. // But if we were already deep cloning meshes then we don't // want to do it again... so we'll check first. - if( this.mesh == originalMesh ) { + if (this.mesh == originalMesh) { this.mesh = mesh.deepClone(); } } diff --git a/jme3-core/src/main/java/com/jme3/font/ColorTags.java b/jme3-core/src/main/java/com/jme3/font/ColorTags.java index 85d260fe5a..a64806a785 100644 --- a/jme3-core/src/main/java/com/jme3/font/ColorTags.java +++ b/jme3-core/src/main/java/com/jme3/font/ColorTags.java @@ -57,14 +57,14 @@ class ColorTags { ColorTags(String seq) { setText(seq); } - + /** * @return text without color tags */ String getPlainText() { return text; } - + LinkedList getTags() { return colors; } @@ -96,34 +96,34 @@ void setText(final String charSeq) { } } - void setBaseAlpha( float alpha ) { + void setBaseAlpha(float alpha) { this.baseAlpha = alpha; - if( alpha == -1 ) { + if (alpha == -1) { // Need to reinitialize from the original text setText(original); return; } - - // Else set the alpha for all of them - for( Range r : colors ) { + + // Else set the alpha for all of them + for (Range r : colors) { r.color.a = alpha; } } - + /** * Sets the colors of all ranges, overriding any color tags * that were in the original text. - */ - void setBaseColor( ColorRGBA color ) { + */ + void setBaseColor(ColorRGBA color) { // There are times when the alpha is directly modified // and the caller may have passed a constant... so we // should clone it. color = color.clone(); - for( Range r : colors ) { + for (Range r : colors) { r.color = color; } } - + class Range { int start; ColorRGBA color; @@ -140,7 +140,7 @@ class Range { } else if (colorStr.length() == 8) { color.a = Integer.parseInt(colorStr.subSequence(6,8).toString(), 16) / 255f; - } + } } else { color.set(Integer.parseInt(Character.toString(colorStr.charAt(0)), 16) / 15f, Integer.parseInt(Character.toString(colorStr.charAt(1)), 16) / 15f, diff --git a/jme3-core/src/main/java/com/jme3/font/LetterQuad.java b/jme3-core/src/main/java/com/jme3/font/LetterQuad.java index 5ac7391c31..2611a059f2 100644 --- a/jme3-core/src/main/java/com/jme3/font/LetterQuad.java +++ b/jme3-core/src/main/java/com/jme3/font/LetterQuad.java @@ -70,7 +70,7 @@ class LetterQuad { private float alignX; private float alignY; private float sizeScale = 1; - + /** * create head / tail * @param font @@ -86,7 +86,7 @@ protected LetterQuad(BitmapFont font, boolean rightToLeft) { /** * create letter and append to previous LetterQuad - * + * * @param c * @param prev previous character */ @@ -99,7 +99,7 @@ protected LetterQuad(char c, LetterQuad prev) { setBitmapChar(c); prev.insert(this); } - + LetterQuad addNextCharacter(char c) { LetterQuad n = new LetterQuad(c, this); return n; @@ -108,11 +108,11 @@ LetterQuad addNextCharacter(char c) { BitmapCharacter getBitmapChar() { return bitmapChar; } - + char getChar() { return c; } - + int getIndex() { return index; } @@ -147,11 +147,11 @@ float getV0() { float getV1() { return v1; } - - boolean isRightToLeft(){ + + boolean isRightToLeft() { return rightToLeft; } - + boolean isInvalid() { return x0 == Integer.MIN_VALUE; } @@ -159,7 +159,7 @@ boolean isInvalid() { boolean isInvalid(StringBlock block) { return isInvalid(block, 0); } - + boolean isInvalid(StringBlock block, float gap) { if (isHead() || isTail()) return false; @@ -177,25 +177,25 @@ boolean isInvalid(StringBlock block, float gap) { return x0 > 0 && bound.x+bound.width-gap < getX1(); } } - + void clip(StringBlock block) { Rectangle bound = block.getTextBox(); if (bound == null) return; - + // Clip the right x position and texture coordinate // to the string block float x1 = Math.min(bound.x + bound.width, x0 + width); float newWidth = x1 - x0; if (isRightToLeft()) newWidth = x1; // only the available space to the left - if( newWidth == width ) + if (newWidth == width) return; - + float rescale = newWidth / width; u1 = u0 + (u1 - u0) * rescale; - width = newWidth; + width = newWidth; } - + float getX0() { return x0; } @@ -218,11 +218,11 @@ float getY0() { float getY1() { return y0-height; } - + float getWidth() { return width; } - + float getHeight() { return height; } @@ -234,7 +234,7 @@ void insert(LetterQuad ins) { ins.previous = this; n.previous = ins; } - + void invalidate() { eol = isLineFeed(); setBitmapChar(font.getCharSet().getCharacter(c, style)); @@ -260,20 +260,20 @@ LetterQuad remove() { void setPrevious(LetterQuad before) { this.previous = before; } - + void setStyle(int style) { this.style = style; invalidate(); } - + void setColor(ColorRGBA color) { this.colorInt = color.asIntRGBA(); invalidate(); } void setAlpha(float alpha) { - int i = (int)(alpha * 255) & 0xFF; - colorInt = (colorInt & 0xffffff00) | i; + int i = (int) (alpha * 255) & 0xFF; + colorInt = (colorInt & 0xffffff00) | i; invalidate(); } @@ -282,7 +282,7 @@ void setBitmapChar(char c) { BitmapCharacter bm = charSet.getCharacter(c, style); setBitmapChar(bm); } - + void setBitmapChar(BitmapCharacter bitmapChar) { x0 = Integer.MIN_VALUE; y0 = Integer.MIN_VALUE; @@ -290,7 +290,7 @@ void setBitmapChar(BitmapCharacter bitmapChar) { height = Integer.MIN_VALUE; alignX = 0; alignY = 0; - + BitmapCharacterSet charSet = font.getCharSet(); this.bitmapChar = bitmapChar; if (bitmapChar != null) { @@ -425,22 +425,22 @@ void update(StringBlock block) { xAdvance = bound.x-x0; } } - + /** * add temporary linewrap indicator */ void setEndOfLine() { this.eol = true; } - + boolean isEndOfLine() { return eol; } - + boolean isLineWrap() { return !isHead() && !isTail() && bitmapChar == null && c == Character.MIN_VALUE; } - + private float computeLineY(StringBlock block) { if (isHead()) { return getBound(block).y; @@ -451,16 +451,16 @@ private float computeLineY(StringBlock block) { } } - + boolean isLineStart() { return x0 == 0 || (previous != null && previous.eol); } - + boolean isBlank() { return c == ' ' || isTab(); } - - public void storeToArrays(float[] pos, float[] tc, short[] idx, byte[] colors, int quadIdx){ + + public void storeToArrays(float[] pos, float[] tc, short[] idx, byte[] colors, int quadIdx) { float x = x0+alignX; float y = y0-alignY; float xpw = x+width; @@ -495,8 +495,8 @@ public void storeToArrays(float[] pos, float[] tc, short[] idx, byte[] colors, i idx[0] = i0; idx[1] = i1; idx[2] = i2; idx[3] = i0; idx[4] = i2; idx[5] = i3; } - - public void appendPositions(FloatBuffer fb){ + + public void appendPositions(FloatBuffer fb) { float sx = x0+alignX; float sy = y0-alignY; float ex = sx+width; @@ -509,21 +509,21 @@ public void appendPositions(FloatBuffer fb){ fb.put(ex).put(sy).put(0f); } - public void appendPositions(ShortBuffer sb){ + public void appendPositions(ShortBuffer sb) { final float x1 = getX1(); final float y1 = getY1(); short x = (short) x0; short y = (short) y0; short xpw = (short) (x1); short ymh = (short) (y1); - + sb.put(x).put(y).put((short)0); sb.put(x).put(ymh).put((short)0); sb.put(xpw).put(ymh).put((short)0); sb.put(xpw).put(y).put((short)0); } - public void appendTexCoords(FloatBuffer fb){ + public void appendTexCoords(FloatBuffer fb) { // flip coords to be compatible with OGL float v0 = 1 - this.v0; float v1 = 1 - this.v1; @@ -538,14 +538,14 @@ public void appendTexCoords(FloatBuffer fb){ fb.put(u1).put(v0); } - public void appendColors(ByteBuffer bb){ + public void appendColors(ByteBuffer bb) { bb.putInt(colorInt); bb.putInt(colorInt); bb.putInt(colorInt); bb.putInt(colorInt); } - public void appendIndices(ShortBuffer sb, int quadIndex){ + public void appendIndices(ShortBuffer sb, int quadIndex) { // each quad has 4 indices short v0 = (short) (quadIndex * 4); short v1 = (short) (v0 + 1); @@ -580,9 +580,9 @@ float getAlignY() { boolean isLineFeed() { return c == '\n'; } - + boolean isTab() { return c == '\t'; } - + } diff --git a/jme3-core/src/main/java/com/jme3/font/Letters.java b/jme3-core/src/main/java/com/jme3/font/Letters.java index 0f63a052ac..0b9473d03e 100644 --- a/jme3-core/src/main/java/com/jme3/font/Letters.java +++ b/jme3-core/src/main/java/com/jme3/font/Letters.java @@ -83,7 +83,7 @@ void setText(final String text) { if (baseColor != null) { // Give the letter a default color if // one has been provided. - l.setColor( baseColor ); + l.setColor(baseColor); } } } @@ -170,7 +170,7 @@ void update() { // Clear the rest up to the next line feed. // = for texts attached to a text block, all coming characters are cleared except a linefeed is explicitly used - for( LetterQuad q = l.getNext(); !q.isTail() && !q.isLineFeed(); q = q.getNext() ) { + for (LetterQuad q = l.getNext(); !q.isTail() && !q.isLineFeed(); q = q.getNext()) { q.setBitmapChar(null); q.update(block); } @@ -395,10 +395,10 @@ void setStyle(int start, int end, int style) { * Sets the base color for all new letter quads and resets * the color of existing letter quads. */ - void setColor( ColorRGBA color ) { + void setColor(ColorRGBA color) { baseColor = color; colorTags.setBaseColor(color); - setColor( 0, block.getText().length(), color ); + setColor(0, block.getText().length(), color); } ColorRGBA getBaseColor() { @@ -424,7 +424,8 @@ float getBaseAlpha() { return baseAlpha; } - void setBaseAlpha( float alpha ) { this.baseAlpha = alpha; + void setBaseAlpha(float alpha) { + this.baseAlpha = alpha; colorTags.setBaseAlpha(alpha); if (alpha == -1) { diff --git a/jme3-core/src/main/java/com/jme3/font/Rectangle.java b/jme3-core/src/main/java/com/jme3/font/Rectangle.java index 5eb5cdd0cb..e40aeb0563 100644 --- a/jme3-core/src/main/java/com/jme3/font/Rectangle.java +++ b/jme3-core/src/main/java/com/jme3/font/Rectangle.java @@ -54,16 +54,17 @@ public Rectangle(float x, float y, float width, float height) { } @Override - public Rectangle clone(){ + public Rectangle clone() { try { return (Rectangle) super.clone(); } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } - + @Override public String toString() { - return getClass().getSimpleName() + "[x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]"; + return getClass().getSimpleName() + + "[x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]"; } } \ No newline at end of file diff --git a/jme3-core/src/main/java/com/jme3/font/StringBlock.java b/jme3-core/src/main/java/com/jme3/font/StringBlock.java index 85fc9ab703..00aa8b0d16 100644 --- a/jme3-core/src/main/java/com/jme3/font/StringBlock.java +++ b/jme3-core/src/main/java/com/jme3/font/StringBlock.java @@ -75,7 +75,7 @@ class StringBlock implements Cloneable { this.kerning = kerning; } - StringBlock(){ + StringBlock() { this.text = ""; this.textBox = null; this.alignment = Align.Left; @@ -85,7 +85,7 @@ class StringBlock implements Cloneable { } @Override - public StringBlock clone(){ + public StringBlock clone() { try { StringBlock clone = (StringBlock) super.clone(); clone.color = color.clone(); @@ -101,7 +101,7 @@ String getText() { return text; } - void setText(String text){ + void setText(String text) { this.text = text == null ? "" : text; } @@ -116,7 +116,7 @@ void setTextBox(Rectangle textBox) { BitmapFont.Align getAlignment() { return alignment; } - + BitmapFont.VAlign getVerticalAlignment() { return valignment; } @@ -124,7 +124,7 @@ BitmapFont.VAlign getVerticalAlignment() { void setAlignment(BitmapFont.Align alignment) { this.alignment = alignment; } - + void setVerticalAlignment(BitmapFont.VAlign alignment) { this.valignment = alignment; } @@ -160,19 +160,19 @@ int getLineCount() { void setLineCount(int lineCount) { this.lineCount = lineCount; } - + LineWrapMode getLineWrapMode() { return wrapType; } - + /** - * available only when bounding is set. setBox() method call is needed in advance. + * available only when bounding is set. setBox() method call is needed in advance. * @param wrap true when word need not be split at the end of the line. */ void setLineWrapMode(LineWrapMode wrap) { this.wrapType = wrap; } - + void setTabWidth(float tabWidth) { this.tabWidth = tabWidth; } @@ -180,11 +180,11 @@ void setTabWidth(float tabWidth) { void setTabPosition(float[] tabs) { this.tabPos = tabs; } - + float getTabWidth() { return tabWidth; } - + float[] getTabPosition() { return tabPos; } diff --git a/jme3-core/src/main/java/com/jme3/input/AbstractJoystick.java b/jme3-core/src/main/java/com/jme3/input/AbstractJoystick.java index c6539abe49..9381f510b7 100644 --- a/jme3-core/src/main/java/com/jme3/input/AbstractJoystick.java +++ b/jme3-core/src/main/java/com/jme3/input/AbstractJoystick.java @@ -46,9 +46,9 @@ public abstract class AbstractJoystick implements Joystick { final private JoyInput joyInput; final private int joyId; final private String name; - - final private List axes = new ArrayList<>(); - final private List buttons = new ArrayList<>(); + + final private List axes = new ArrayList<>(); + final private List buttons = new ArrayList<>(); /** * Creates a new joystick instance. Only used internally. @@ -65,20 +65,20 @@ protected AbstractJoystick(InputManager inputManager, JoyInput joyInput, this.joyId = joyId; this.name = name; } - + protected InputManager getInputManager() { return inputManager; } - + protected JoyInput getJoyInput() { - return joyInput; + return joyInput; } - protected void addAxis( JoystickAxis axis ) { + protected void addAxis(JoystickAxis axis) { axes.add(axis); } - protected void addButton( JoystickButton button ) { + protected void addButton(JoystickButton button) { buttons.add(button); } @@ -88,7 +88,7 @@ protected void addButton( JoystickButton button ) { * @param amount The amount to rumble. Should be between 0 and 1. */ @Override - public void rumble(float amount){ + public void rumble(float amount) { joyInput.setJoyRumble(joyId, amount); } @@ -104,7 +104,7 @@ public void rumble(float amount){ */ @Override @Deprecated - public void assignButton(String mappingName, int buttonId){ + public void assignButton(String mappingName, int buttonId) { if (buttonId < 0 || buttonId >= getButtonCount()) throw new IllegalArgumentException(); @@ -123,23 +123,23 @@ public void assignButton(String mappingName, int buttonId){ */ @Override @Deprecated - public void assignAxis(String positiveMapping, String negativeMapping, int axisId){ - + public void assignAxis(String positiveMapping, String negativeMapping, int axisId) { + // For backwards compatibility - if( axisId == JoyInput.AXIS_POV_X ) { + if (axisId == JoyInput.AXIS_POV_X) { axisId = getPovXAxis().getAxisId(); - } else if( axisId == JoyInput.AXIS_POV_Y ) { + } else if (axisId == JoyInput.AXIS_POV_Y) { axisId = getPovYAxis().getAxisId(); } - + inputManager.addMapping(positiveMapping, new JoyAxisTrigger(joyId, axisId, false)); inputManager.addMapping(negativeMapping, new JoyAxisTrigger(joyId, axisId, true)); } @Override public JoystickAxis getAxis(String logicalId) { - for( JoystickAxis axis : axes ) { - if( axis.getLogicalId().equals(logicalId) ) + for (JoystickAxis axis : axes) { + if (axis.getLogicalId().equals(logicalId)) return axis; } return null; @@ -161,12 +161,12 @@ public List getAxes() { @Override public int getAxisCount() { return axes.size(); - } + } @Override public JoystickButton getButton(String logicalId) { - for( JoystickButton b : buttons ) { - if( b.getLogicalId().equals(logicalId) ) + for (JoystickButton b : buttons) { + if (b.getLogicalId().equals(logicalId)) return b; } return null; @@ -178,7 +178,7 @@ public JoystickButton getButton(String logicalId) { @Override public List getButtons() { return Collections.unmodifiableList(buttons); - } + } /** * Returns the number of buttons on this joystick. @@ -189,7 +189,7 @@ public List getButtons() { public int getButtonCount() { return buttons.size(); } - + /** * Returns the name of this joystick. * @@ -220,7 +220,7 @@ public int getJoyId() { * @see Joystick#assignAxis(java.lang.String, java.lang.String, int) */ @Override - public int getXAxisIndex(){ + public int getXAxisIndex() { return getXAxis().getAxisId(); } @@ -234,12 +234,12 @@ public int getXAxisIndex(){ * @see Joystick#assignAxis(java.lang.String, java.lang.String, int) */ @Override - public int getYAxisIndex(){ + public int getYAxisIndex() { return getYAxis().getAxisId(); } @Override - public String toString(){ + public String toString() { return "Joystick[name=" + name + ", id=" + joyId + ", buttons=" + getButtonCount() + ", axes=" + getAxisCount() + "]"; } diff --git a/jme3-core/src/main/java/com/jme3/input/ChaseCamera.java b/jme3-core/src/main/java/com/jme3/input/ChaseCamera.java index 8538d4c36b..057e729062 100644 --- a/jme3-core/src/main/java/com/jme3/input/ChaseCamera.java +++ b/jme3-core/src/main/java/com/jme3/input/ChaseCamera.java @@ -57,7 +57,7 @@ public class ChaseCamera implements ActionListener, AnalogListener, Control, Jme protected float maxVerticalRotation = FastMath.PI / 2; protected float minDistance = 1.0f; protected float maxDistance = 40.0f; - protected float distance = 20; + protected float distance = 20; protected float rotationSpeed = 1.0f; protected float rotation = 0; protected float trailingRotationInertia = 0.05f; @@ -100,7 +100,7 @@ public class ChaseCamera implements ActionListener, AnalogListener, Control, Jme protected Vector3f temp = new Vector3f(0, 0, 0); protected boolean invertYaxis = false; protected boolean invertXaxis = false; - + /** * @deprecated use {@link CameraInput#CHASECAM_DOWN} */ @@ -201,10 +201,8 @@ public void onAction(String name, boolean keyPressed, float tpf) { } } } - } - @Override public void onAnalog(String name, float value, float tpf) { if (name.equals(CameraInput.CHASECAM_MOVELEFT)) { @@ -236,7 +234,6 @@ public void onAnalog(String name, float value, float tpf) { * @param inputManager (alias created) */ public final void registerWithInput(InputManager inputManager) { - String[] inputs = {CameraInput.CHASECAM_TOGGLEROTATE, CameraInput.CHASECAM_DOWN, CameraInput.CHASECAM_UP, @@ -247,33 +244,45 @@ public final void registerWithInput(InputManager inputManager) { this.inputManager = inputManager; if (!invertYaxis) { - inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); - inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); + inputManager.addMapping(CameraInput.CHASECAM_DOWN, + new MouseAxisTrigger(MouseInput.AXIS_Y, true)); + inputManager.addMapping(CameraInput.CHASECAM_UP, + new MouseAxisTrigger(MouseInput.AXIS_Y, false)); } else { - inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, false)); - inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, true)); + inputManager.addMapping(CameraInput.CHASECAM_DOWN, + new MouseAxisTrigger(MouseInput.AXIS_Y, false)); + inputManager.addMapping(CameraInput.CHASECAM_UP, + new MouseAxisTrigger(MouseInput.AXIS_Y, true)); } - inputManager.addMapping(CameraInput.CHASECAM_ZOOMIN, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); - inputManager.addMapping(CameraInput.CHASECAM_ZOOMOUT, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); + inputManager.addMapping(CameraInput.CHASECAM_ZOOMIN, + new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); + inputManager.addMapping(CameraInput.CHASECAM_ZOOMOUT, + new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); if (!invertXaxis) { - inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, true)); - inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, false)); + inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, + new MouseAxisTrigger(MouseInput.AXIS_X, true)); + inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, + new MouseAxisTrigger(MouseInput.AXIS_X, false)); } else { - inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, false)); - inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, true)); + inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, + new MouseAxisTrigger(MouseInput.AXIS_X, false)); + inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, + new MouseAxisTrigger(MouseInput.AXIS_X, true)); } - inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); - inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); + inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, + new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); + inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, + new MouseButtonTrigger(MouseInput.BUTTON_RIGHT)); inputManager.addListener(this, inputs); } - + /** * Cleans up the input mappings from the input manager. * Undoes the work of registerWithInput(). * @param mgr the InputManager to clean up */ - public void cleanupWithInput(InputManager mgr){ + public void cleanupWithInput(InputManager mgr) { mgr.deleteMapping(CameraInput.CHASECAM_TOGGLEROTATE); mgr.deleteMapping(CameraInput.CHASECAM_DOWN); mgr.deleteMapping(CameraInput.CHASECAM_UP); @@ -614,16 +623,16 @@ public Object jmeClone() { cc.setMaxDistance(getMaxDistance()); cc.setMinDistance(getMinDistance()); return cc; - } + } - @Override - public void cloneFields( Cloner cloner, Object original ) { + @Override + public void cloneFields(Cloner cloner, Object original) { this.target = cloner.clone(target); computePosition(); prevPos = new Vector3f(target.getWorldTranslation()); cam.setLocation(pos); } - + /** * Sets the spatial for the camera control, should only be used internally * @@ -847,7 +856,7 @@ public float getZoomSensitivity() { public void setZoomSensitivity(float zoomSensitivity) { this.zoomSensitivity = zoomSensitivity; } - + /** * Returns the rotation speed when the mouse is moved. * diff --git a/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java b/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java index 3b533de1d1..6e6bff046f 100644 --- a/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java +++ b/jme3-core/src/main/java/com/jme3/input/DefaultJoystickAxis.java @@ -62,8 +62,8 @@ public class DefaultJoystickAxis implements JoystickAxis { * @param deadZone the radius of the dead zone */ public DefaultJoystickAxis(InputManager inputManager, Joystick parent, - int axisIndex, String name, String logicalId, - boolean isAnalog, boolean isRelative, float deadZone ) { + int axisIndex, String name, String logicalId, + boolean isAnalog, boolean isRelative, float deadZone) { this.inputManager = inputManager; this.parent = parent; this.axisIndex = axisIndex; @@ -81,7 +81,7 @@ public DefaultJoystickAxis(InputManager inputManager, Joystick parent, * @param negativeMapping The mapping to receive events when the axis is positive */ @Override - public void assignAxis(String positiveMapping, String negativeMapping){ + public void assignAxis(String positiveMapping, String negativeMapping) { if (axisIndex != -1) { inputManager.addMapping(positiveMapping, new JoyAxisTrigger(parent.getJoyId(), axisIndex, false)); inputManager.addMapping(negativeMapping, new JoyAxisTrigger(parent.getJoyId(), axisIndex, true)); @@ -114,7 +114,7 @@ public String getName() { @Override public String getLogicalId() { return logicalId; - } + } /** * Returns the axisId of this joystick axis. @@ -134,7 +134,7 @@ public int getAxisId() { public boolean isAnalog() { return isAnalog; } - + /** * Returns true if this axis presents relative values. */ @@ -142,7 +142,7 @@ public boolean isAnalog() { public boolean isRelative() { return isRelative; } - + /** * Returns the suggested dead zone for this axis. Values less than this * can be safely ignored. @@ -150,7 +150,7 @@ public boolean isRelative() { @Override public float getDeadZone() { return deadZone; - } + } /** * Sets/overrides the dead zone for this axis. This indicates that values @@ -158,13 +158,13 @@ public float getDeadZone() { * * @param f the desired radius */ - public void setDeadZone( float f ) { + public void setDeadZone(float f) { this.deadZone = f; - } + } @Override - public String toString(){ - return "JoystickAxis[name=" + name + ", parent=" + parent.getName() + ", id=" + axisIndex + public String toString() { + return "JoystickAxis[name=" + name + ", parent=" + parent.getName() + ", id=" + axisIndex + ", logicalId=" + logicalId + ", isAnalog=" + isAnalog + ", isRelative=" + isRelative + ", deadZone=" + deadZone + "]"; } diff --git a/jme3-core/src/main/java/com/jme3/input/DefaultJoystickButton.java b/jme3-core/src/main/java/com/jme3/input/DefaultJoystickButton.java index 7a1b7dbea6..63cc1e9bfe 100644 --- a/jme3-core/src/main/java/com/jme3/input/DefaultJoystickButton.java +++ b/jme3-core/src/main/java/com/jme3/input/DefaultJoystickButton.java @@ -39,21 +39,21 @@ * @author Paul Speed */ public class DefaultJoystickButton implements JoystickButton { - + final private InputManager inputManager; final private Joystick parent; final private int buttonIndex; final private String name; final private String logicalId; - public DefaultJoystickButton( InputManager inputManager, Joystick parent, int buttonIndex, - String name, String logicalId ) { + public DefaultJoystickButton(InputManager inputManager, Joystick parent, int buttonIndex, + String name, String logicalId) { this.inputManager = inputManager; this.parent = parent; this.buttonIndex = buttonIndex; this.name = name; - this.logicalId = logicalId; - } + this.logicalId = logicalId; + } /** * Assign the mapping name to receive events from the given button index @@ -65,14 +65,14 @@ public DefaultJoystickButton( InputManager inputManager, Joystick parent, int bu public void assignButton(String mappingName) { inputManager.addMapping(mappingName, new JoyButtonTrigger(parent.getJoyId(), buttonIndex)); } - + /** * Returns the joystick to which this axis object belongs. */ @Override public Joystick getJoystick() { return parent; - } + } /** * Returns the name of this joystick. @@ -82,7 +82,7 @@ public Joystick getJoystick() { @Override public String getName() { return name; - } + } /** * Returns the logical identifier of this joystick axis. @@ -92,10 +92,10 @@ public String getName() { @Override public String getLogicalId() { return logicalId; - } + } /** - * Returns the unique buttonId of this joystick axis within a given + * Returns the unique buttonId of this joystick axis within a given * InputManager context. * * @return the buttonId of this joystick axis. @@ -104,10 +104,10 @@ public String getLogicalId() { public int getButtonId() { return buttonIndex; } - + @Override - public String toString(){ - return "JoystickButton[name=" + getName() + ", parent=" + parent.getName() + ", id=" + getButtonId() + public String toString() { + return "JoystickButton[name=" + getName() + ", parent=" + parent.getName() + ", id=" + getButtonId() + ", logicalId=" + getLogicalId() + "]"; } } diff --git a/jme3-core/src/main/java/com/jme3/input/FlyByCamera.java b/jme3-core/src/main/java/com/jme3/input/FlyByCamera.java index 3248822c0f..39e40725fd 100644 --- a/jme3-core/src/main/java/com/jme3/input/FlyByCamera.java +++ b/jme3-core/src/main/java/com/jme3/input/FlyByCamera.java @@ -114,7 +114,7 @@ public class FlyByCamera implements AnalogListener, ActionListener { * * @param cam camera to be controlled (not null) */ - public FlyByCamera(Camera cam){ + public FlyByCamera(Camera cam) { this.cam = cam; initialUpVec = cam.getUp().clone(); } @@ -290,25 +290,27 @@ public void registerWithInput(InputManager inputManager){ } } - protected void mapJoystick( Joystick joystick ) { - + protected void mapJoystick(Joystick joystick) { // Map it differently if there are Z axis - if( joystick.getAxis( JoystickAxis.Z_ROTATION ) != null && joystick.getAxis( JoystickAxis.Z_AXIS ) != null ) { + if (joystick.getAxis(JoystickAxis.Z_ROTATION) != null + && joystick.getAxis(JoystickAxis.Z_AXIS) != null) { // Make the left stick move - joystick.getXAxis().assignAxis( CameraInput.FLYCAM_STRAFERIGHT, CameraInput.FLYCAM_STRAFELEFT ); - joystick.getYAxis().assignAxis( CameraInput.FLYCAM_BACKWARD, CameraInput.FLYCAM_FORWARD ); + joystick.getXAxis().assignAxis(CameraInput.FLYCAM_STRAFERIGHT, CameraInput.FLYCAM_STRAFELEFT); + joystick.getYAxis().assignAxis(CameraInput.FLYCAM_BACKWARD, CameraInput.FLYCAM_FORWARD); // And the right stick control the camera - joystick.getAxis( JoystickAxis.Z_ROTATION ).assignAxis( CameraInput.FLYCAM_DOWN, CameraInput.FLYCAM_UP ); - joystick.getAxis( JoystickAxis.Z_AXIS ).assignAxis( CameraInput.FLYCAM_RIGHT, CameraInput.FLYCAM_LEFT ); + joystick.getAxis(JoystickAxis.Z_ROTATION) + .assignAxis(CameraInput.FLYCAM_DOWN, CameraInput.FLYCAM_UP); + joystick.getAxis(JoystickAxis.Z_AXIS) + .assignAxis(CameraInput.FLYCAM_RIGHT, CameraInput.FLYCAM_LEFT); // And let the dpad be up and down joystick.getPovYAxis().assignAxis(CameraInput.FLYCAM_RISE, CameraInput.FLYCAM_LOWER); - if( joystick.getButton( "Button 8" ) != null ) { + if( joystick.getButton("Button 8") != null) { // Let the standard select button be the y invert toggle - joystick.getButton( "Button 8" ).assignButton( CameraInput.FLYCAM_INVERTY ); + joystick.getButton("Button 8").assignButton(CameraInput.FLYCAM_INVERTY); } } else { @@ -322,14 +324,14 @@ protected void mapJoystick( Joystick joystick ) { /** * Unregister this controller from its input manager. */ - public void unregisterInput(){ + public void unregisterInput() { if (inputManager == null) { return; } for (String s : mappings) { if (inputManager.hasMapping(s)) { - inputManager.deleteMapping( s ); + inputManager.deleteMapping(s); } } @@ -337,7 +339,7 @@ public void unregisterInput(){ inputManager.setCursorVisible(!dragToRotate); Joystick[] joysticks = inputManager.getJoysticks(); - if (joysticks != null && joysticks.length > 0){ + if (joysticks != null && joysticks.length > 0) { // No way to unassign axis } } @@ -348,11 +350,11 @@ public void unregisterInput(){ * @param value rotation amount * @param axis direction of rotation (a unit vector) */ - protected void rotateCamera(float value, Vector3f axis){ - if (dragToRotate){ - if (canRotate){ + protected void rotateCamera(float value, Vector3f axis) { + if (dragToRotate) { + if (canRotate) { // value = -value; - }else{ + } else { return; } } @@ -380,7 +382,7 @@ protected void rotateCamera(float value, Vector3f axis){ * * @param value zoom amount */ - protected void zoomCamera(float value){ + protected void zoomCamera(float value) { float newFov = cam.getFov() + value * 0.1F * zoomSpeed; if (newFov > 0) { cam.setFov(newFov); @@ -392,7 +394,7 @@ protected void zoomCamera(float value){ * * @param value translation amount */ - protected void riseCamera(float value){ + protected void riseCamera(float value) { Vector3f vel = initialUpVec.mult(value * moveSpeed); Vector3f pos = cam.getLocation().clone(); @@ -410,13 +412,13 @@ protected void riseCamera(float value){ * @param value translation amount * @param sideways true→left, false→forward */ - protected void moveCamera(float value, boolean sideways){ + protected void moveCamera(float value, boolean sideways) { Vector3f vel = new Vector3f(); Vector3f pos = cam.getLocation().clone(); if (sideways){ cam.getLeft(vel); - }else{ + } else { cam.getDirection(vel); } vel.multLocal(value * moveSpeed); @@ -441,29 +443,29 @@ public void onAnalog(String name, float value, float tpf) { if (!enabled) return; - if (name.equals(CameraInput.FLYCAM_LEFT)){ + if (name.equals(CameraInput.FLYCAM_LEFT)) { rotateCamera(value, initialUpVec); - }else if (name.equals(CameraInput.FLYCAM_RIGHT)){ + } else if (name.equals(CameraInput.FLYCAM_RIGHT)) { rotateCamera(-value, initialUpVec); - }else if (name.equals(CameraInput.FLYCAM_UP)){ + } else if (name.equals(CameraInput.FLYCAM_UP)) { rotateCamera(-value * (invertY ? -1 : 1), cam.getLeft()); - }else if (name.equals(CameraInput.FLYCAM_DOWN)){ + } else if (name.equals(CameraInput.FLYCAM_DOWN)) { rotateCamera(value * (invertY ? -1 : 1), cam.getLeft()); - }else if (name.equals(CameraInput.FLYCAM_FORWARD)){ + } else if (name.equals(CameraInput.FLYCAM_FORWARD)) { moveCamera(value, false); - }else if (name.equals(CameraInput.FLYCAM_BACKWARD)){ + } else if (name.equals(CameraInput.FLYCAM_BACKWARD)) { moveCamera(-value, false); - }else if (name.equals(CameraInput.FLYCAM_STRAFELEFT)){ + } else if (name.equals(CameraInput.FLYCAM_STRAFELEFT)) { moveCamera(value, true); - }else if (name.equals(CameraInput.FLYCAM_STRAFERIGHT)){ + } else if (name.equals(CameraInput.FLYCAM_STRAFERIGHT)) { moveCamera(-value, true); - }else if (name.equals(CameraInput.FLYCAM_RISE)){ + } else if (name.equals(CameraInput.FLYCAM_RISE)) { riseCamera(value); - }else if (name.equals(CameraInput.FLYCAM_LOWER)){ + } else if (name.equals(CameraInput.FLYCAM_LOWER)) { riseCamera(-value); - }else if (name.equals(CameraInput.FLYCAM_ZOOMIN)){ + } else if (name.equals(CameraInput.FLYCAM_ZOOMIN)) { zoomCamera(value); - }else if (name.equals(CameraInput.FLYCAM_ZOOMOUT)){ + } else if (name.equals(CameraInput.FLYCAM_ZOOMOUT)) { zoomCamera(-value); } } @@ -480,12 +482,12 @@ public void onAction(String name, boolean value, float tpf) { if (!enabled) return; - if (name.equals(CameraInput.FLYCAM_ROTATEDRAG) && dragToRotate){ + if (name.equals(CameraInput.FLYCAM_ROTATEDRAG) && dragToRotate) { canRotate = value; inputManager.setCursorVisible(!value); } else if (name.equals(CameraInput.FLYCAM_INVERTY)) { // Invert the "up" direction. - if( !value ) { + if (!value) { invertY = !invertY; } } diff --git a/jme3-core/src/main/java/com/jme3/input/JoystickCompatibilityMappings.java b/jme3-core/src/main/java/com/jme3/input/JoystickCompatibilityMappings.java index ffff931917..105440855d 100644 --- a/jme3-core/src/main/java/com/jme3/input/JoystickCompatibilityMappings.java +++ b/jme3-core/src/main/java/com/jme3/input/JoystickCompatibilityMappings.java @@ -408,7 +408,7 @@ public static void addButtonMapping(String stickName, String sourceComponentId, * Adds a single Joystick axis or button remapping based on the * joystick's name and axis/button name. The "remap" value will be * used instead. - * + * * @param stickName which joystick (not null) * @param sourceComponentId the name to be remapped * @param remapId the remapped name diff --git a/jme3-core/src/main/java/com/jme3/input/controls/JoyAxisTrigger.java b/jme3-core/src/main/java/com/jme3/input/controls/JoyAxisTrigger.java index c678ba909d..d09c9d1019 100644 --- a/jme3-core/src/main/java/com/jme3/input/controls/JoyAxisTrigger.java +++ b/jme3-core/src/main/java/com/jme3/input/controls/JoyAxisTrigger.java @@ -52,7 +52,7 @@ public JoyAxisTrigger(int joyId, int axisId, boolean negative) { this.negative = negative; } - public static int joyAxisHash(int joyId, int joyAxis, boolean negative){ + public static int joyAxisHash(int joyId, int joyAxis, boolean negative) { assert joyAxis >= 0 && joyAxis <= 255; return (2048 * joyId) | (negative ? 1280 : 1024) | (joyAxis & 0xff); } @@ -78,5 +78,5 @@ public String getName() { public int triggerHashCode() { return joyAxisHash(joyId, axisId, negative); } - + } diff --git a/jme3-core/src/main/java/com/jme3/input/controls/JoyButtonTrigger.java b/jme3-core/src/main/java/com/jme3/input/controls/JoyButtonTrigger.java index 5c4030775e..5985e62bc7 100644 --- a/jme3-core/src/main/java/com/jme3/input/controls/JoyButtonTrigger.java +++ b/jme3-core/src/main/java/com/jme3/input/controls/JoyButtonTrigger.java @@ -39,7 +39,7 @@ public class JoyButtonTrigger implements Trigger { /** * Use {@link Joystick#assignButton(java.lang.String, int) } instead. - * + * * @param joyId the ID of a joystick * @param axisId the ID of a joystick axis */ @@ -48,7 +48,7 @@ public JoyButtonTrigger(int joyId, int axisId) { this.buttonId = axisId; } - public static int joyButtonHash(int joyId, int joyButton){ + public static int joyButtonHash(int joyId, int joyButton) { assert joyButton >= 0 && joyButton <= 255; return (2048 * joyId) | 1536 | (joyButton & 0xff); } diff --git a/jme3-core/src/main/java/com/jme3/input/event/KeyInputEvent.java b/jme3-core/src/main/java/com/jme3/input/event/KeyInputEvent.java index 1f81c450bd..f693d2caad 100644 --- a/jme3-core/src/main/java/com/jme3/input/event/KeyInputEvent.java +++ b/jme3-core/src/main/java/com/jme3/input/event/KeyInputEvent.java @@ -35,7 +35,7 @@ /** * Keyboard key event. - * + * * @author Kirill Vainer */ public class KeyInputEvent extends InputEvent { @@ -54,7 +54,7 @@ public KeyInputEvent(int keyCode, char keyChar, boolean pressed, boolean repeati /** * Returns the key character. Returns 0 if the key has no character. - * + * * @return the key character. 0 if the key has no character. */ public char getKeyChar() { @@ -65,7 +65,7 @@ public char getKeyChar() { * The key code. *

    * See KEY_*** constants in {@link KeyInput}. - * + * * @return key code. */ public int getKeyCode() { @@ -74,7 +74,7 @@ public int getKeyCode() { /** * Returns true if this event is key press, false is it was a key release. - * + * * @return true if this event is key press, false is it was a key release. */ public boolean isPressed() { @@ -83,7 +83,7 @@ public boolean isPressed() { /** * Returns true if this event is a repeat event. - * + * * @return true if this event is a repeat event */ public boolean isRepeating() { @@ -92,7 +92,7 @@ public boolean isRepeating() { /** * Returns true if this event is a key release, false if it was a key press. - * + * * @return true if this event is a key release, false if it was a key press. */ public boolean isReleased() { @@ -100,16 +100,16 @@ public boolean isReleased() { } @Override - public String toString(){ + public String toString() { String str = "Key(CODE="+keyCode; if (keyChar != '\0') str = str + ", CHAR=" + keyChar; - - if (repeating){ + + if (repeating) { return str + ", REPEATING)"; - }else if (pressed){ + } else if (pressed) { return str + ", PRESSED)"; - }else{ + } else { return str + ", RELEASED)"; } } diff --git a/jme3-core/src/main/java/com/jme3/input/event/MouseButtonEvent.java b/jme3-core/src/main/java/com/jme3/input/event/MouseButtonEvent.java index ebbba9c016..83c383cef7 100644 --- a/jme3-core/src/main/java/com/jme3/input/event/MouseButtonEvent.java +++ b/jme3-core/src/main/java/com/jme3/input/event/MouseButtonEvent.java @@ -35,7 +35,7 @@ /** * Mouse button press/release event. - * + * * @author Kirill Vainer */ public class MouseButtonEvent extends InputEvent { @@ -56,7 +56,7 @@ public MouseButtonEvent(int btnIndex, boolean pressed, int x, int y) { * Returns the mouse button index. *

    * See constants in {@link MouseInput}. - * + * * @return the mouse button index. */ public int getButtonIndex() { @@ -65,7 +65,7 @@ public int getButtonIndex() { /** * Returns true if the mouse button was pressed, false if it was released. - * + * * @return true if the mouse button was pressed, false if it was released. */ public boolean isPressed() { @@ -74,13 +74,13 @@ public boolean isPressed() { /** * Returns true if the mouse button was released, false if it was pressed. - * + * * @return true if the mouse button was released, false if it was pressed. */ public boolean isReleased() { return !pressed; } - + /** * The X coordinate of the mouse when the event was generated. * @return X coordinate of the mouse when the event was generated. @@ -88,7 +88,7 @@ public boolean isReleased() { public int getX() { return x; } - + /** * The Y coordinate of the mouse when the event was generated. * @return Y coordinate of the mouse when the event was generated. @@ -96,15 +96,14 @@ public int getX() { public int getY() { return y; } - + @Override public String toString(){ String str = "MouseButton(BTN="+btnIndex; - if (pressed){ + if (pressed) { return str + ", PRESSED)"; - }else{ + } else { return str + ", RELEASED)"; } } - } diff --git a/jme3-core/src/main/java/com/jme3/light/DefaultLightFilter.java b/jme3-core/src/main/java/com/jme3/light/DefaultLightFilter.java index 08ff78ded6..8734ae92aa 100644 --- a/jme3-core/src/main/java/com/jme3/light/DefaultLightFilter.java +++ b/jme3-core/src/main/java/com/jme3/light/DefaultLightFilter.java @@ -52,7 +52,7 @@ public DefaultLightFilter() { public DefaultLightFilter(LightProbeBlendingStrategy probeBlendStrategy) { this.probeBlendStrategy = probeBlendStrategy; } - + @Override public void setCamera(Camera camera) { this.camera = camera; @@ -66,7 +66,7 @@ public void filterLights(Geometry geometry, LightList filteredLightList) { TempVars vars = TempVars.get(); try { LightList worldLights = geometry.getWorldLightList(); - + for (int i = 0; i < worldLights.size(); i++) { Light light = worldLights.get(i); @@ -86,27 +86,27 @@ public void filterLights(Geometry geometry, LightList filteredLightList) { } BoundingVolume bv = geometry.getWorldBound(); - + if (bv instanceof BoundingBox) { - if (!light.intersectsBox((BoundingBox)bv, vars)) { + if (!light.intersectsBox((BoundingBox) bv, vars)) { continue; } } else if (bv instanceof BoundingSphere) { - if (!Float.isInfinite( ((BoundingSphere)bv).getRadius() )) { - if (!light.intersectsSphere((BoundingSphere)bv, vars)) { + if (!Float.isInfinite(((BoundingSphere) bv).getRadius())) { + if (!light.intersectsSphere((BoundingSphere) bv, vars)) { continue; } } } - + if (light.getType() == Light.Type.Probe) { probeBlendStrategy.registerProbe((LightProbe) light); } else { filteredLightList.add(light); } - + } - + probeBlendStrategy.populateProbes(geometry, filteredLightList); } finally { @@ -114,7 +114,7 @@ public void filterLights(Geometry geometry, LightList filteredLightList) { } } - public void setLightProbeBlendingStrategy(LightProbeBlendingStrategy strategy){ + public void setLightProbeBlendingStrategy(LightProbeBlendingStrategy strategy) { probeBlendStrategy = strategy; } diff --git a/jme3-core/src/main/java/com/jme3/light/LightList.java b/jme3-core/src/main/java/com/jme3/light/LightList.java index fd59ab5fc6..97c4c29820 100644 --- a/jme3-core/src/main/java/com/jme3/light/LightList.java +++ b/jme3-core/src/main/java/com/jme3/light/LightList.java @@ -72,7 +72,7 @@ else if (l1.lastDistance > l2.lastDistance) /** * constructor for serialization. Do not use */ - protected LightList(){ + protected LightList() { } /** @@ -93,11 +93,11 @@ public LightList(Spatial owner) { * * @param owner the desired owner (alias created) */ - public void setOwner(Spatial owner){ + public void setOwner(Spatial owner) { this.owner = owner; } - private void doubleSize(){ + private void doubleSize() { Light[] temp = new Light[list.length * 2]; float[] temp2 = new float[list.length * 2]; System.arraycopy(list, 0, temp, 0, list.length); @@ -125,17 +125,17 @@ public void add(Light l) { * * @param index the zero-based index of the Light to be removed (≥0) */ - public void remove(int index){ + public void remove(int index) { if (index >= listSize || index < 0) throw new IndexOutOfBoundsException(); listSize --; - if (index == listSize){ + if (index == listSize) { list[listSize] = null; return; } - for (int i = index; i < listSize; i++){ + for (int i = index; i < listSize; i++) { list[i] = list[i+1]; } list[listSize] = null; @@ -146,9 +146,9 @@ public void remove(int index){ * * @param l the light to remove */ - public void remove(Light l){ - for (int i = 0; i < listSize; i++){ - if (list[i] == l){ + public void remove(Light l) { + for (int i = 0; i < listSize; i++) { + if (list[i] == l) { remove(i); return; } @@ -158,7 +158,7 @@ public void remove(Light l){ /** * @return The size of the list. */ - public int size(){ + public int size() { return listSize; } @@ -167,7 +167,7 @@ public int size(){ * @return the light at the given index. * @throws IndexOutOfBoundsException If the given index is outside bounds. */ - public Light get(int num){ + public Light get(int num) { if (num >= listSize || num < 0) throw new IndexOutOfBoundsException(); @@ -210,9 +210,9 @@ public void sort(boolean transformChanged) { System.arraycopy(list, 0, tlist, 0, list.length); } - if (transformChanged){ + if (transformChanged) { // check distance of each light - for (int i = 0; i < listSize; i++){ + for (int i = 0; i < listSize; i++) { list[i].computeLastDistance(owner); } } @@ -229,37 +229,37 @@ public void sort(boolean transformChanged) { * @param local the local-space LightList (not null) * @param parent the parent's world-space LightList */ - public void update(LightList local, LightList parent){ + public void update(LightList local, LightList parent) { // clear the list as it will be reconstructed // using the arguments clear(); - while (list.length <= local.listSize){ + while (list.length <= local.listSize) { doubleSize(); } // add the lights from the local list System.arraycopy(local.list, 0, list, 0, local.listSize); - for (int i = 0; i < local.listSize; i++){ + for (int i = 0; i < local.listSize; i++) { // list[i] = local.list[i]; distToOwner[i] = Float.NEGATIVE_INFINITY; } // if the spatial has a parent node, add the lights // from the parent list as well - if (parent != null){ + if (parent != null) { int sz = local.listSize + parent.listSize; while (list.length <= sz) doubleSize(); - for (int i = 0; i < parent.listSize; i++){ + for (int i = 0; i < parent.listSize; i++) { int p = i + local.listSize; list[p] = parent.list[i]; distToOwner[p] = Float.NEGATIVE_INFINITY; } listSize = local.listSize + parent.listSize; - }else{ + } else { listSize = local.listSize; } } @@ -271,7 +271,7 @@ public void update(LightList local, LightList parent){ */ @Override public Iterator iterator() { - return new Iterator(){ + return new Iterator() { int index = 0; @@ -296,8 +296,8 @@ public void remove() { } @Override - public LightList clone(){ - try{ + public LightList clone() { + try { LightList clone = (LightList) super.clone(); clone.owner = null; @@ -306,24 +306,24 @@ public LightList clone(){ clone.tlist = null; // list used for sorting only return clone; - }catch (CloneNotSupportedException ex){ + } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } @Override public LightList jmeClone() { - try{ + try { LightList clone = (LightList)super.clone(); clone.tlist = null; // list used for sorting only return clone; - }catch (CloneNotSupportedException ex){ + } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.owner = cloner.clone(owner); this.list = cloner.clone(list); this.distToOwner = cloner.clone(distToOwner); @@ -335,7 +335,7 @@ public void write(JmeExporter ex) throws IOException { // oc.write(owner, "owner", null); ArrayList lights = new ArrayList<>(); - for (int i = 0; i < listSize; i++){ + for (int i = 0; i < listSize; i++) { lights.add(list[i]); } oc.writeSavableArrayList(lights, "lights", null); @@ -355,11 +355,10 @@ public void read(JmeImporter im) throws IOException { list = new Light[arraySize]; distToOwner = new float[arraySize]; - for (int i = 0; i < listSize; i++){ + for (int i = 0; i < listSize; i++) { list[i] = lights.get(i); } Arrays.fill(distToOwner, Float.NEGATIVE_INFINITY); } - } diff --git a/jme3-core/src/main/java/com/jme3/light/PointLight.java b/jme3-core/src/main/java/com/jme3/light/PointLight.java index 4d9f306a06..959147c9a0 100644 --- a/jme3-core/src/main/java/com/jme3/light/PointLight.java +++ b/jme3-core/src/main/java/com/jme3/light/PointLight.java @@ -51,10 +51,10 @@ * A point light emits light from a given position into all directions in space. * E.g a lamp or a bright effect. Point light positions are in world space. *

    - * In addition to a position, point lights also have a radius which - * can be used to attenuate the influence of the light depending on the + * In addition to a position, point lights also have a radius which + * can be used to attenuate the influence of the light depending on the * distance between the light and the affected object. - * + * */ public class PointLight extends Light { @@ -85,9 +85,9 @@ public PointLight(Vector3f position, ColorRGBA color) { super(color); setPosition(position); } - + /** - * Creates a PointLight at the given position, with the given color and the + * Creates a PointLight at the given position, with the given color and the * given radius * @param position the position in world space * @param color the light color @@ -97,7 +97,7 @@ public PointLight(Vector3f position, ColorRGBA color, float radius) { this(position, color); setRadius(radius); } - + /** * Creates a PointLight at the given position, with the given radius * @param position the position in world space @@ -120,10 +120,10 @@ public void computeLastDistance(Spatial owner) { /** * Returns the world space position of the light. - * + * * @return the world space position of the light. - * - * @see PointLight#setPosition(com.jme3.math.Vector3f) + * + * @see PointLight#setPosition(com.jme3.math.Vector3f) */ public Vector3f getPosition() { return position; @@ -131,7 +131,7 @@ public Vector3f getPosition() { /** * Set the world space position of the light. - * + * * @param position the world space position of the light. */ public final void setPosition(Vector3f position) { @@ -141,7 +141,7 @@ public final void setPosition(Vector3f position) { /** * Returns the radius of the light influence. A radius of 0 means * the light has no attenuation. - * + * * @return the radius of the light */ public float getRadius() { @@ -156,9 +156,9 @@ public float getRadius() { * is greater than the light's radius, then the pixel will not be * affected by this light, if the distance is less than the radius, then * the magnitude of the influence is equal to distance / radius. - * + * * @param radius the radius of the light influence. - * + * * @throws IllegalArgumentException If radius is negative */ public final void setRadius(float radius) { @@ -195,7 +195,7 @@ public boolean intersectsBox(BoundingBox box, TempVars vars) { return Intersection.intersect(box, position, radius); } } - + @Override public boolean intersectsSphere(BoundingSphere sphere, TempVars vars) { if (this.radius == 0) { @@ -205,7 +205,7 @@ public boolean intersectsSphere(BoundingSphere sphere, TempVars vars) { return Intersection.intersect(sphere, position, radius); } } - + @Override public boolean intersectsFrustum(Camera camera, TempVars vars) { if (this.radius == 0) { @@ -214,7 +214,7 @@ public boolean intersectsFrustum(Camera camera, TempVars vars) { return Intersection.intersect(camera, position, radius); } } - + @Override public void write(JmeExporter ex) throws IOException { super.write(ex); @@ -229,9 +229,9 @@ public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); position = (Vector3f) ic.readSavable("position", null); radius = ic.readFloat("radius", 0f); - if(radius!=0){ + if (radius!=0) { this.invRadius = 1 / radius; - }else{ + } else { this.invRadius = 0; } } diff --git a/jme3-core/src/main/java/com/jme3/material/MatParam.java b/jme3-core/src/main/java/com/jme3/material/MatParam.java index e0cb8683fb..3bd50332fc 100644 --- a/jme3-core/src/main/java/com/jme3/material/MatParam.java +++ b/jme3-core/src/main/java/com/jme3/material/MatParam.java @@ -156,7 +156,7 @@ public String getValueAsString() { case Vector2: Vector2f v2 = (Vector2f) value; return v2.getX() + " " + v2.getY(); -/* +/* This may get used at a later point of time When arrays can be inserted in J3M files @@ -243,9 +243,9 @@ public String getValueAsString() { TextureKey texKey = (TextureKey) texVal.getKey(); if (texKey == null){ //throw new UnsupportedOperationException("The specified MatParam cannot be represented in J3M"); - // this is used in toString and the above line causes blender materials to throw this exception. + // this is used in toString and the above line causes blender materials to throw this exception. // toStrings should be very robust IMO as even debuggers often invoke toString and logging code - // often does as well, even implicitly. + // often does as well, even implicitly. return texVal+":returned null key"; } @@ -280,13 +280,13 @@ public String getValueAsString() { private String getWrapMode(Texture texVal, Texture.WrapAxis axis) { WrapMode mode = WrapMode.EdgeClamp; - try{ + try { mode = texVal.getWrap(axis); - }catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { //this axis doesn't exist on the texture return ""; } - if(mode != WrapMode.EdgeClamp){ + if (mode != WrapMode.EdgeClamp) { return"Wrap"+ mode.name() + "_" + axis.name() + " "; } return ""; diff --git a/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java b/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java index 1796cf477d..daa08d3266 100644 --- a/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java +++ b/jme3-core/src/main/java/com/jme3/material/TechniqueDef.java @@ -123,7 +123,7 @@ public enum ShadowMode { InPass, PostPass, } - + /** * Define in what space the light data should be sent to the shader. */ @@ -136,7 +136,7 @@ public enum LightSpace { private final EnumSet requiredCaps = EnumSet.noneOf(Caps.class); private String name; private int sortId; - + private EnumMap shaderLanguages; private EnumMap shaderNames; @@ -145,7 +145,7 @@ public enum LightSpace { private ArrayList defineTypes; private HashMap paramToDefineId; private final HashMap definesToShaderMap; - + private boolean usesNodes = false; private List shaderNodes; private ShaderGenerationInfo shaderGenerationInfo; @@ -173,7 +173,7 @@ public enum LightSpace { * @param name The name of the technique * @param sortId a unique ID for sorting */ - public TechniqueDef(String name, int sortId){ + public TechniqueDef(String name, int sortId) { this(); this.sortId = sortId; this.name = name; @@ -191,9 +191,9 @@ protected TechniqueDef() { definesToShaderMap = new HashMap(); worldBinds = new ArrayList<>(); } - + /** - * @return A unique sort ID. + * @return A unique sort ID. * No other technique definition can have the same ID. */ public int getSortId() { @@ -207,7 +207,7 @@ public int getSortId() { * * @return the name of this technique */ - public String getName(){ + public String getName() { return name; } @@ -230,15 +230,15 @@ public LightMode getLightMode() { public void setLightMode(LightMode lightMode) { this.lightMode = lightMode; //if light space is not specified we set it to Legacy - if(lightSpace == null){ - if(lightMode== LightMode.MultiPass){ + if (lightSpace == null) { + if (lightMode== LightMode.MultiPass) { lightSpace = LightSpace.Legacy; - }else{ + } else { lightSpace = LightSpace.World; } } } - + public void setLogic(TechniqueDefLogic logic) { this.logic = logic; } @@ -246,7 +246,7 @@ public void setLogic(TechniqueDefLogic logic) { public TechniqueDefLogic getLogic() { return logic; } - + /** * Returns the shadow mode. * @return the shadow mode. @@ -304,7 +304,7 @@ public void setNoRender(boolean noRender) { * @return true if this technique should not be rendered, false otherwise. * */ - public boolean isNoRender(){ + public boolean isNoRender() { return noRender; } @@ -314,7 +314,7 @@ public boolean isNoRender(){ * @return true if this technique uses Shader Nodes, false otherwise. * */ - public boolean isUsingShaderNodes(){ + public boolean isUsingShaderNodes() { return usesNodes; } @@ -353,22 +353,22 @@ public void setShaderFile(String vertexShader, String fragmentShader, String ver /** * Set a string which is prepended to every shader used by this technique. - * + * * Typically this is used for preset defines. - * + * * @param shaderPrologue The prologue to append before the technique's shaders. */ public void setShaderPrologue(String shaderPrologue) { this.shaderPrologue = shaderPrologue; } - + /** * @return the shader prologue which is prepended to every shader. */ public String getShaderPrologue() { return shaderPrologue; } - + /** * Returns the define name which the given material parameter influences. * @@ -377,7 +377,7 @@ public String getShaderPrologue() { * * @see #addShaderParamDefine(java.lang.String, com.jme3.shader.VarType, java.lang.String) */ - public String getShaderParamDefine(String paramName){ + public String getShaderParamDefine(String paramName) { Integer defineId = paramToDefineId.get(paramName); if (defineId != null) { return defineNames.get(defineId); @@ -385,7 +385,7 @@ public String getShaderParamDefine(String paramName){ return null; } } - + /** * Get the define ID for a given material parameter. * @@ -405,13 +405,13 @@ public Integer getShaderParamDefineId(String paramName) { public VarType getDefineIdType(int defineId) { return defineId < defineTypes.size() ? defineTypes.get(defineId) : null; } - + /** * Adds a define linked to a material parameter. *

    * Any time the material parameter on the parent material is altered, * the appropriate define on the technique will be modified as well. - * When set, the material parameter will be mapped to an integer define, + * When set, the material parameter will be mapped to an integer define, * typically 1 if it is set, unless it is an integer or a float, * in which case it will be converted into an integer. * @@ -419,14 +419,14 @@ public VarType getDefineIdType(int defineId) { * @param paramType The type of the material parameter to link to. * @param defineName The name of the define parameter, e.g. USE_LIGHTING */ - public void addShaderParamDefine(String paramName, VarType paramType, String defineName){ + public void addShaderParamDefine(String paramName, VarType paramType, String defineName) { int defineId = defineNames.size(); - + if (defineId >= DefineList.MAX_DEFINES) { - throw new IllegalStateException("Cannot have more than " + + throw new IllegalStateException("Cannot have more than " + DefineList.MAX_DEFINES + " defines on a technique."); } - + paramToDefineId.put(paramName, defineId); defineNames.add(defineName); defineTypes.add(paramType); @@ -434,22 +434,22 @@ public void addShaderParamDefine(String paramName, VarType paramType, String def /** * Add an unmapped define which can only be set by define ID. - * - * Unmapped defines are used by technique renderers to + * + * Unmapped defines are used by technique renderers to * configure the shader internally before rendering. - * + * * @param defineName The define name to create * @param defineType the type for the new define * @return The define ID of the created define */ public int addShaderUnmappedDefine(String defineName, VarType defineType) { int defineId = defineNames.size(); - + if (defineId >= DefineList.MAX_DEFINES) { - throw new IllegalStateException("Cannot have more than " + + throw new IllegalStateException("Cannot have more than " + DefineList.MAX_DEFINES + " defines on a technique."); } - + defineNames.add(defineName); defineTypes.add(defineType); return defineId; @@ -476,18 +476,18 @@ public String[] getDefineNames() { public VarType[] getDefineTypes() { return defineTypes.toArray(new VarType[0]); } - + /** * Create a define list with the size matching the number * of defines on this technique. - * + * * @return a define list with the size matching the number * of defines on this technique. */ public DefineList createDefineList() { return new DefineList(defineNames.size()); } - + private Shader loadShader(AssetManager assetManager, EnumSet rendererCaps, DefineList defines) { StringBuilder sb = new StringBuilder(); sb.append(shaderPrologue); @@ -519,10 +519,10 @@ private Shader loadShader(AssetManager assetManager, EnumSet rendererCaps, for (final UniformBinding binding : getWorldBindings()) { shader.addUniformBinding(binding); } - + return shader; } - + public Shader getShader(AssetManager assetManager, EnumSet rendererCaps, DefineList defines) { Shader shader = definesToShaderMap.get(defines); if (shader == null) { @@ -531,14 +531,15 @@ public Shader getShader(AssetManager assetManager, EnumSet rendererCaps, D } return shader; } - + /** * Sets the shaders that this technique definition will use. * * @param shaderNames EnumMap containing all shader names for this stage * @param shaderLanguages EnumMap containing all shader languages for this stage */ - public void setShaderFile(EnumMap shaderNames, EnumMap shaderLanguages) { + public void setShaderFile(EnumMap shaderNames, + EnumMap shaderLanguages) { requiredCaps.clear(); weight = 0; @@ -584,7 +585,7 @@ public String getVertexShaderName() { /** * Returns the language of the fragment shader used in this technique. - * + * * @return the name of the language (such as "GLSL100") */ public String getFragmentShaderLanguage() { @@ -593,7 +594,7 @@ public String getFragmentShaderLanguage() { /** * Returns the language of the vertex shader used in this technique. - * + * * @return the name of the language (such as "GLSL100") */ public String getVertexShaderLanguage() { @@ -604,14 +605,14 @@ public String getVertexShaderLanguage() { * @param shaderType Fragment/Vertex/etcetera * @return the name of the language */ - public String getShaderProgramLanguage(Shader.ShaderType shaderType){ + public String getShaderProgramLanguage(Shader.ShaderType shaderType) { return shaderLanguages.get(shaderType); } /**Returns the name for each shader program * @param shaderType Fragment/Vertex/etcetera * @return the name of the program */ - public String getShaderProgramName(Shader.ShaderType shaderType){ + public String getShaderProgramName(Shader.ShaderType shaderType) { return shaderNames.get(shaderType); } @@ -659,7 +660,7 @@ public List getWorldBindings() { } @Override - public void write(JmeExporter ex) throws IOException{ + public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(name, "name", null); @@ -691,7 +692,7 @@ public void write(JmeExporter ex) throws IOException{ @Override @SuppressWarnings("unchecked") - public void read(JmeImporter im) throws IOException{ + public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); name = ic.readString("name", null); shaderNames.put(Shader.ShaderType.Vertex,ic.readString("vertName", null)); @@ -823,7 +824,8 @@ public TechniqueDef clone() throws CloneNotSupportedException { try { clone.logic = logic.getClass().getConstructor(TechniqueDef.class).newInstance(clone); - } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + } catch (InstantiationException | IllegalAccessException + | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } diff --git a/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java b/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java index d04a532b9d..801d5b7837 100644 --- a/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java +++ b/jme3-core/src/main/java/com/jme3/material/logic/SinglePassAndImageBasedLightingLogic.java @@ -141,7 +141,7 @@ protected int updateLightListUniforms(Shader shader, Geometry g, LightList light // apply additive blending for 2nd and future passes rm.getRenderer().applyRenderState(ADDITIVE_LIGHT); ambientColor.setValue(VarType.Vector4, ColorRGBA.Black); - } else{ + } else { extractIndirectLights(lightList,true); ambientColor.setValue(VarType.Vector4, ambientLightColor); } @@ -169,8 +169,6 @@ protected int updateLightListUniforms(Shader shader, Geometry g, LightList light int curIndex; int endIndex = numLights + startIndex; for (curIndex = startIndex; curIndex < endIndex && curIndex < lightList.size(); curIndex++) { - - Light l = lightList.get(curIndex); if(l.getType() == Light.Type.Ambient){ endIndex++; @@ -234,17 +232,17 @@ protected int updateLightListUniforms(Shader shader, Geometry g, LightList light vars.release(); // pad unused buffer space - while(lightDataIndex < numLights * 3) { + while (lightDataIndex < numLights * 3) { lightData.setVector4InArray(0f, 0f, 0f, 0f, lightDataIndex); lightDataIndex++; } return curIndex; } - private int setProbeData(RenderManager rm, int lastTexUnit, Uniform lightProbeData, Uniform shCoeffs, Uniform lightProbePemMap, LightProbe lightProbe) { - + private int setProbeData(RenderManager rm, int lastTexUnit, Uniform lightProbeData, Uniform shCoeffs, + Uniform lightProbePemMap, LightProbe lightProbe) { lightProbeData.setValue(VarType.Matrix4, lightProbe.getUniformMatrix()); - //setVector4InArray(lightProbe.getPosition().x, lightProbe.getPosition().y, lightProbe.getPosition().z, 1f / area.getRadius() + lightProbe.getNbMipMaps(), 0); + //setVector4InArray(lightProbe.getPosition().x, lightProbe.getPosition().y, lightProbe.getPosition().z, 1f / area.getRadius() + lightProbe.getNbMipMaps(), 0); shCoeffs.setValue(VarType.Vector3Array, lightProbe.getShCoeffs()); /* * Assign the prefiltered env map to the next available texture unit. diff --git a/jme3-core/src/main/java/com/jme3/material/logic/SinglePassLightingLogic.java b/jme3-core/src/main/java/com/jme3/material/logic/SinglePassLightingLogic.java index 2414f69866..a9b51783c2 100644 --- a/jme3-core/src/main/java/com/jme3/material/logic/SinglePassLightingLogic.java +++ b/jme3-core/src/main/java/com/jme3/material/logic/SinglePassLightingLogic.java @@ -198,7 +198,7 @@ protected int updateLightListUniforms(Shader shader, Geometry g, LightList light } vars.release(); // pad unused buffer space - while(lightDataIndex < numLights * 3) { + while (lightDataIndex < numLights * 3) { lightData.setVector4InArray(0f, 0f, 0f, 0f, lightDataIndex); lightDataIndex++; } diff --git a/jme3-core/src/main/java/com/jme3/post/FilterPostProcessor.java b/jme3-core/src/main/java/com/jme3/post/FilterPostProcessor.java index 15892bfbeb..5f35e28ac7 100644 --- a/jme3-core/src/main/java/com/jme3/post/FilterPostProcessor.java +++ b/jme3-core/src/main/java/com/jme3/post/FilterPostProcessor.java @@ -68,7 +68,7 @@ public class FilterPostProcessor implements SceneProcessor, Savable { private Texture2D filterTexture; private Texture2D depthTexture; private SafeArrayList filters = new SafeArrayList<>(Filter.class); - private AssetManager assetManager; + private AssetManager assetManager; private Picture fsQuad; private boolean computeDepth = false; private FrameBuffer outputBuffer; @@ -87,9 +87,9 @@ public class FilterPostProcessor implements SceneProcessor, Savable { private Format fbFormat = Format.RGB111110F; final private Format depthFormat = Format.Depth; - + /** - * Create a FilterProcessor + * Create a FilterProcessor * @param assetManager the assetManager */ public FilterPostProcessor(AssetManager assetManager) { @@ -155,7 +155,7 @@ public void initialize(RenderManager rm, ViewPort vp) { fbFormat = Format.RGB16F; } } - + Camera cam = vp.getCamera(); //save view port dimensions @@ -172,11 +172,11 @@ public void initialize(RenderManager rm, ViewPort vp) { public Format getDefaultPassTextureFormat() { return fbFormat; } - + /** * init the given filter * @param filter - * @param vp + * @param vp */ private void initFilter(Filter filter, ViewPort vp) { filter.setProcessor(this); @@ -197,7 +197,7 @@ private void initFilter(Filter filter, ViewPort vp) { * renders a filter on a fullscreen quad * @param r * @param buff - * @param mat + * @param mat */ private void renderProcessing(Renderer r, FrameBuffer buff, Material mat) { if (buff == outputBuffer) { @@ -207,32 +207,32 @@ private void renderProcessing(Renderer r, FrameBuffer buff, Material mat) { // run the appropriate (and same) onXXXChange methods. // Also, update() updates some things that don't need to be updated. //viewPort.getCamera().update(); - renderManager.setCamera( viewPort.getCamera(), false); + renderManager.setCamera( viewPort.getCamera(), false); if (mat.getAdditionalRenderState().isDepthWrite()) { mat.getAdditionalRenderState().setDepthTest(false); mat.getAdditionalRenderState().setDepthWrite(false); } - }else{ + } else { viewPort.getCamera().resize(buff.getWidth(), buff.getHeight(), false); viewPort.getCamera().setViewPort(0, 1, 0, 1); // update is redundant because resize and setViewPort will both // run the appropriate (and same) onXXXChange methods. // Also, update() updates some things that don't need to be updated. //viewPort.getCamera().update(); - renderManager.setCamera( viewPort.getCamera(), false); + renderManager.setCamera( viewPort.getCamera(), false); mat.getAdditionalRenderState().setDepthTest(true); mat.getAdditionalRenderState().setDepthWrite(true); } - - + + fsQuad.setMaterial(mat); fsQuad.updateGeometricState(); - - r.setFrameBuffer(buff); + + r.setFrameBuffer(buff); r.clearBuffers(true, true, true); renderManager.renderGeometry(fsQuad); } - + @Override public boolean isInitialized() { return viewPort != null; @@ -246,12 +246,12 @@ public void postQueue(RenderQueue rq) { filter.postQueue(rq); } } - } + } /** * iterate through the filter list and renders filters * @param r - * @param sceneFb + * @param sceneFb */ private void renderFilterChain(Renderer r, FrameBuffer sceneFb) { Texture2D tex = filterTexture; @@ -302,7 +302,7 @@ private void renderFilterChain(Renderer r, FrameBuffer sceneFb) { mat.clearParam("NumSamples"); } } - + boolean wantsBilinear = filter.isRequiresBilinear(); if (wantsBilinear) { tex.setMagFilter(Texture.MagFilter.Bilinear); @@ -319,7 +319,7 @@ private void renderFilterChain(Renderer r, FrameBuffer sceneFb) { renderProcessing(r, buff, mat); if (prof != null) prof.spStep(SpStep.ProcPostFrame, FPP, filter.getName(), "postFilter"); filter.postFilter(r, buff); - + if (wantsBilinear) { tex.setMagFilter(Texture.MagFilter.Nearest); tex.setMinFilter(Texture.MinFilter.NearestNoMipMaps); @@ -339,7 +339,7 @@ public void postFrame(FrameBuffer out) { } renderFilterChain(renderer, sceneBuffer); renderer.setFrameBuffer(outputBuffer); - + //viewport can be null if no filters are enabled if (viewPort != null) { renderManager.setCamera(viewPort.getCamera(), false); @@ -359,7 +359,7 @@ public void preFrame(float tpf) { } else { setupViewPortFrameBuffer(); - //if we are in a multiview situation we need to resize the camera + //if we are in a multiview situation we need to resize the camera //to the viewport size so that the back buffer is rendered correctly if (multiView) { viewPort.getCamera().resize(width, height, false); @@ -410,7 +410,7 @@ private void updateLastFilterIndex() { } } if (isInitialized() && lastFilterIndex == -1) { - //There is no enabled filter, we restore the original framebuffer + //There is no enabled filter, we restore the original framebuffer //to the viewport to bypass the fpp. viewPort.setOutputFrameBuffer(outputBuffer); } @@ -461,14 +461,14 @@ public void reshape(ViewPort vp, int w, int h) { originalWidth = w; originalHeight = h; - //computing real dimension of the viewport and resizing the camera + //computing real dimension of the viewport and resizing the camera width = (int) (w * (Math.abs(right - left))); height = (int) (h * (Math.abs(bottom - top))); width = Math.max(1, width); height = Math.max(1, height); - + //Testing original versus actual viewport dimension. - //If they are different we are in a multiview situation and + //If they are different we are in a multiview situation and //camera must be handled differently if(originalWidth!=width || originalHeight!=height){ multiView = true; @@ -592,13 +592,13 @@ public Texture2D getDepthTexture() { public Texture2D getFilterTexture() { return filterTexture; } - + /** - * returns the first filter in the list assignable from the given type + * returns the first filter in the list assignable from the given type * * @param the filter type * @param filterType the filter type - * @return a filter assignable from the given type + * @return a filter assignable from the given type */ @SuppressWarnings("unchecked") public T getFilter(Class filterType) { @@ -609,7 +609,7 @@ public T getFilter(Class filterType) { } return null; } - + /** * returns an unmodifiable version of the filter list. * @return the filters list diff --git a/jme3-core/src/main/java/com/jme3/post/HDRRenderer.java b/jme3-core/src/main/java/com/jme3/post/HDRRenderer.java index 00afd7b0f5..241401ff15 100644 --- a/jme3-core/src/main/java/com/jme3/post/HDRRenderer.java +++ b/jme3-core/src/main/java/com/jme3/post/HDRRenderer.java @@ -99,16 +99,16 @@ public class HDRRenderer implements SceneProcessor { private boolean enabled = true; - public HDRRenderer(AssetManager manager, Renderer renderer){ + public HDRRenderer(AssetManager manager, Renderer renderer) { this.manager = manager; this.renderer = renderer; - + Collection caps = renderer.getCaps(); if (caps.contains(Caps.PackedFloatColorBuffer)) bufFormat = Format.RGB111110F; else if (caps.contains(Caps.FloatColorBuffer)) bufFormat = Format.RGB16F; - else{ + else { enabled = false; return; } @@ -118,19 +118,19 @@ public boolean isEnabled() { return enabled; } - public void setSamples(int samples){ + public void setSamples(int samples) { this.numSamples = samples; } - public void setExposure(float exp){ + public void setExposure(float exp) { this.exposure = exp; } - public void setWhiteLevel(float whiteLevel){ + public void setWhiteLevel(float whiteLevel) { this.whiteLevel = whiteLevel; } - public void setMaxIterations(int maxIterations){ + public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; // regenerate shaders if needed @@ -138,21 +138,21 @@ public void setMaxIterations(int maxIterations){ createLumShaders(); } - public void setThrottle(float throttle){ + public void setThrottle(float throttle) { this.throttle = throttle; } - public void setUseFastFilter(boolean fastFilter){ + public void setUseFastFilter(boolean fastFilter) { if (fastFilter){ fbMagFilter = MagFilter.Nearest; fbMinFilter = MinFilter.NearestNoMipMaps; - }else{ + } else { fbMagFilter = MagFilter.Bilinear; fbMinFilter = MinFilter.BilinearNoMipMaps; } } - public Picture createDisplayQuad(/*int mode, Texture tex*/){ + public Picture createDisplayQuad(/*int mode, Texture tex*/) { if (scene64 == null) return null; @@ -163,16 +163,16 @@ public Picture createDisplayQuad(/*int mode, Texture tex*/){ mat.setBoolean("DecodeLum", true); mat.setTexture("Texture", scene64); // mat.setTexture("Texture", tex); - + Picture dispQuad = new Picture("Luminance Display"); dispQuad.setMaterial(mat); return dispQuad; } private Material createLumShader(int srcW, int srcH, int bufW, int bufH, int mode, - int iters, Texture tex){ + int iters, Texture tex) { Material mat = new Material(manager, "Common/MatDefs/Hdr/LogLum.j3md"); - + Vector2f blockSize = new Vector2f(1f / bufW, 1f / bufH); Vector2f pixelSize = new Vector2f(1f / srcW, 1f / srcH); Vector2f blocks = new Vector2f(); @@ -184,7 +184,7 @@ private Material createLumShader(int srcW, int srcH, int bufW, int bufH, int mod blockSize.y / pixelSize.y); numPixels = blocks.x * blocks.y; } while (numPixels > iters); - }else{ + } else { blocks.set(blockSize.x / pixelSize.x, blockSize.y / pixelSize.y); numPixels = blocks.x * blocks.y; @@ -204,7 +204,7 @@ else if (mode == LUMMODE_DECODE_LUM) return mat; } - private void createLumShaders(){ + private void createLumShaders() { int w = mainSceneFB.getWidth(); int h = mainSceneFB.getHeight(); hdr64 = createLumShader(w, h, 64, 64, LUMMODE_ENCODE_LUM, maxIterations, mainScene); @@ -212,16 +212,16 @@ private void createLumShaders(){ hdr1 = createLumShader(8, 8, 1, 1, LUMMODE_NONE, maxIterations, scene8); } - private int opposite(int i){ + private int opposite(int i) { return i == 1 ? 0 : 1; } - private void renderProcessing(Renderer r, FrameBuffer dst, Material mat){ - if (dst == null){ + private void renderProcessing(Renderer r, FrameBuffer dst, Material mat) { + if (dst == null) { fsQuad.setWidth(mainSceneFB.getWidth()); fsQuad.setHeight(mainSceneFB.getHeight()); fbCam.resize(mainSceneFB.getWidth(), mainSceneFB.getHeight(), true); - }else{ + } else { fsQuad.setWidth(dst.getWidth()); fsQuad.setHeight(dst.getHeight()); fbCam.resize(dst.getWidth(), dst.getHeight(), true); @@ -235,7 +235,7 @@ private void renderProcessing(Renderer r, FrameBuffer dst, Material mat){ renderManager.renderGeometry(fsQuad); } - private void renderToneMap(Renderer r, FrameBuffer out){ + private void renderToneMap(Renderer r, FrameBuffer out) { tone.setFloat("A", exposure); tone.setFloat("White", whiteLevel); tone.setTexture("Lum", scene1[oppSrc]); @@ -244,19 +244,19 @@ private void renderToneMap(Renderer r, FrameBuffer out){ renderProcessing(r, out, tone); } - private void updateAverageLuminance(Renderer r){ + private void updateAverageLuminance(Renderer r) { renderProcessing(r, scene64FB, hdr64); renderProcessing(r, scene8FB, hdr8); renderProcessing(r, scene1FB[curSrc], hdr1); } @Override - public boolean isInitialized(){ + public boolean isInitialized() { return viewPort != null; } @Override - public void reshape(ViewPort vp, int w, int h){ + public void reshape(ViewPort vp, int w, int h) { if (mainSceneFB != null){ renderer.deleteFrameBuffer(mainSceneFB); } @@ -273,14 +273,14 @@ public void reshape(ViewPort vp, int w, int h){ } tone.setTexture("Texture", mainScene); - + Collection caps = renderer.getCaps(); if (numSamples > 1 && caps.contains(Caps.FrameBufferMultisample)){ msFB = new FrameBuffer(w, h, numSamples); msFB.setDepthBuffer(Format.Depth); msFB.setColorBuffer(bufFormat); vp.setOutputFrameBuffer(msFB); - }else{ + } else { if (numSamples > 1) logger.warning("FBO multisampling not supported on this GPU, request ignored."); @@ -291,7 +291,7 @@ public void reshape(ViewPort vp, int w, int h){ } @Override - public void initialize(RenderManager rm, ViewPort vp){ + public void initialize(RenderManager rm, ViewPort vp) { if (!enabled) return; @@ -332,8 +332,6 @@ public void initialize(RenderManager rm, ViewPort vp){ int w = vp.getCamera().getWidth(); int h = vp.getCamera().getHeight(); reshape(vp, w, h); - - } @Override @@ -354,7 +352,7 @@ public void postFrame(FrameBuffer out) { if (!enabled) return; - if (msFB != null){ + if (msFB != null) { // first render to multisampled FB // renderer.setFrameBuffer(msFB); // renderer.clearBuffers(true,true,true); @@ -363,7 +361,7 @@ public void postFrame(FrameBuffer out) { // render back to non-multisampled FB renderer.copyFrameBuffer(msFB, mainSceneFB, true, true); - }else{ + } else { // renderer.setFrameBuffer(mainSceneFB); // renderer.clearBuffers(true,true,false); // @@ -378,7 +376,7 @@ public void postFrame(FrameBuffer out) { blendFactor = 0; time = 0; updateAverageLuminance(renderer); - }else{ + } else { if (curSrc == -1){ curSrc = 0; oppSrc = 0; @@ -429,5 +427,4 @@ public void cleanup() { public void setProfiler(AppProfiler profiler) { // not implemented } - } diff --git a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java index 88f9a6c041..4332600c67 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java +++ b/jme3-core/src/main/java/com/jme3/renderer/opengl/GLRenderer.java @@ -158,7 +158,7 @@ public static int extractVersion(String version) { int major = Integer.parseInt(m.group(1)); int minor = Integer.parseInt(m.group(2)); if (minor >= 10 && minor % 10 == 0) { - // some versions can look like "1.30" instead of "1.3". + // some versions can look like "1.30" instead of "1.3". // make sure to correct for this minor /= 10; } @@ -350,7 +350,7 @@ private void loadCapabilitiesCommon() { if (hasFloatTexture) { caps.add(Caps.FloatTexture); } - + // integer texture format extensions if(hasExtension("GL_EXT_texture_integer") || caps.contains(Caps.OpenGL30)) caps.add(Caps.IntegerTexture); @@ -443,7 +443,7 @@ private void loadCapabilitiesCommon() { limits.put(Limits.TextureAnisotropy, getInteger(GLExt.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)); } - if (hasExtension("GL_EXT_framebuffer_object") + if (hasExtension("GL_EXT_framebuffer_object") || caps.contains(Caps.OpenGL30) || caps.contains(Caps.OpenGLES20)) { caps.add(Caps.FrameBuffer); @@ -469,7 +469,7 @@ private void loadCapabilitiesCommon() { limits.put(Limits.FrameBufferSamples, limits.get(Limits.ColorTextureSamples)); } } - + if (hasExtension("GL_ARB_draw_buffers") || caps.contains(Caps.OpenGL30) || caps.contains(Caps.OpenGLES30)) { limits.put(Limits.FrameBufferMrtAttachments, getInteger(GLExt.GL_MAX_DRAW_BUFFERS_ARB)); if (limits.get(Limits.FrameBufferMrtAttachments) > 1) { @@ -495,7 +495,7 @@ private void loadCapabilitiesCommon() { // Supports sRGB pipeline. if ( (hasExtension("GL_ARB_framebuffer_sRGB") && hasExtension("GL_EXT_texture_sRGB")) - || caps.contains(Caps.OpenGL30) ) { + || caps.contains(Caps.OpenGL30)) { caps.add(Caps.Srgb); } @@ -525,34 +525,43 @@ private void loadCapabilitiesCommon() { if (hasExtension("GL_ARB_shader_storage_buffer_object")) { caps.add(Caps.ShaderStorageBufferObject); - limits.put(Limits.ShaderStorageBufferObjectMaxBlockSize, getInteger(GL4.GL_MAX_SHADER_STORAGE_BLOCK_SIZE)); + limits.put(Limits.ShaderStorageBufferObjectMaxBlockSize, + getInteger(GL4.GL_MAX_SHADER_STORAGE_BLOCK_SIZE)); // Commented out until we support ComputeShaders and the ComputeShader Cap // limits.put(Limits.ShaderStorageBufferObjectMaxComputeBlocks, getInteger(GL4.GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS)); if (caps.contains(Caps.GeometryShader)) { - limits.put(Limits.ShaderStorageBufferObjectMaxGeometryBlocks, getInteger(GL4.GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS)); + limits.put(Limits.ShaderStorageBufferObjectMaxGeometryBlocks, + getInteger(GL4.GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS)); } - limits.put(Limits.ShaderStorageBufferObjectMaxFragmentBlocks, getInteger(GL4.GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS)); - limits.put(Limits.ShaderStorageBufferObjectMaxVertexBlocks, getInteger(GL4.GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS)); + limits.put(Limits.ShaderStorageBufferObjectMaxFragmentBlocks, + getInteger(GL4.GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS)); + limits.put(Limits.ShaderStorageBufferObjectMaxVertexBlocks, + getInteger(GL4.GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS)); if (caps.contains(Caps.TesselationShader)) { - limits.put(Limits.ShaderStorageBufferObjectMaxTessControlBlocks, getInteger(GL4.GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS)); - limits.put(Limits.ShaderStorageBufferObjectMaxTessEvaluationBlocks, getInteger(GL4.GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS)); + limits.put(Limits.ShaderStorageBufferObjectMaxTessControlBlocks, + getInteger(GL4.GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS)); + limits.put(Limits.ShaderStorageBufferObjectMaxTessEvaluationBlocks, + getInteger(GL4.GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS)); } - limits.put(Limits.ShaderStorageBufferObjectMaxCombineBlocks, getInteger(GL4.GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS)); + limits.put(Limits.ShaderStorageBufferObjectMaxCombineBlocks, + getInteger(GL4.GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS)); } if (hasExtension("GL_ARB_uniform_buffer_object")) { caps.add(Caps.UniformBufferObject); - limits.put(Limits.UniformBufferObjectMaxBlockSize, getInteger(GL3.GL_MAX_UNIFORM_BLOCK_SIZE)); + limits.put(Limits.UniformBufferObjectMaxBlockSize, + getInteger(GL3.GL_MAX_UNIFORM_BLOCK_SIZE)); if (caps.contains(Caps.GeometryShader)) { - limits.put(Limits.UniformBufferObjectMaxGeometryBlocks, getInteger(GL3.GL_MAX_GEOMETRY_UNIFORM_BLOCKS)); + limits.put(Limits.UniformBufferObjectMaxGeometryBlocks, + getInteger(GL3.GL_MAX_GEOMETRY_UNIFORM_BLOCKS)); } - limits.put(Limits.UniformBufferObjectMaxFragmentBlocks, getInteger(GL3.GL_MAX_FRAGMENT_UNIFORM_BLOCKS)); - limits.put(Limits.UniformBufferObjectMaxVertexBlocks, getInteger(GL3.GL_MAX_VERTEX_UNIFORM_BLOCKS)); + limits.put(Limits.UniformBufferObjectMaxFragmentBlocks, + getInteger(GL3.GL_MAX_FRAGMENT_UNIFORM_BLOCKS)); + limits.put(Limits.UniformBufferObjectMaxVertexBlocks, + getInteger(GL3.GL_MAX_VERTEX_UNIFORM_BLOCKS)); } - - - if(caps.contains(Caps.OpenGL20)){ + if (caps.contains(Caps.OpenGL20)) { caps.add(Caps.UnpackRowLength); } @@ -579,7 +588,7 @@ private void loadCapabilitiesCommon() { { sb.append("\t").append(cap.toString()).append("\n"); } - + sb.append("\nHardware limits: \n"); for (Limits limit : Limits.values()) { Integer value = limits.get(limit); @@ -589,7 +598,7 @@ private void loadCapabilitiesCommon() { sb.append("\t").append(limit.name()).append(" = ") .append(value).append("\n"); } - + logger.log(Level.FINE, sb.toString()); } @@ -623,7 +632,7 @@ public void initialize() { // Initialize default state.. gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1); - + if (caps.contains(Caps.SeamlessCubemap)) { // Enable this globally. Should be OK. gl.glEnable(GLExt.GL_TEXTURE_CUBE_MAP_SEAMLESS); @@ -769,7 +778,7 @@ public void applyRenderState(RenderState state) { gl.glDepthFunc(convertTestFunction(state.getDepthFunc())); context.depthFunc = state.getDepthFunc(); } - + if (state.isDepthWrite() && !context.depthWriteEnabled) { gl.glDepthMask(true); context.depthWriteEnabled = true; @@ -868,10 +877,10 @@ public void applyRenderState(RenderState state) { break; case AlphaSumA: blendFuncSeparate( - RenderState.BlendFunc.Src_Alpha, + RenderState.BlendFunc.Src_Alpha, RenderState.BlendFunc.One_Minus_Src_Alpha, RenderState.BlendFunc.One, - RenderState.BlendFunc.One + RenderState.BlendFunc.One ); break; case PremultAlpha: @@ -1020,7 +1029,7 @@ private int convertBlendEquation(RenderState.BlendEquation blendEquation) { throw new UnsupportedOperationException("Unrecognized blend operation: " + blendEquation); } } - + private int convertBlendEquationAlpha(RenderState.BlendEquationAlpha blendEquationAlpha) { //Note: InheritColor mode should already be handled, that is why it does not belong the switch case. switch (blendEquationAlpha) { @@ -1038,7 +1047,7 @@ private int convertBlendEquationAlpha(RenderState.BlendEquationAlpha blendEquati throw new UnsupportedOperationException("Unrecognized alpha blend operation: " + blendEquationAlpha); } } - + private int convertBlendFunc(BlendFunc blendFunc) { switch (blendFunc) { case Zero: @@ -1061,7 +1070,7 @@ private int convertBlendFunc(BlendFunc blendFunc) { return GL.GL_DST_ALPHA; case One_Minus_Dst_Alpha: return GL.GL_ONE_MINUS_DST_ALPHA; - case Src_Alpha_Saturate: + case Src_Alpha_Saturate: return GL.GL_SRC_ALPHA_SATURATE; default: throw new UnsupportedOperationException("Unrecognized blend function operation: " + blendFunc); @@ -1178,7 +1187,7 @@ protected void bindProgram(Shader shader) { /*=========*\ |* Shaders *| \*=========*/ - + /** * Update the location of the specified Uniform in the specified Shader. * @@ -1448,7 +1457,7 @@ public void updateShaderSourceData(ShaderSource source) { if (gles2 || gles3) { // request GLSL ES (1.00) when compiling under GLES2. stringBuf.append("#version 100\n"); - + } else { // version 100 does not exist in desktop GLSL. // put version 110 in that case to enable strict checking @@ -1737,9 +1746,9 @@ public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyColor, dstX1 = dst.getWidth(); dstY1 = dst.getHeight(); } - + int mask = 0; - + if(copyColor){ mask|=GL.GL_COLOR_BUFFER_BIT; } @@ -1867,9 +1876,9 @@ public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) { image.getId(), rb.getLevel()); } else { - glfbo.glFramebufferTextureLayerEXT(GLFbo.GL_FRAMEBUFFER_EXT, - convertAttachmentSlot(rb.getSlot()), - image.getId(), + glfbo.glFramebufferTextureLayerEXT(GLFbo.GL_FRAMEBUFFER_EXT, + convertAttachmentSlot(rb.getSlot()), + image.getId(), rb.getLevel(), rb.getLayer()); } @@ -1892,7 +1901,7 @@ public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) { rb.getId()); } } - + private void bindFrameBuffer(FrameBuffer fb) { if (fb == null) { if (context.boundFBO != defaultFBO) { @@ -1940,7 +1949,7 @@ public void updateFrameBuffer(FrameBuffer fb) { FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i); updateFrameBufferAttachment(fb, colorBuf); } - + setReadDrawBuffers(fb); checkFrameBufferError(); @@ -1982,11 +1991,11 @@ public void setReadDrawBuffers(FrameBuffer fb) { if (gl2 == null || gl instanceof GLES_30) { return; } - + final int NONE = -2; final int INITIAL = -1; final int MRT_OFF = 100; - + if (fb == null) { // Set Read/Draw buffers to initial value. if (context.boundDrawBuf != INITIAL) { @@ -2034,7 +2043,7 @@ public void setReadDrawBuffers(FrameBuffer fb) { intBuf16.flip(); glext.glDrawBuffers(intBuf16); context.boundDrawBuf = MRT_OFF + fb.getNumColorBuffers(); - + } else { RenderBuffer rb = fb.getColorBuffer(fb.getTargetIndex()); // select this draw buffer @@ -2045,9 +2054,9 @@ public void setReadDrawBuffers(FrameBuffer fb) { } } } - + } - + @Override public void setFrameBuffer(FrameBuffer fb) { if (fb == null && mainFbOverride != null) { @@ -2128,7 +2137,7 @@ private void readFrameBufferWithGLFormat(FrameBuffer fb, ByteBuffer byteBuf, int context.boundReadBuf = rb.getSlot(); } } - + } else { setFrameBuffer(null); } @@ -2291,7 +2300,7 @@ private void setupTextureParams(int unit, Texture tex) { if (image != null) { haveMips = image.isGeneratedMipmapsRequired() || image.hasMipmaps(); } - + LastTextureState curState = image.getLastTextureState(); if (curState.magFilter != tex.getMagFilter()) { @@ -2359,7 +2368,7 @@ private void setupTextureParams(int unit, Texture tex) { } curState.shadowCompareMode = texCompareMode; } - + // If at this point we didn't bind the texture, bind it now bindTextureOnly(target, image, unit); } @@ -2367,7 +2376,7 @@ private void setupTextureParams(int unit, Texture tex) { /** * Validates if a potentially NPOT texture is supported by the hardware. *

    - * Textures with power-of-2 dimensions are supported on all hardware, however + * Textures with power-of-2 dimensions are supported on all hardware, however * non-power-of-2 textures may or may not be supported depending on which * texturing features are used. * @@ -2422,7 +2431,7 @@ private void checkNonPowerOfTwo(Texture tex) { /** * Ensures that the texture is bound to the given unit * and that the unit is currently active (for modification). - * + * * @param target The texture target, one of GL_TEXTURE_*** * @param img The image texture to bind * @param unit At what unit to bind the texture. @@ -2440,11 +2449,11 @@ private void bindTextureAndUnit(int target, Image img, int unit) { statistics.onTextureUse(img, false); } } - + /** * Ensures that the texture is bound to the given unit, * but does not care if the unit is active (for rendering). - * + * * @param target The texture target, one of GL_TEXTURE_*** * @param img The image texture to bind * @param unit At what unit to bind the texture. @@ -2462,7 +2471,7 @@ private void bindTextureOnly(int target, Image img, int unit) { statistics.onTextureUse(img, false); } } - + /** * Uploads the given image to the GL driver. * @@ -2503,7 +2512,7 @@ public void updateTexImageData(Image img, Texture.Type type, int unit, boolean s } } else if (caps.contains(Caps.OpenGL20) || caps.contains(Caps.OpenGLES30)) { if (img.hasMipmaps()) { - // Image already has mipmaps, set the max level based on the + // Image already has mipmaps, set the max level based on the // number of mipmaps we have. gl.glTexParameteri(target, GL2.GL_TEXTURE_MAX_LEVEL, img.getMipMapSizes().length - 1); } else { @@ -2649,11 +2658,12 @@ public void modifyTexture(Texture tex, Image pixels, int x, int y) { throw new RuntimeException("Renderer lacks texture units?"); } - if(caps.contains(Caps.OpenGLES20) && pixels.getFormat()!=tex.getImage().getFormat() ) { + if(caps.contains(Caps.OpenGLES20) && pixels.getFormat()!=tex.getImage().getFormat()) { logger.log(Level.WARNING, "Incompatible texture subimage"); } int target = convertTextureType(tex.getType(), pixels.getMultiSamples(), -1); - texUtil.uploadSubTexture(target,pixels, 0, x, y,0,0,pixels.getWidth(),pixels.getHeight(), linearizeSrgbImages); + texUtil.uploadSubTexture(target, pixels, 0, x, y, + 0, 0, pixels.getWidth(), pixels.getHeight(), linearizeSrgbImages); } /** @@ -2667,7 +2677,8 @@ public void modifyTexture(Texture tex, Image pixels, int x, int y) { * @param areaW Width of the area to copy * @param areaH Height of the area to copy */ - public void modifyTexture(Texture2D dest, Image src, int destX, int destY, int srcX, int srcY, int areaW, int areaH) { + public void modifyTexture(Texture2D dest, Image src, int destX, int destY, + int srcX, int srcY, int areaW, int areaH) { final int textureUnitIndex = 0; try { setTexture(textureUnitIndex, dest); @@ -2675,13 +2686,14 @@ public void modifyTexture(Texture2D dest, Image src, int destX, int destY, int s throw new RuntimeException("Renderer lacks texture units?"); } - if(caps.contains(Caps.OpenGLES20) && src.getFormat()!=dest.getImage().getFormat() ) { + if(caps.contains(Caps.OpenGLES20) && src.getFormat()!=dest.getImage().getFormat()) { logger.log(Level.WARNING, "Incompatible texture subimage"); } int target = convertTextureType(dest.getType(), src.getMultiSamples(), -1); - texUtil.uploadSubTexture(target, src, 0, destX, destY, srcX, srcY, areaW, areaH, linearizeSrgbImages); + texUtil.uploadSubTexture(target, src, 0, destX, destY, + srcX, srcY, areaW, areaH, linearizeSrgbImages); } - + @Override public void deleteImage(Image image) { int texId = image.getId(); @@ -3111,7 +3123,7 @@ public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) { /*==============*\ |* Render Calls *| \*==============*/ - + /** * Convert a mesh mode to the corresponding GL value. * @@ -3184,7 +3196,7 @@ public void updateVertexArray(Mesh mesh, VertexBuffer instanceData) { private void renderMeshDefault(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { // Here while count is still passed in. Can be removed when/if - // the method is collapsed again. -pspeed + // the method is collapsed again. -pspeed count = Math.max(mesh.getInstanceCount(), count); VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); @@ -3222,7 +3234,7 @@ private void renderMeshDefault(Mesh mesh, int lod, int count, VertexBuffer[] ins } clearVertexAttribs(); - + if (indices != null) { drawTriangleList(indices, mesh, count); } else { diff --git a/jme3-core/src/main/java/com/jme3/renderer/queue/GeometryList.java b/jme3-core/src/main/java/com/jme3/renderer/queue/GeometryList.java index b26840f9c8..5836c87614 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/queue/GeometryList.java +++ b/jme3-core/src/main/java/com/jme3/renderer/queue/GeometryList.java @@ -50,7 +50,7 @@ public class GeometryList implements Iterable{ private static final int DEFAULT_SIZE = 32; - private Geometry[] geometries; + private Geometry[] geometries; final private ListSort listSort; private int size; private GeometryComparator comparator; @@ -63,7 +63,7 @@ public class GeometryList implements Iterable{ */ public GeometryList(GeometryComparator comparator) { size = 0; - geometries = new Geometry[DEFAULT_SIZE]; + geometries = new Geometry[DEFAULT_SIZE]; this.comparator = comparator; listSort = new ListSort(); } @@ -88,7 +88,7 @@ public GeometryComparator getComparator() { * * @param cam Camera to use for sorting. */ - public void setCamera(Camera cam){ + public void setCamera(Camera cam) { this.comparator.setCamera(cam); } @@ -103,21 +103,21 @@ public int size(){ /** * Sets the element at the given index. - * + * * @param index The index to set * @param value The value */ public void set(int index, Geometry value) { geometries[index] = value; } - + /** * Returns the element at the given index. * * @param index The index to lookup * @return Geometry at the index */ - public Geometry get(int index){ + public Geometry get(int index) { return geometries[index]; } @@ -141,7 +141,7 @@ public void add(Geometry g) { * Resets list size to 0. */ public void clear() { - for (int i = 0; i < size; i++){ + for (int i = 0; i < size; i++) { geometries[i] = null; } @@ -155,9 +155,9 @@ public void clear() { public void sort() { if (size > 1) { // sort the spatial list using the comparator - if(listSort.getLength() != size){ + if (listSort.getLength() != size) { listSort.allocateStack(size); - } + } listSort.sort(geometries,comparator); } } @@ -165,28 +165,26 @@ public void sort() { @Override public Iterator iterator() { return new Iterator() { - int index = 0; - + @Override public boolean hasNext() { return index < size(); } - + @Override public Geometry next() { - if ( index >= size() ) { + if (index >= size()) { throw new NoSuchElementException("Geometry list has only " + size() + " elements"); } return get(index++); } - + @Override public void remove() { throw new UnsupportedOperationException("Geometry list doesn't support iterator removal"); } - }; } } \ No newline at end of file diff --git a/jme3-core/src/main/java/com/jme3/renderer/queue/OpaqueComparator.java b/jme3-core/src/main/java/com/jme3/renderer/queue/OpaqueComparator.java index 8eab520e77..1896ae9ace 100644 --- a/jme3-core/src/main/java/com/jme3/renderer/queue/OpaqueComparator.java +++ b/jme3-core/src/main/java/com/jme3/renderer/queue/OpaqueComparator.java @@ -43,30 +43,30 @@ public class OpaqueComparator implements GeometryComparator { private final Vector3f tempVec2 = new Vector3f(); @Override - public void setCamera(Camera cam){ + public void setCamera(Camera cam) { this.cam = cam; } - public float distanceToCam(Geometry spat){ + public float distanceToCam(Geometry spat) { if (spat == null) return Float.NEGATIVE_INFINITY; - + if (spat.queueDistance != Float.NEGATIVE_INFINITY) return spat.queueDistance; - + Vector3f camPosition = cam.getLocation(); Vector3f viewVector = cam.getDirection(tempVec2); Vector3f spatPosition = null; - + if (spat.getWorldBound() != null){ spatPosition = spat.getWorldBound().getCenter(); - }else{ + } else { spatPosition = spat.getWorldTranslation(); } - + spatPosition.subtract(camPosition, tempVec); spat.queueDistance = tempVec.dot(viewVector); - + return spat.queueDistance; } @@ -74,7 +74,7 @@ public float distanceToCam(Geometry spat){ public int compare(Geometry o1, Geometry o2) { Material m1 = o1.getMaterial(); Material m2 = o2.getMaterial(); - + int compareResult = Integer.compare(m1.getSortId(), m2.getSortId()); if (compareResult == 0){ // use the same shader. @@ -88,9 +88,8 @@ else if (d1 < d2) return -1; else return 1; - }else{ + } else { return compareResult; } } - } diff --git a/jme3-core/src/main/java/com/jme3/scene/AssetLinkNode.java b/jme3-core/src/main/java/com/jme3/scene/AssetLinkNode.java index 2e0fd2b45d..1a94fde246 100644 --- a/jme3-core/src/main/java/com/jme3/scene/AssetLinkNode.java +++ b/jme3-core/src/main/java/com/jme3/scene/AssetLinkNode.java @@ -74,7 +74,7 @@ public AssetLinkNode(String name, ModelKey key) { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); // This is a change in behavior because the old version did not clone diff --git a/jme3-core/src/main/java/com/jme3/scene/CameraNode.java b/jme3-core/src/main/java/com/jme3/scene/CameraNode.java index ab8a16e544..0f42325b8f 100644 --- a/jme3-core/src/main/java/com/jme3/scene/CameraNode.java +++ b/jme3-core/src/main/java/com/jme3/scene/CameraNode.java @@ -100,7 +100,7 @@ public Camera getCamera() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); // A change in behavior... I think previously CameraNode was probably diff --git a/jme3-core/src/main/java/com/jme3/scene/LightNode.java b/jme3-core/src/main/java/com/jme3/scene/LightNode.java index 88e8c45408..00cc652868 100644 --- a/jme3-core/src/main/java/com/jme3/scene/LightNode.java +++ b/jme3-core/src/main/java/com/jme3/scene/LightNode.java @@ -101,7 +101,7 @@ public Light getLight() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); // A change in behavior... I think previously LightNode was probably diff --git a/jme3-core/src/main/java/com/jme3/scene/control/AbstractControl.java b/jme3-core/src/main/java/com/jme3/scene/control/AbstractControl.java index c46be62f32..cc92767c35 100644 --- a/jme3-core/src/main/java/com/jme3/scene/control/AbstractControl.java +++ b/jme3-core/src/main/java/com/jme3/scene/control/AbstractControl.java @@ -59,10 +59,10 @@ public AbstractControl(){ public void setSpatial(Spatial spatial) { if (this.spatial != null && spatial != null && spatial != this.spatial) { throw new IllegalStateException("This control has already been added to a Spatial"); - } + } this.spatial = spatial; } - + public Spatial getSpatial(){ return spatial; } @@ -100,16 +100,16 @@ public Control cloneForSpatial(Spatial spatial) { public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { - throw new RuntimeException( "Can't clone control for spatial", e ); + } catch (CloneNotSupportedException e) { + throw new RuntimeException("Can't clone control for spatial", e); } - } + } @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.spatial = cloner.clone(spatial); } - + @Override public void update(float tpf) { if (!enabled) @@ -139,5 +139,4 @@ public void read(JmeImporter im) throws IOException { enabled = ic.readBoolean("enabled", true); spatial = (Spatial) ic.readSavable("spatial", null); } - } diff --git a/jme3-core/src/main/java/com/jme3/scene/control/BillboardControl.java b/jme3-core/src/main/java/com/jme3/scene/control/BillboardControl.java index 573c570bb2..f51e7460b4 100644 --- a/jme3-core/src/main/java/com/jme3/scene/control/BillboardControl.java +++ b/jme3-core/src/main/java/com/jme3/scene/control/BillboardControl.java @@ -103,17 +103,17 @@ protected void controlRender(RenderManager rm, ViewPort vp) { Camera cam = vp.getCamera(); rotateBillboard(cam); } - + private void fixRefreshFlags(){ // force transforms to update below this node spatial.updateGeometricState(); - + // force world bound to update Spatial rootNode = spatial; while (rootNode.getParent() != null){ rootNode = rootNode.getParent(); } - rootNode.getWorldBound(); + rootNode.getWorldBound(); } /** @@ -193,8 +193,8 @@ private void rotateScreenAligned(Camera camera) { left.set(camera.getLeft()).negateLocal(); orient.fromAxes(left, camera.getUp(), look); Node parent = spatial.getParent(); - Quaternion rot=new Quaternion().fromRotationMatrix(orient); - if ( parent != null ) { + Quaternion rot = new Quaternion().fromRotationMatrix(orient); + if (parent != null) { rot = parent.getWorldRotation().inverse().multLocal(rot); rot.normalizeLocal(); } @@ -213,7 +213,7 @@ private void rotateAxial(Camera camera, Vector3f axis) { // the camera. To do this, the camera must be inverse-transformed into // the model space of the billboard. look.set(camera.getLocation()).subtractLocal( - spatial.getWorldTranslation()); + spatial.getWorldTranslation()); spatial.getParent().getWorldRotation().mult(look, left); // co-opt left for our own purposes. left.x *= 1.0f / spatial.getWorldScale().x; left.y *= 1.0f / spatial.getWorldScale().y; @@ -279,7 +279,7 @@ public Alignment getAlignment() { * Sets the type of rotation this Billboard will have. The alignment can * be Camera, Screen, AxialY, or AxialZ. Invalid alignments will * assume no billboard rotation. - * + * * @param alignment the desired alignment (Camera/Screen/AxialY/AxialZ) */ public void setAlignment(Alignment alignment) { diff --git a/jme3-core/src/main/java/com/jme3/scene/debug/Grid.java b/jme3-core/src/main/java/com/jme3/scene/debug/Grid.java index 5ad8197a80..d2947e52a9 100644 --- a/jme3-core/src/main/java/com/jme3/scene/debug/Grid.java +++ b/jme3-core/src/main/java/com/jme3/scene/debug/Grid.java @@ -40,7 +40,7 @@ /** * Simple grid shape. - * + * * @author Kirill Vainer */ public class Grid extends Mesh { @@ -76,12 +76,12 @@ public Grid(int xLines, int yLines, float lineDist){ fpb.put(xLineLen).put(0).put(y); // indices - sib.put( (short) (curIndex++) ); - sib.put( (short) (curIndex++) ); + sib.put((short) (curIndex++)); + sib.put((short) (curIndex++)); } // add lines along Y - for (int i = 0; i < yLines + 2; i++){ + for (int i = 0; i < yLines + 2; i++) { float x = (i) * lineDist; // positions @@ -89,8 +89,8 @@ public Grid(int xLines, int yLines, float lineDist){ fpb.put(x).put(0).put(yLineLen); // indices - sib.put( (short) (curIndex++) ); - sib.put( (short) (curIndex++) ); + sib.put((short) (curIndex++)); + sib.put((short) (curIndex++)); } fpb.flip(); @@ -98,12 +98,11 @@ public Grid(int xLines, int yLines, float lineDist){ setBuffer(Type.Position, 3, fpb); setBuffer(Type.Index, 2, sib); - + setMode(Mode.Lines); updateBound(); updateCounts(); setStatic(); } - } diff --git a/jme3-core/src/main/java/com/jme3/scene/debug/WireBox.java b/jme3-core/src/main/java/com/jme3/scene/debug/WireBox.java index d4e4e1d585..38593898c1 100644 --- a/jme3-core/src/main/java/com/jme3/scene/debug/WireBox.java +++ b/jme3-core/src/main/java/com/jme3/scene/debug/WireBox.java @@ -44,11 +44,11 @@ public class WireBox extends Mesh { - public WireBox(){ + public WireBox() { this(1,1,1); } - - public WireBox(float xExt, float yExt, float zExt){ + + public WireBox(float xExt, float yExt, float zExt) { updatePositions(xExt,yExt,zExt); setBuffer(Type.Index, 2, new short[]{ @@ -73,15 +73,15 @@ public WireBox(float xExt, float yExt, float zExt){ updateCounts(); } - public void updatePositions(float xExt, float yExt, float zExt){ + public void updatePositions(float xExt, float yExt, float zExt) { VertexBuffer pvb = getBuffer(Type.Position); FloatBuffer pb; - if (pvb == null){ + if (pvb == null) { pvb = new VertexBuffer(Type.Position); pb = BufferUtils.createVector3Buffer(8); pvb.setupData(Usage.Dynamic, 3, Format.Float, pb); setBuffer(pvb); - }else{ + } else { pb = (FloatBuffer) pvb.getData(); pvb.updateData(pb); } @@ -101,7 +101,7 @@ public void updatePositions(float xExt, float yExt, float zExt){ ); updateBound(); } - + /** * Create a geometry suitable for visualizing the specified bounding box. * diff --git a/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedGeometry.java b/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedGeometry.java index 150d1f8203..99e68baff1 100644 --- a/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedGeometry.java +++ b/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedGeometry.java @@ -408,7 +408,7 @@ public int collideWith(Collidable other, CollisionResults results) { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); this.globalInstanceData = cloner.clone(globalInstanceData); diff --git a/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java b/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java index 383c117a16..ea5b576ed3 100644 --- a/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java +++ b/jme3-core/src/main/java/com/jme3/scene/instancing/InstancedNode.java @@ -108,13 +108,13 @@ public InstanceTypeKey clone() { public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new AssertionError(); } } @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.mesh = cloner.clone(mesh); this.material = cloner.clone(material); } @@ -141,18 +141,18 @@ public Control cloneForSpatial(Spatial spatial) { public Object jmeClone() { try { return super.clone(); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning control", e); } } @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields (Cloner cloner, Object original) { this.node = cloner.clone(node); } @Override - public void setSpatial(Spatial spatial){ + public void setSpatial(Spatial spatial) { } @Override @@ -368,20 +368,20 @@ public InstancedNode clone(boolean cloneMaterials) { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { super.cloneFields(cloner, original); this.control = cloner.clone(control); this.lookUp = cloner.clone(lookUp); HashMap newIgByGeom = new HashMap<>(); - for( Map.Entry e : igByGeom.entrySet() ) { + for (Map.Entry e : igByGeom.entrySet()) { newIgByGeom.put(cloner.clone(e.getKey()), cloner.clone(e.getValue())); } this.igByGeom = newIgByGeom; HashMap newInstancesMap = new HashMap<>(); - for( Map.Entry e : instancesMap.entrySet() ) { + for (Map.Entry e : instancesMap.entrySet()) { newInstancesMap.put(cloner.clone(e.getKey()), cloner.clone(e.getValue())); } this.instancesMap = newInstancesMap; diff --git a/jme3-core/src/main/java/com/jme3/scene/shape/Cylinder.java b/jme3-core/src/main/java/com/jme3/scene/shape/Cylinder.java index bf54337e28..36df9d9892 100644 --- a/jme3-core/src/main/java/com/jme3/scene/shape/Cylinder.java +++ b/jme3-core/src/main/java/com/jme3/scene/shape/Cylinder.java @@ -122,7 +122,7 @@ public Cylinder(int axisSamples, int radialSamples, * and the rest of the texture is used for the cylinder wall. The middle of the top is * mapped to texture coordinates (0.5, 1), bottom to (0.5, 0). Thus, it requires * - * @param axisSamples The number of vertices samples along the axis. It is equal to the number of segments + 1; so + * @param axisSamples The number of vertices samples along the axis. It is equal to the number of segments + 1; so * that, for instance, 4 samples mean the cylinder will be made of 3 segments. * @param radialSamples The number of triangle samples along the radius. For instance, 4 means that the sides of the * cylinder are made of 4 rectangles, and the top and bottom are made of 4 triangles. @@ -196,10 +196,12 @@ public boolean isInverted() { /** * Rebuilds the cylinder based on a new set of parameters. * - * @param axisSamples The number of vertices samples along the axis. It is equal to the number of segments + 1; so - * that, for instance, 4 samples mean the cylinder will be made of 3 segments. - * @param radialSamples The number of triangle samples along the radius. For instance, 4 means that the sides of the - * cylinder are made of 4 rectangles, and the top and bottom are made of 4 triangles. + * @param axisSamples The number of vertices samples along the axis. + * It is equal to the number of segments + 1; so + * that, for instance, 4 samples mean the cylinder will be made of 3 segments. + * @param radialSamples The number of triangle samples along the radius. + * For instance, 4 means that the sides of the + * cylinder are made of 4 rectangles, and the top and bottom are made of 4 triangles. * @param topRadius the radius of the top of the cylinder. * @param bottomRadius the radius of the bottom of the cylinder. * @param height the cylinder's height. @@ -209,14 +211,14 @@ public boolean isInverted() { public void updateGeometry(int axisSamples, int radialSamples, float topRadius, float bottomRadius, float height, boolean closed, boolean inverted) { // Ensure there's at least two axis samples and 3 radial samples, and positive dimensions. - if( axisSamples < 2 + if (axisSamples < 2 || radialSamples < 3 || topRadius <= 0 || bottomRadius <= 0 - || height <= 0 ) { + || height <= 0) { throw new IllegalArgumentException("Cylinders must have at least 2 axis samples and 3 radial samples, and positive dimensions."); } - + this.axisSamples = axisSamples; this.radialSamples = radialSamples; this.radius = bottomRadius; @@ -229,7 +231,7 @@ public void updateGeometry(int axisSamples, int radialSamples, int verticesCount = axisSamples * (radialSamples +1); // Triangles: Two per side rectangle, which is the product of numbers of samples. int trianglesCount = axisSamples * radialSamples * 2 ; - if( closed ) { + if (closed) { // If there are caps, add two additional rims and two summits. verticesCount += 2 + 2 * (radialSamples +1); // Add one triangle per radial sample, twice, to form the caps. @@ -246,9 +248,9 @@ public void updateGeometry(int axisSamples, int radialSamples, // Add a point to close the texture around the side of the cylinder. circlePoints[radialSamples][0] = circlePoints[0][0]; circlePoints[radialSamples][1] = circlePoints[0][1]; - + // Calculate normals. - // + // // A---------B // \ | // \ | @@ -263,7 +265,9 @@ public void updateGeometry(int axisSamples, int radialSamples, // The normal is the orthogonal to the side, which can be got without trigonometry. // The edge direction is oriented so that it goes up by Height, and out by the radius difference; let's use // those values in reverse order. - Vector3f normal = new Vector3f(height * circlePoints[circlePoint][0], height * circlePoints[circlePoint][1], bottomRadius - topRadius ); + Vector3f normal = new Vector3f(height * circlePoints[circlePoint][0], + height * circlePoints[circlePoint][1], + bottomRadius - topRadius); circleNormals[circlePoint] = normal.normalizeLocal(); } @@ -271,38 +275,39 @@ public void updateGeometry(int axisSamples, int radialSamples, float[] normals = new float[verticesCount * 3]; float[] textureCoords = new float[verticesCount * 2]; int currentIndex = 0; - + // Add a circle of points for each axis sample. - for(int axisSample = 0; axisSample < axisSamples; axisSample++ ) { - float currentHeight = -height / 2 + height * axisSample / (axisSamples-1); - float currentRadius = bottomRadius + (topRadius - bottomRadius) * axisSample / (axisSamples-1); - + for (int axisSample = 0; axisSample < axisSamples; axisSample++) { + float currentHeight = -height / 2 + height * axisSample / (axisSamples - 1); + float currentRadius = bottomRadius + (topRadius - bottomRadius) * axisSample / (axisSamples - 1); + for (int circlePoint = 0; circlePoint < radialSamples + 1; circlePoint++) { // Position, by multiplying the position on a unit circle with the current radius. vertices[currentIndex*3] = circlePoints[circlePoint][0] * currentRadius; vertices[currentIndex*3 +1] = circlePoints[circlePoint][1] * currentRadius; vertices[currentIndex*3 +2] = currentHeight; - + // Normal Vector3f currentNormal = circleNormals[circlePoint]; normals[currentIndex*3] = currentNormal.x; normals[currentIndex*3+1] = currentNormal.y; normals[currentIndex*3+2] = currentNormal.z; - + // Texture // The X is the angular position of the point. - textureCoords[currentIndex *2] = (float) circlePoint / radialSamples; - // Depending on whether there is a cap, the Y is either the height scaled to [0,1], or the radii of + textureCoords[currentIndex * 2] = (float) circlePoint / radialSamples; + // Depending on whether there is a cap, the Y is either the height scaled to [0,1], or the radii of // the cap count as well. if (closed) - textureCoords[currentIndex *2 +1] = (bottomRadius + height / 2 + currentHeight) / (bottomRadius + height + topRadius); + textureCoords[currentIndex * 2 + 1] = (bottomRadius + height / 2 + currentHeight) + / (bottomRadius + height + topRadius); else - textureCoords[currentIndex *2 +1] = height / 2 + currentHeight; - + textureCoords[currentIndex * 2 + 1] = height / 2 + currentHeight; + currentIndex++; } } - + // If closed, add duplicate rims on top and bottom, with normals facing up and down. if (closed) { // Bottom @@ -335,29 +340,29 @@ public void updateGeometry(int axisSamples, int radialSamples, currentIndex++; } - + // Add the centers of the caps. vertices[currentIndex*3] = 0; vertices[currentIndex*3 +1] = 0; vertices[currentIndex*3 +2] = -height/2; - + normals[currentIndex*3] = 0; normals[currentIndex*3+1] = 0; normals[currentIndex*3+2] = -1; - + textureCoords[currentIndex *2] = 0.5f; textureCoords[currentIndex *2+1] = 0f; - + currentIndex++; - + vertices[currentIndex*3] = 0; vertices[currentIndex*3 +1] = 0; vertices[currentIndex*3 +2] = height/2; - + normals[currentIndex*3] = 0; normals[currentIndex*3+1] = 0; normals[currentIndex*3+2] = 1; - + textureCoords[currentIndex *2] = 0.5f; textureCoords[currentIndex *2+1] = 1f; } @@ -380,16 +385,16 @@ public void updateGeometry(int axisSamples, int radialSamples, if(closed) { short bottomCapIndex = (short) (verticesCount - 2); short topCapIndex = (short) (verticesCount - 1); - + int bottomRowOffset = (axisSamples) * (radialSamples +1 ); int topRowOffset = (axisSamples+1) * (radialSamples +1 ); - + for (int circlePoint = 0; circlePoint < radialSamples; circlePoint++) { indices[currentIndex++] = (short) (bottomRowOffset + circlePoint +1); indices[currentIndex++] = (short) (bottomRowOffset + circlePoint); indices[currentIndex++] = bottomCapIndex; - + indices[currentIndex++] = (short) (topRowOffset + circlePoint); indices[currentIndex++] = (short) (topRowOffset + circlePoint +1); indices[currentIndex++] = topCapIndex; @@ -403,18 +408,18 @@ public void updateGeometry(int axisSamples, int radialSamples, indices[i] = indices[indices.length - 1 - i]; indices[indices.length - 1 - i] = temp; } - - for(int i = 0; i< normals.length; i++) { + + for (int i = 0; i< normals.length; i++) { normals[i] = -normals[i]; } } - + // Fill in the buffers. setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(vertices)); setBuffer(Type.Normal, 3, BufferUtils.createFloatBuffer(normals)); setBuffer(Type.TexCoord, 2, BufferUtils.createFloatBuffer(textureCoords)); setBuffer(Type.Index, 3, BufferUtils.createShortBuffer(indices)); - + updateBound(); setStatic(); } diff --git a/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java b/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java index 4a306c7375..5cfd312f82 100644 --- a/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java +++ b/jme3-core/src/main/java/com/jme3/scene/shape/Dome.java @@ -48,7 +48,7 @@ /** * A hemisphere. - * + * * @author Peter Andersson * @author Joshua Slack (Original sphere code that was adapted) * @version $Revision: 4131 $, $Date: 2009-03-19 16:15:28 -0400 (Thu, 19 Mar 2009) $ @@ -70,8 +70,8 @@ protected Dome() { } /** - * Constructs a dome for use as a SkyDome. The SkyDome is centered at the origin - * and only visible from the inside. + * Constructs a dome for use as a SkyDome. The SkyDome is centered at the origin + * and only visible from the inside. * @param planes * The number of planes along the Z-axis. Must be >= 2. * Influences how round the arch of the dome is. @@ -87,18 +87,18 @@ public Dome(int planes, int radialSamples, float radius) { } /** - * Constructs a dome visible from the inside, e.g. for use as a SkyDome. + * Constructs a dome visible from the inside, e.g. for use as a SkyDome. * All geometry data buffers are updated automatically.
    * For a cone, set planes=2. For a pyramid, set radialSamples=4 and planes=2. * Increasing planes and radialSamples increase the quality of the dome. - * + * * @param center * Center of the dome. * @param planes * The number of planes along the Z-axis. Must be >= 2. * Influences how round the arch of the dome is. * @param radialSamples - * The number of samples along the radial. + * The number of samples along the radial. * Influences how round the base of the dome is. * @param radius * The radius of the dome. @@ -110,12 +110,12 @@ public Dome(Vector3f center, int planes, int radialSamples, } /** - * Constructs a dome. Use this constructor for half-sphere, pyramids, or cones. + * Constructs a dome. Use this constructor for half-sphere, pyramids, or cones. * All geometry data buffers are updated automatically.
    * For a cone, set planes=2. For a pyramid, set radialSamples=4 and planes=2. - * Setting higher values for planes and radialSamples increases + * Setting higher values for planes and radialSamples increases * the quality of the half-sphere. - * + * * @param center * Center of the dome. * @param planes @@ -140,8 +140,8 @@ public Vector3f getCenter() { return center; } - /** - * Get the number of planar segments along the z-axis of the dome. + /** + * Get the number of planar segments along the z-axis of the dome. * * @return the count */ @@ -149,8 +149,8 @@ public int getPlanes() { return planes; } - /** - * Get the number of samples radially around the main axis of the dome. + /** + * Get the number of samples radially around the main axis of the dome. * * @return the count */ @@ -158,8 +158,8 @@ public int getRadialSamples() { return radialSamples; } - /** - * Get the radius of the dome. + /** + * Get the radius of the dome. * * @return the radius (in mesh units) */ @@ -169,7 +169,7 @@ public float getRadius() { /** * Are the triangles connected in such a way as to present a view out from the dome or not. - * + * * @return true if visible from inside, false if visible from outside */ public boolean isInsideView() { @@ -178,7 +178,7 @@ public boolean isInsideView() { /** * Rebuilds the dome with a new set of parameters. - * + * * @param center the new center of the dome. * @param planes the number of planes along the Z-axis. * @param radialSamples the new number of radial samples of the dome. @@ -290,14 +290,14 @@ public void updateGeometry(Vector3f center, int planes, int bottomPlaneStart = ((plane - 1) * (radialSamples + 1)); int topPlaneStart = (plane * (radialSamples + 1)); for (int sample = 0; sample < radialSamples; sample++, index += 6) { - if (insideView){ + if (insideView) { ib.put((short) (bottomPlaneStart + sample)); ib.put((short) (bottomPlaneStart + sample + 1)); ib.put((short) (topPlaneStart + sample)); ib.put((short) (bottomPlaneStart + sample + 1)); ib.put((short) (topPlaneStart + sample + 1)); ib.put((short) (topPlaneStart + sample)); - }else{ + } else { ib.put((short) (bottomPlaneStart + sample)); ib.put((short) (topPlaneStart + sample)); ib.put((short) (bottomPlaneStart + sample + 1)); @@ -311,11 +311,11 @@ public void updateGeometry(Vector3f center, int planes, // pole triangles int bottomPlaneStart = (planes - 2) * (radialSamples + 1); for (int samples = 0; samples < radialSamples; samples++, index += 3) { - if (insideView){ + if (insideView) { ib.put((short) (bottomPlaneStart + samples)); ib.put((short) (bottomPlaneStart + samples + 1)); ib.put((short) (vertCount - 1)); - }else{ + } else { ib.put((short) (bottomPlaneStart + samples)); ib.put((short) (vertCount - 1)); ib.put((short) (bottomPlaneStart + samples + 1)); diff --git a/jme3-core/src/main/java/com/jme3/scene/shape/Quad.java b/jme3-core/src/main/java/com/jme3/scene/shape/Quad.java index 30f8d95976..07c161c301 100644 --- a/jme3-core/src/main/java/com/jme3/scene/shape/Quad.java +++ b/jme3-core/src/main/java/com/jme3/scene/shape/Quad.java @@ -45,7 +45,7 @@ * defined by 4 vertices. The quad's lower-left side is contained * at the local space origin (0, 0, 0), while the upper-right * side is located at the width/height coordinates (width, height, 0). - * + * * @author Kirill Vainer */ public class Quad extends Mesh { @@ -56,30 +56,30 @@ public class Quad extends Mesh { /** * Serialization only. Do not use. */ - protected Quad(){ + protected Quad() { } /** * Create a quad with the given width and height. The quad * is always created in the XY plane. - * + * * @param width The X extent or width * @param height The Y extent or width */ - public Quad(float width, float height){ + public Quad(float width, float height) { updateGeometry(width, height); } /** * Create a quad with the given width and height. The quad * is always created in the XY plane. - * + * * @param width The X extent or width * @param height The Y extent or width * @param flipCoords If true, the texture coordinates will be flipped * along the Y axis. */ - public Quad(float width, float height, boolean flipCoords){ + public Quad(float width, float height, boolean flipCoords) { updateGeometry(width, height, flipCoords); } @@ -91,7 +91,7 @@ public float getWidth() { return width; } - public void updateGeometry(float width, float height){ + public void updateGeometry(float width, float height) { updateGeometry(width, height, false); } @@ -103,14 +103,14 @@ public void updateGeometry(float width, float height, boolean flipCoords) { width, height, 0, 0, height, 0 }); - - if (flipCoords){ + + if (flipCoords) { setBuffer(Type.TexCoord, 2, new float[]{0, 1, 1, 1, 1, 0, 0, 0}); - }else{ + } else { setBuffer(Type.TexCoord, 2, new float[]{0, 0, 1, 0, 1, 1, @@ -120,18 +120,18 @@ public void updateGeometry(float width, float height, boolean flipCoords) { 0, 0, 1, 0, 0, 1, 0, 0, 1}); - if (height < 0){ + if (height < 0) { setBuffer(Type.Index, 3, new short[]{0, 2, 1, 0, 3, 2}); - }else{ + } else { setBuffer(Type.Index, 3, new short[]{0, 1, 2, 0, 2, 3}); } - + updateBound(); setStatic(); } - + @Override public void read(JmeImporter importer) throws IOException { super.read(importer); diff --git a/jme3-core/src/main/java/com/jme3/scene/shape/Surface.java b/jme3-core/src/main/java/com/jme3/scene/shape/Surface.java index 95cb49c989..9beef259e4 100644 --- a/jme3-core/src/main/java/com/jme3/scene/shape/Surface.java +++ b/jme3-core/src/main/java/com/jme3/scene/shape/Surface.java @@ -177,20 +177,27 @@ private void buildSurface(boolean smooth) { int vVerticesAmount = vSegments + 1; int newUVerticesAmount = 2 + (uVerticesAmount - 2) * 2; List verticesWithUDuplicates = new ArrayList<>(vVerticesAmount * newUVerticesAmount); - for(int i=0;i verticesWithVDuplicates = new ArrayList<>(verticesWithUDuplicates.size() * vVerticesAmount); + List verticesWithVDuplicates + = new ArrayList<>(verticesWithUDuplicates.size() * vVerticesAmount); verticesWithVDuplicates.addAll(verticesWithUDuplicates.subList(0, newUVerticesAmount)); - for(int i=1;i normalMap = new HashMap<>(verticesArray.length); for (int i = 0; i < indices.length; i += 3) { - Vector3f n = FastMath.computeNormal(verticesArray[indices[i]], verticesArray[indices[i + 1]], verticesArray[indices[i + 2]]); - this.addNormal(n, normalMap, smooth, verticesArray[indices[i]], verticesArray[indices[i + 1]], verticesArray[indices[i + 2]]); + Vector3f n = FastMath.computeNormal(verticesArray[indices[i]], + verticesArray[indices[i + 1]], verticesArray[indices[i + 2]]); + this.addNormal(n, normalMap, smooth, verticesArray[indices[i]], + verticesArray[indices[i + 1]], verticesArray[indices[i + 2]]); } // preparing normal list (the order of normals must match the order of vertices) float[] normals = new float[verticesArray.length * 3]; @@ -423,7 +432,7 @@ private float getMaxVNurbKnot() { * @param normalMap * merges normals of faces that will be rendered smooth; the key is the vertex and the value - its normal vector * @param smooth the variable that indicates whether to merge normals - * (creating the smooth mesh) or not + * (creating the smooth mesh) or not * @param vertices * a list of vertices read from the blender file */ diff --git a/jme3-core/src/main/java/com/jme3/shader/Shader.java b/jme3-core/src/main/java/com/jme3/shader/Shader.java index 04e4abe5ef..7860e29b13 100644 --- a/jme3-core/src/main/java/com/jme3/shader/Shader.java +++ b/jme3-core/src/main/java/com/jme3/shader/Shader.java @@ -41,7 +41,7 @@ import java.util.Collection; public final class Shader extends NativeObject { - + /** * A list of all shader sources currently attached. */ @@ -56,10 +56,10 @@ public final class Shader extends NativeObject { * Maps storage block name to the buffer block variables. */ private final ListMap bufferBlocks; - + /** * Uniforms bound to {@link UniformBinding}s. - * + * * Managed by the {@link UniformBindingManager}. */ private final ArrayList boundUniforms; @@ -99,11 +99,11 @@ public static enum ShaderType { TessellationEvaluation("tseval"); private String extension; - + public String getExtension() { return extension; } - + private ShaderType(String extension) { this.extension = extension; } @@ -121,29 +121,29 @@ public static class ShaderSource extends NativeObject { String source; String defines; - public ShaderSource(ShaderType type){ + public ShaderSource(ShaderType type) { super(); this.sourceType = type; if (type == null) { throw new IllegalArgumentException("The shader type must be specified"); } } - - protected ShaderSource(ShaderSource ss){ + + protected ShaderSource(ShaderSource ss) { super(ss.id); // No data needs to be copied. // (This is a destructible clone) } - public ShaderSource(){ + public ShaderSource() { super(); } - public void setName(String name){ + public void setName(String name) { this.name = name; } - public String getName(){ + public String getName() { return name; } @@ -163,7 +163,7 @@ public void setLanguage(String language) { setUpdateNeeded(); } - public void setSource(String source){ + public void setSource(String source) { if (source == null) { throw new IllegalArgumentException("Shader source cannot be null"); } @@ -171,7 +171,7 @@ public void setSource(String source){ setUpdateNeeded(); } - public void setDefines(String defines){ + public void setDefines(String defines) { if (defines == null) { throw new IllegalArgumentException("Shader defines cannot be null"); } @@ -179,40 +179,40 @@ public void setDefines(String defines){ setUpdateNeeded(); } - public String getSource(){ + public String getSource() { return source; } - public String getDefines(){ + public String getDefines() { return defines; } - + @Override public long getUniqueId() { return ((long)OBJTYPE_SHADERSOURCE << 32) | ((long)id); } - + @Override - public String toString(){ + public String toString() { String nameTxt = ""; if (name != null) nameTxt = "name="+name+", "; if (defines != null) nameTxt += "defines, "; - + return getClass().getSimpleName() + "["+nameTxt+"type=" + sourceType.name()+", language=" + language + "]"; } @Override - public void resetObject(){ + public void resetObject() { id = -1; setUpdateNeeded(); } @Override - public void deleteObject(Object rendererObject){ + public void deleteObject(Object rendererObject) { ((Renderer)rendererObject).deleteShaderSource(ShaderSource.this); } @@ -226,7 +226,7 @@ public NativeObject createDestructableClone(){ * Creates a new shader, initialize() must be called * after this constructor for the shader to be usable. */ - public Shader(){ + public Shader() { super(); shaderSourceList = new ArrayList<>(); uniforms = new ListMap<>(); @@ -240,16 +240,16 @@ public Shader(){ * * @param s (not null) */ - protected Shader(Shader s){ + protected Shader(Shader s) { super(s.id); - + // Shader sources cannot be shared, therefore they must // be destroyed together with the parent shader. shaderSourceList = new ArrayList(); for (ShaderSource source : s.shaderSourceList){ - shaderSourceList.add( (ShaderSource)source.createDestructableClone() ); + shaderSourceList.add((ShaderSource) source.createDestructableClone()); } - + uniforms = null; bufferBlocks = null; boundUniforms = null; @@ -289,7 +289,7 @@ public void addUniformBinding(UniformBinding binding){ boundUniforms.add(uniform); } } - + public Uniform getUniform(String name){ assert name.startsWith("m_") || name.startsWith("g_"); Uniform uniform = uniforms.get(name); @@ -369,7 +369,7 @@ public Collection getSources(){ @Override public String toString() { - return getClass().getSimpleName() + + return getClass().getSimpleName() + "[numSources=" + shaderSourceList.size() + ", numUniforms=" + uniforms.size() + ", numBufferBlocks=" + bufferBlocks.size() + @@ -379,7 +379,7 @@ public String toString() { /** * Removes the "set-by-current-material" flag from all uniforms. * When a uniform is modified after this call, the flag shall - * become "set-by-current-material". + * become "set-by-current-material". * A call to {@link #resetUniformsNotSetByCurrent() } will reset * all uniforms that do not have the "set-by-current-material" flag * to their default value (usually all zeroes or false). diff --git a/jme3-core/src/main/java/com/jme3/shader/ShaderGenerator.java b/jme3-core/src/main/java/com/jme3/shader/ShaderGenerator.java index 5ad6f3b04e..3376234233 100644 --- a/jme3-core/src/main/java/com/jme3/shader/ShaderGenerator.java +++ b/jme3-core/src/main/java/com/jme3/shader/ShaderGenerator.java @@ -80,13 +80,13 @@ public abstract class ShaderGenerator { * @param assetManager for loading assets (alias created) */ protected ShaderGenerator(AssetManager assetManager) { - this.assetManager = assetManager; + this.assetManager = assetManager; } - + public void initialize(TechniqueDef techniqueDef){ this.techniqueDef = techniqueDef; } - + /** * Generate vertex and fragment shaders for the given technique * @@ -108,13 +108,13 @@ public Shader generateShader(String definesSourceCode) { String extension = type.getExtension(); String language = getLanguageAndVersion(type); String shaderSourceCode = buildShader(techniqueDef.getShaderNodes(), info, type); - + if (shaderSourceCode != null) { String shaderSourceAssetName = techniqueName + "." + extension; shader.addSource(type, shaderSourceAssetName, shaderSourceCode, definesSourceCode, language); } } - + techniqueDef = null; return shader; } @@ -129,7 +129,7 @@ public Shader generateShader(String definesSourceCode) { */ protected String buildShader(List shaderNodes, ShaderGenerationInfo info, ShaderType type) { if (type == ShaderType.TessellationControl || - type == ShaderType.TessellationEvaluation || + type == ShaderType.TessellationEvaluation || type == ShaderType.Geometry) { // TODO: Those are not supported. // Too much code assumes that type is either Vertex or Fragment @@ -174,9 +174,9 @@ protected String buildShader(List shaderNodes, ShaderGenerationInfo * @return */ private String moveExtensionsUp(StringBuilder sourceDeclaration) { - Matcher m = extensions.matcher( sourceDeclaration.toString()); + Matcher m = extensions.matcher(sourceDeclaration.toString()); StringBuilder finalSource = new StringBuilder(); - while(m.find()){ + while (m.find()) { finalSource.append(m.group()); } finalSource.append(m.replaceAll("")); @@ -295,7 +295,7 @@ protected void appendNodeDeclarationAndMain(String loadedSource, StringBuilder s * * @see ShaderNode#getDefinition() * @see ShaderNodeDefinition#getType() - * + * * @param nodeDeclarationSource the declaration part of the node * @param source the StringBuilder to append generated code. * @param shaderNode the shaderNode. @@ -364,5 +364,5 @@ protected int findShaderIndexFromVersion(ShaderNode shaderNode, ShaderType type) } } return index; - } + } } diff --git a/jme3-core/src/main/java/com/jme3/shader/ShaderNodeDefinition.java b/jme3-core/src/main/java/com/jme3/shader/ShaderNodeDefinition.java index 121c8cbe74..fce3369a99 100644 --- a/jme3-core/src/main/java/com/jme3/shader/ShaderNodeDefinition.java +++ b/jme3-core/src/main/java/com/jme3/shader/ShaderNodeDefinition.java @@ -183,8 +183,8 @@ public String getPath() { public void setPath(String path) { this.path = path; } - - + + /** * jme serialization (not used) @@ -220,8 +220,8 @@ public void setNoOutput(boolean noOutput) { this.noOutput = noOutput; } - - + + /** * jme serialization (not used) * @@ -260,6 +260,8 @@ public void read(JmeImporter im) throws IOException { */ @Override public String toString() { - return "\nShaderNodeDefinition{\n" + "name=" + name + "\ntype=" + type + "\nshaderPath=" + shadersPath + "\nshaderLanguage=" + shadersLanguage + "\ndocumentation=" + documentation + "\ninputs=" + inputs + ",\noutputs=" + outputs + '}'; + return "\nShaderNodeDefinition{\n" + "name=" + name + "\ntype=" + type + + "\nshaderPath=" + shadersPath + "\nshaderLanguage=" + shadersLanguage + + "\ndocumentation=" + documentation + "\ninputs=" + inputs + ",\noutputs=" + outputs + '}'; } } diff --git a/jme3-core/src/main/java/com/jme3/shader/Uniform.java b/jme3-core/src/main/java/com/jme3/shader/Uniform.java index 7836ab4881..28ae71b1ba 100644 --- a/jme3-core/src/main/java/com/jme3/shader/Uniform.java +++ b/jme3-core/src/main/java/com/jme3/shader/Uniform.java @@ -47,7 +47,7 @@ public class Uniform extends ShaderVariable { * Currently set value of the uniform. */ protected Object value = null; - + /** * For arrays or matrices, efficient format * that can be sent to GL faster. @@ -126,7 +126,7 @@ public VarType getVarType() { public Object getValue(){ return value; } - + public FloatBuffer getMultiData() { return multiData; } @@ -142,12 +142,12 @@ public void clearSetByCurrentMaterial(){ public void clearValue(){ updateNeeded = true; - if (multiData != null){ + if (multiData != null){ multiData.clear(); while (multiData.remaining() > 0){ ZERO_BUF.clear(); - ZERO_BUF.limit( Math.min(multiData.remaining(), 16) ); + ZERO_BUF.limit(Math.min(multiData.remaining(), 16)); multiData.put(ZERO_BUF); } @@ -159,7 +159,7 @@ public void clearValue(){ if (varType == null) { return; } - + switch (varType){ case Int: this.value = ZERO_INT; @@ -168,7 +168,7 @@ public void clearValue(){ this.value = Boolean.FALSE; break; case Float: - this.value = ZERO_FLT; + this.value = ZERO_FLT; break; case Vector2: if (this.value != null) { @@ -196,7 +196,7 @@ public void clearValue(){ // or multidata types } } - + public void setValue(VarType type, Object value){ if (location == LOC_NOT_DEFINED) { return; @@ -407,7 +407,7 @@ public void setVector4Length(int length){ if (location == -1) { return; } - + multiData = BufferUtils.ensureLargeEnough(multiData, length * 4); value = multiData; varType = VarType.Vector4Array; @@ -430,7 +430,7 @@ public void setVector4InArray(float x, float y, float z, float w, int index){ updateNeeded = true; setByCurrentMaterial = true; } - + public boolean isUpdateNeeded(){ return updateNeeded; } diff --git a/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java b/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java index c1f2e3e293..384630b521 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java +++ b/jme3-core/src/main/java/com/jme3/shadow/AbstractShadowRenderer.java @@ -126,13 +126,13 @@ public abstract class AbstractShadowRenderer implements SceneProcessor, Savable, * true to skip the post pass when there are no shadow casters */ protected boolean skipPostPass; - + /** * used for serialization */ - protected AbstractShadowRenderer(){ - } - + protected AbstractShadowRenderer() { + } + /** * Create an abstract shadow renderer. Subclasses invoke this constructor. * @@ -175,7 +175,7 @@ private void init(AssetManager assetManager, int nbShadowMaps, int shadowMapSize //DO NOT COMMENT THIS (it prevents the OSX incomplete read-buffer crash) shadowFB[i].addColorTarget(FrameBufferTarget.newTarget(dummyTex)); - shadowMapStringCache[i] = "ShadowMap" + i; + shadowMapStringCache[i] = "ShadowMap" + i; lightViewStringCache[i] = "LightViewProjectionMatrix" + i; postshadowMat.setTexture(shadowMapStringCache[i], shadowMaps[i]); @@ -294,7 +294,7 @@ public CompareMode getShadowCompareMode() { /** * debug function to create a visible frustum - * + * * @param pts optional storage for vertex positions (may be null) * @param i the index of the desired wire color (default=White) * @return a new Geometry @@ -344,7 +344,7 @@ public void initialize(RenderManager rm, ViewPort vp) { initFrustumCam(); } } - + /** * delegates the initialization of the frustum cam to child renderers */ @@ -363,7 +363,7 @@ public boolean isInitialized() { /** * Invoked once per frame to update the shadow cams according to the light * view. - * + * * @param viewCam the scene cam */ protected abstract void updateShadowCams(Camera viewCam); @@ -401,13 +401,13 @@ protected void doDisplayFrustumDebug(int shadowMapIndex) { public void postQueue(RenderQueue rq) { lightReceivers.clear(); skipPostPass = false; - if ( !checkCulling(viewPort.getCamera()) ) { + if (!checkCulling(viewPort.getCamera())) { skipPostPass = true; return; } updateShadowCams(viewPort.getCamera()); - + Renderer r = renderManager.getRenderer(); renderManager.setForcedMaterial(preshadowMat); renderManager.setForcedTechnique("PreShadow"); @@ -428,14 +428,14 @@ public void postQueue(RenderQueue rq) { renderManager.setForcedMaterial(null); renderManager.setForcedTechnique(null); renderManager.setCamera(viewPort.getCamera(), false); - + } protected void renderShadowMap(int shadowMapIndex) { shadowMapOccluders = getOccludersToRender(shadowMapIndex, shadowMapOccluders); Camera shadowCam = getShadowCam(shadowMapIndex); - //saving light view projection matrix for this split + //saving light view projection matrix for this split lightViewProjectionsMatrices[shadowMapIndex].set(shadowCam.getViewProjectionMatrix()); renderManager.setCamera(shadowCam, false); @@ -489,7 +489,7 @@ public void postFrame(FrameBuffer out) { if (debug) { displayShadowMap(renderManager.getRenderer()); } - + getReceivers(lightReceivers); if (lightReceivers.size() != 0) { @@ -512,26 +512,26 @@ public void postFrame(FrameBuffer out) { renderManager.setForcedTechnique(null); renderManager.setForcedMaterial(null); renderManager.setCamera(cam, false); - + //clearing the params in case there are some other shadow renderers clearMatParams(); } } - + /** * This method is called once per frame and is responsible for clearing any * material parameters that subclasses may need to clear on the post material. * - * @param material the material that was used for the post shadow pass + * @param material the material that was used for the post shadow pass */ - protected abstract void clearMaterialParameters(Material material); - + protected abstract void clearMaterialParameters(Material material); + private void clearMatParams(){ for (Material mat : matCache) { - - //clearing only necessary params, the others may be set by other - //renderers - //Note that j start at 1 because other shadow renderers will have + + //clearing only necessary params, the others may be set by other + //renderers + //Note that j start at 1 because other shadow renderers will have //at least 1 shadow map and will set it on each frame anyway. for (int j = 1; j < nbShadowMaps; j++) { mat.clearParam(lightViewStringCache[j]); @@ -541,8 +541,8 @@ private void clearMatParams(){ } mat.clearParam("FadeInfo"); clearMaterialParameters(mat); - } - //No need to clear the postShadowMat params as the instance is locale to each renderer + } + //No need to clear the postShadowMat params as the instance is locale to each renderer } /** @@ -621,7 +621,7 @@ protected void setPostShadowParams() { } postshadowMat.setBoolean("BackfaceShadows", renderBackFacesShadows); } - + /** * How far the shadows are rendered in the view * @@ -640,7 +640,7 @@ public float getShadowZExtend() { * @param zFar the zFar values that override the computed one */ public void setShadowZExtend(float zFar) { - this.zFarOverride = zFar; + this.zFarOverride = zFar; if(zFarOverride == 0){ fadeInfo = null; frustumCam = null; @@ -653,7 +653,7 @@ public void setShadowZExtend(float zFar) { } } } - + /** * Define the length over which the shadow will fade out when using a * shadowZextend This is useful to make dynamic shadows fade into baked @@ -689,15 +689,15 @@ public float getShadowZFadeLength() { } return 0f; } - + /** * @param viewCam a Camera to define the view frustum * @return true if the light source bounding box is in the view frustum */ protected abstract boolean checkCulling(Camera viewCam); - + @Override - public void preFrame(float tpf) { + public void preFrame(float tpf) { } @Override diff --git a/jme3-core/src/main/java/com/jme3/shadow/ShadowUtil.java b/jme3-core/src/main/java/com/jme3/shadow/ShadowUtil.java index 25eea3983d..9f7abee4b0 100644 --- a/jme3-core/src/main/java/com/jme3/shadow/ShadowUtil.java +++ b/jme3-core/src/main/java/com/jme3/shadow/ShadowUtil.java @@ -351,20 +351,20 @@ public static void updateShadowCamera(Camera shadowCam, Vector3f[] points) { * all of them one by one against camera frustum the whole Node is checked first * to hopefully avoid the check on its children. */ - public static class OccludersExtractor - { + public static class OccludersExtractor { // global variables set in order not to have recursive process method with too many parameters Matrix4f viewProjMatrix; public Integer casterCount; BoundingBox splitBB, casterBB; GeometryList splitOccluders; TempVars vars; - + public OccludersExtractor() {} - + // initialize the global OccludersExtractor variables - public OccludersExtractor(Matrix4f vpm, int cc, BoundingBox sBB, BoundingBox cBB, GeometryList sOCC, TempVars v) { - viewProjMatrix = vpm; + public OccludersExtractor(Matrix4f vpm, int cc, BoundingBox sBB, BoundingBox cBB, + GeometryList sOCC, TempVars v) { + viewProjMatrix = vpm; casterCount = cc; splitBB = sBB; casterBB = cBB; @@ -376,32 +376,31 @@ public OccludersExtractor(Matrix4f vpm, int cc, BoundingBox sBB, BoundingBox cBB * Check the rootScene against camera frustum and if intersects process it recursively. * The global OccludersExtractor variables need to be initialized first. * Variables are updated and used in {@link ShadowUtil#updateShadowCamera} at last. - * + * * @param scene the root of the scene to check (may be null) * @return the number of shadow casters found */ public int addOccluders(Spatial scene) { - if ( scene != null ) process(scene); + if (scene != null) process(scene); return casterCount; } - + private void process(Spatial scene) { if (scene.getCullHint() == Spatial.CullHint.Always) return; RenderQueue.ShadowMode shadowMode = scene.getShadowMode(); - if ( scene instanceof Geometry ) - { + if (scene instanceof Geometry) { // convert bounding box to light's viewproj space Geometry occluder = (Geometry)scene; if (shadowMode != RenderQueue.ShadowMode.Off && shadowMode != RenderQueue.ShadowMode.Receive && !occluder.isGrouped() && occluder.getWorldBound()!=null) { BoundingVolume bv = occluder.getWorldBound(); BoundingVolume occBox = bv.transform(viewProjMatrix, vars.bbox); - + boolean intersects = splitBB.intersects(occBox); if (!intersects && occBox instanceof BoundingBox) { BoundingBox occBB = (BoundingBox) occBox; - //Kirill 01/10/2011 + // Kirill 01/10/2011 // Extend the occluder further into the frustum // This fixes shadow disappearing issues when // the caster itself is not in the view camera @@ -416,7 +415,7 @@ private void process(Spatial scene) { // We return the bound to its former shape // Before adding it occBB.setZExtent(occBB.getZExtent() - 50); - occBB.setCenter(occBB.getCenter().subtractLocal(0, 0, 25)); + occBB.setCenter(occBB.getCenter().subtractLocal(0, 0, 25)); casterBB.mergeLocal(occBox); casterCount++; } @@ -432,15 +431,13 @@ private void process(Spatial scene) { } } } - } - else if ( scene instanceof Node && ((Node)scene).getWorldBound()!=null ) - { + } else if (scene instanceof Node && ((Node)scene).getWorldBound() != null) { Node nodeOcc = (Node)scene; boolean intersects = false; - // some + // some BoundingVolume bv = nodeOcc.getWorldBound(); BoundingVolume occBox = bv.transform(viewProjMatrix, vars.bbox); - + intersects = splitBB.intersects(occBox); if (!intersects && occBox instanceof BoundingBox) { BoundingBox occBB = (BoundingBox) occBox; @@ -454,8 +451,8 @@ else if ( scene instanceof Node && ((Node)scene).getWorldBound()!=null ) occBB.setCenter(occBB.getCenter().addLocal(0, 0, 25)); intersects = splitBB.intersects(occBB); } - - if ( intersects ) { + + if (intersects) { for (Spatial child : ((Node)scene).getChildren()) { process(child); } @@ -463,7 +460,7 @@ else if ( scene instanceof Node && ((Node)scene).getWorldBound()!=null ) } } } - + /** * Updates the shadow camera to properly contain the given points (which * contain the eye camera frustum corners) and the shadow occluder objects @@ -482,7 +479,7 @@ public static void updateShadowCamera(ViewPort viewPort, Vector3f[] points, GeometryList splitOccluders, float shadowMapSize) { - + boolean ortho = shadowCam.isParallelProjection(); shadowCam.setProjectionMatrix(null); @@ -491,18 +488,18 @@ public static void updateShadowCamera(ViewPort viewPort, shadowCam.setFrustum(-shadowCam.getFrustumFar(), shadowCam.getFrustumFar(), -1, 1, 1, -1); } - // create transform to rotate points to viewspace + // create transform to rotate points to viewspace Matrix4f viewProjMatrix = shadowCam.getViewProjectionMatrix(); BoundingBox splitBB = computeBoundForPoints(points, viewProjMatrix); TempVars vars = TempVars.get(); - + BoundingBox casterBB = new BoundingBox(); BoundingBox receiverBB = new BoundingBox(); - + int casterCount = 0, receiverCount = 0; - + for (int i = 0; i < receivers.size(); i++) { // convert bounding box to light's viewproj space Geometry receiver = receivers.get(i); @@ -524,7 +521,7 @@ public static void updateShadowCamera(ViewPort viewPort, occExt.addOccluders(scene); } casterCount = occExt.casterCount; - + //Nehon 08/18/2010 this is to avoid shadow bleeding when the ground is set to only receive shadows if (casterCount != receiverCount) { casterBB.setXExtent(casterBB.getXExtent() + 2.0f); @@ -576,7 +573,7 @@ public static void updateShadowCamera(ViewPort viewPort, float halfTextureSize = shadowMapSize * 0.5f; if (halfTextureSize != 0 && scaleX >0 && scaleY>0) { - float scaleQuantizer = 0.1f; + float scaleQuantizer = 0.1f; scaleX = 1.0f / FastMath.ceil(1.0f / scaleX * scaleQuantizer) * scaleQuantizer; scaleY = 1.0f / FastMath.ceil(1.0f / scaleY * scaleQuantizer) * scaleQuantizer; } @@ -613,7 +610,7 @@ public static void updateShadowCamera(ViewPort viewPort, shadowCam.setProjectionMatrix(result); } - + /** * Populates the outputGeometryList with the geometry of the * inputGeometryList that are in the frustum of the given camera @@ -648,7 +645,7 @@ public static void getGeometriesInCamFrustum(GeometryList inputGeometryList, * @param mode the ShadowMode to test for * @param outputGeometryList the list of all geometries that are in the * camera frustum - */ + */ public static void getGeometriesInCamFrustum(Spatial rootScene, Camera camera, RenderQueue.ShadowMode mode, GeometryList outputGeometryList) { if (rootScene != null && rootScene instanceof Node) { int planeState = camera.getPlaneState(); @@ -656,12 +653,12 @@ public static void getGeometriesInCamFrustum(Spatial rootScene, Camera camera, R camera.setPlaneState(planeState); } } - + /** * Helper function to distinguish between Occluders and Receivers - * + * * @param shadowMode the ShadowMode tested - * @param desired the desired ShadowMode + * @param desired the desired ShadowMode * @return true if tested ShadowMode matches the desired one */ static private boolean checkShadowMode(RenderQueue.ShadowMode shadowMode, RenderQueue.ShadowMode desired) @@ -669,9 +666,9 @@ static private boolean checkShadowMode(RenderQueue.ShadowMode shadowMode, Render if (shadowMode != RenderQueue.ShadowMode.Off) { switch (desired) { - case Cast : + case Cast : return shadowMode==RenderQueue.ShadowMode.Cast || shadowMode==RenderQueue.ShadowMode.CastAndReceive; - case Receive: + case Receive: return shadowMode==RenderQueue.ShadowMode.Receive || shadowMode==RenderQueue.ShadowMode.CastAndReceive; case CastAndReceive: return true; @@ -679,15 +676,15 @@ static private boolean checkShadowMode(RenderQueue.ShadowMode shadowMode, Render } return false; } - + /** - * Helper function used to recursively populate the outputGeometryList + * Helper function used to recursively populate the outputGeometryList * with geometry children of scene node - * + * * @param camera * @param scene the root of the scene to traverse (may be null) * @param mode the ShadowMode to test for - * @param outputGeometryList + * @param outputGeometryList */ private static void addGeometriesInCamFrustumFromNode(Camera camera, Node scene, RenderQueue.ShadowMode mode, GeometryList outputGeometryList) { if (scene.getCullHint() == Spatial.CullHint.Always) return; @@ -706,7 +703,7 @@ else if (child instanceof Geometry && child.getCullHint() != Spatial.CullHint.Al } } } - + /** * Populates the outputGeometryList with the geometry of the * inputGeometryList that are in the radius of a light. @@ -739,12 +736,12 @@ public static void getGeometriesInLightRadius(GeometryList inputGeometryList, } /** - * Populates the outputGeometryList with the geometries of the children + * Populates the outputGeometryList with the geometries of the children * of OccludersExtractor.rootScene node that are both in the frustum of the given vpCamera and some camera inside cameras array. * The array of cameras must be initialized to represent the light viewspace of some light like pointLight or spotLight * * @param rootScene the root of the scene to traverse (may be null) - * @param vpCamera the viewPort camera + * @param vpCamera the viewPort camera * @param cameras the camera array to check geometries against, representing the light viewspace * @param mode the ShadowMode to test for * @param outputGeometryList the output list of all geometries that are in the camera frustum @@ -756,8 +753,8 @@ public static void getLitGeometriesInViewPort(Spatial rootScene, Camera vpCamera } /** * Helper function to recursively collect the geometries for getLitGeometriesInViewPort function. - * - * @param vpCamera the viewPort camera + * + * @param vpCamera the viewPort camera * @param cameras the camera array to check geometries against, representing the light viewspace * @param scene the Node to traverse or geometry to possibly add * @param outputGeometryList the output list of all geometries that are in the camera frustum @@ -782,7 +779,7 @@ private static void addGeometriesInCamFrustumAndViewPortFromNode(Camera vpCamera } } else if (scene instanceof Geometry) { - if (checkShadowMode(scene.getShadowMode(), mode) && !((Geometry)scene).isGrouped() ) { + if (checkShadowMode(scene.getShadowMode(), mode) && !((Geometry)scene).isGrouped()) { outputGeometryList.add((Geometry)scene); } } diff --git a/jme3-core/src/main/java/com/jme3/system/AppSettings.java b/jme3-core/src/main/java/com/jme3/system/AppSettings.java index d371e00ef8..9eeb1118ce 100644 --- a/jme3-core/src/main/java/com/jme3/system/AppSettings.java +++ b/jme3-core/src/main/java/com/jme3/system/AppSettings.java @@ -57,7 +57,7 @@ public final class AppSettings extends HashMap { private static final long serialVersionUID = 1L; - + private static final AppSettings defaults = new AppSettings(false); /** @@ -92,7 +92,7 @@ public final class AppSettings extends HashMap { *

    * If the underlying system does not support OpenGL3.0, then the context * initialization will throw an exception. Note that currently jMonkeyEngine - * does not have any shaders that support OpenGL3.0 therefore this + * does not have any shaders that support OpenGL3.0 therefore this * option is not useful. *

    * @@ -237,7 +237,7 @@ public final class AppSettings extends HashMap { * @see AppSettings#setAudioRenderer(java.lang.String) */ public static final String ANDROID_OPENAL_SOFT = "OpenAL_SOFT"; - + /** * Use JogAmp's JOGL as the display system, with the OpenGL forward compatible profile *

    @@ -246,7 +246,7 @@ public final class AppSettings extends HashMap { * @see AppSettings#setRenderer(java.lang.String) */ public static final String JOGL_OPENGL_FORWARD_COMPATIBLE = "JOGL_OPENGL_FORWARD_COMPATIBLE"; - + /** * Use JogAmp's JOGL as the display system, with the backward compatible profile *

    @@ -255,7 +255,7 @@ public final class AppSettings extends HashMap { * @see AppSettings#setRenderer(java.lang.String) */ public static final String JOGL_OPENGL_BACKWARD_COMPATIBLE = "JOGL_OPENGL_BACKWARD_COMPATIBLE"; - + /** * Use JogAmp's JOAL as the audio renderer. *

    @@ -333,7 +333,7 @@ public void copyFrom(AppSettings other) { */ public void mergeFrom(AppSettings other) { for (String key : other.keySet()) { - if( !this.containsKey(key) ) { + if (!this.containsKey(key)) { put(key, other.get(key)); } } @@ -499,7 +499,7 @@ public void save(String preferencesKey) throws BackingStoreException { *

    * If the key is not set, then 0 is returned. * - * @param key the key of an integer setting + * @param key the key of an integer setting * @return the corresponding value, or 0 if not set */ public int getInteger(String key) { @@ -511,12 +511,12 @@ public int getInteger(String key) { return i.intValue(); } - /** + /** * Get a boolean from the settings. *

    * If the key is not set, then false is returned. * - * @param key the key of a boolean setting + * @param key the key of a boolean setting * @return the corresponding value, or false if not set */ public boolean getBoolean(String key) { @@ -533,7 +533,7 @@ public boolean getBoolean(String key) { *

    * If the key is not set, then null is returned. * - * @param key the key of a string setting + * @param key the key of a string setting * @return the corresponding value, or null if not set */ public String getString(String key) { @@ -550,7 +550,7 @@ public String getString(String key) { *

    * If the key is not set, then 0.0 is returned. * - * @param key the key of a float setting + * @param key the key of a float setting * @return the corresponding value, or 0 if not set */ public float getFloat(String key) { @@ -1081,7 +1081,7 @@ public int getStencilBits() { /** * Get the number of samples - * + * * @return the number of samples per pixel (for multisample anti-aliasing) * @see #setSamples(int) */ @@ -1180,32 +1180,32 @@ public boolean isGammaCorrection() { /** * Allows the display window to be resized by dragging its edges. - * - * Only supported for {@link JmeContext.Type#Display} contexts which - * are in windowed mode, ignored for other types. + * + * Only supported for {@link JmeContext.Type#Display} contexts which + * are in windowed mode, ignored for other types. * The default value is false. - * + * * @param resizable True to make a resizable window, false to make a fixed * size window. */ public void setResizable(boolean resizable) { putBoolean("Resizable", resizable); } - + /** * Determine if the display window can be resized by dragging its edges. - * + * * @return True if the window is resizable, false if it is fixed size. - * - * @see #setResizable(boolean) + * + * @see #setResizable(boolean) */ public boolean isResizable() { return getBoolean("Resizable"); } - + /** * When enabled the display context will swap buffers every frame. - * + * * This may need to be disabled when integrating with an external * library that handles buffer swapping on its own, e.g. Oculus Rift. * When disabled, the engine will process window messages @@ -1213,19 +1213,19 @@ public boolean isResizable() { * will cause 100% CPU usage normally as there's no VSync or any framerate * caps (unless set via {@link #setFrameRate(int) }). * The default is true. - * + * * @param swapBuffers True to enable buffer swapping, false to disable it. */ public void setSwapBuffers(boolean swapBuffers) { putBoolean("SwapBuffers", swapBuffers); } - + /** * Determine if the display context will swap buffers every frame. - * + * * @return True if buffer swapping is enabled, false otherwise. - * - * @see #setSwapBuffers(boolean) + * + * @see #setSwapBuffers(boolean) */ public boolean isSwapBuffers() { return getBoolean("SwapBuffers"); @@ -1243,19 +1243,19 @@ public void setOpenCLSupport(boolean support) { public boolean isOpenCLSupport() { return getBoolean("OpenCL"); } - + /** * Sets a custom platform chooser. This chooser specifies which platform and * which devices are used for the OpenCL context. - * + * * Default: an implementation defined one. - * + * * @param chooser the class of the chooser, must have a default constructor */ public void setOpenCLPlatformChooser(Class chooser) { putString("OpenCLPlatformChooser", chooser.getName()); } - + public String getOpenCLPlatformChooser() { return getString("OpenCLPlatformChooser"); } @@ -1353,7 +1353,7 @@ public boolean isUseRetinaFrameBuffer() { public void setUseRetinaFrameBuffer(boolean useRetinaFrameBuffer) { putBoolean("UseRetinaFrameBuffer", useRetinaFrameBuffer); } - + /** * Tests the state of the Center Window flag. * @@ -1367,7 +1367,7 @@ public void setUseRetinaFrameBuffer(boolean useRetinaFrameBuffer) { public boolean getCenterWindow() { return getBoolean("CenterWindow"); } - + /** * Enables or disables the Center Window flag. * diff --git a/jme3-core/src/main/java/com/jme3/texture/Texture.java b/jme3-core/src/main/java/com/jme3/texture/Texture.java index 82be52f296..00493860bb 100644 --- a/jme3-core/src/main/java/com/jme3/texture/Texture.java +++ b/jme3-core/src/main/java/com/jme3/texture/Texture.java @@ -64,7 +64,7 @@ public enum Type { * Two dimensional texture (default). A rectangle. */ TwoDimensional, - + /** * An array of two-dimensional textures. */ @@ -180,17 +180,17 @@ public enum WrapMode { * Only the fractional portion of the coordinate is considered. */ Repeat, - + /** * Only the fractional portion of the coordinate is considered, but if * the integer portion is odd, we'll use 1 - the fractional portion. * (Introduced around OpenGL1.4) Falls back on Repeat if not supported. */ MirroredRepeat, - + /** * coordinate will be clamped to [0,1] - * + * * @deprecated Not supported by OpenGL 3 */ @Deprecated @@ -203,19 +203,19 @@ public enum WrapMode { * is the size of the one-, two-, or three-dimensional texture image in * the direction of wrapping. (Introduced after OpenGL1.4) Falls back on * Clamp if not supported. - * + * * @deprecated Not supported by OpenGL 3 */ @Deprecated MirrorClamp, - + /** * coordinate will be clamped to the range [-1/(2N), 1 + 1/(2N)] where N * is the size of the texture in the direction of clamping. Falls back * on Clamp if not supported. - * + * * @deprecated Not supported by OpenGL 3 or OpenGL ES 2 - */ + */ @Deprecated BorderClamp, /** @@ -226,7 +226,7 @@ public enum WrapMode { * where N is the size of the one-, two-, or three-dimensional texture * image in the direction of wrapping. (Introduced after OpenGL1.4) * Falls back on BorderClamp if not supported. - * + * * @deprecated Not supported by OpenGL 3 */ @Deprecated @@ -237,7 +237,7 @@ public enum WrapMode { * on Clamp if not supported. */ EdgeClamp, - + /** * mirrors and clamps to edge the texture coordinate, where mirroring * and clamping to edge a value f computes: @@ -245,7 +245,7 @@ public enum WrapMode { * where N is the size of the one-, two-, or three-dimensional texture * image in the direction of wrapping. (Introduced after OpenGL1.4) * Falls back on EdgeClamp if not supported. - * + * * @deprecated Not supported by OpenGL 3 */ @Deprecated @@ -270,7 +270,7 @@ public enum WrapAxis { /** * If this texture is a depth texture (the format is Depth*) then * this value may be used to compare the texture depth to the R texture - * coordinate. + * coordinate. */ public enum ShadowCompareMode { /** @@ -279,7 +279,7 @@ public enum ShadowCompareMode { */ Off, - /** + /** * {@code * Compares the 3rd texture coordinate R to the value * in this depth texture. If R <= texture value then result is 1.0, @@ -416,7 +416,7 @@ public void setShadowCompareMode(ShadowCompareMode compareMode){ */ public void setImage(Image image) { this.image = image; - + // Test if mipmap generation required. setMinFilter(getMinFilter()); } @@ -491,7 +491,7 @@ public void setName(String name) { /** * @return the anisotropic filtering level for this texture. Default value - * is 0 (use value from config), + * is 0 (use value from config), * 1 means 1x (no anisotropy), 2 means x2, 4 is x4, etc. */ public int getAnisotropicFilter() { @@ -528,7 +528,7 @@ public boolean equals(Object obj) { return false; } final Texture other = (Texture) obj; - + // NOTE: Since images are generally considered unique assets in jME3, // using the image's equals() implementation is not necessary here // (would be too slow) @@ -569,7 +569,7 @@ public int hashCode() { * * @param rVal storage for the clone (not null, modified) * @return Texture - * + * * @deprecated Use {@link Texture#clone()} instead. */ @Deprecated @@ -595,14 +595,14 @@ public Texture createSimpleClone(Texture rVal) { public void write(JmeExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(name, "name", null); - + if (key == null){ // no texture key is set, try to save image instead then capsule.write(image, "image", null); }else{ capsule.write(key, "key", null); } - + capsule.write(anisotropicFilter, "anisotropicFilter", 1); capsule.write(minificationFilter, "minificationFilter", MinFilter.BilinearNoMipMaps); @@ -615,7 +615,7 @@ public void read(JmeImporter importer) throws IOException { InputCapsule capsule = importer.getCapsule(this); name = capsule.readString("name", null); key = (TextureKey) capsule.readSavable("key", null); - + // load texture from key, if available if (key != null) { // key is available, so try the texture from there. @@ -630,9 +630,10 @@ public void read(JmeImporter importer) throws IOException { // no key is set on the texture. Attempt to load an embedded image image = (Image) capsule.readSavable("image", null); if (image == null){ - // TODO: what to print out here? the texture has no key or data, there's no useful information .. + // TODO: what to print out here? the texture has no key or data, there's no useful information .. // assume texture.name is set even though the key is null - Logger.getLogger(Texture.class.getName()).log(Level.SEVERE, "Cannot load embedded image {0}", toString() ); + Logger.getLogger(Texture.class.getName()) + .log(Level.SEVERE, "Cannot load embedded image {0}", toString()); } } diff --git a/jme3-core/src/main/java/com/jme3/texture/TextureCubeMap.java b/jme3-core/src/main/java/com/jme3/texture/TextureCubeMap.java index b98e4908c0..40e6c037c3 100644 --- a/jme3-core/src/main/java/com/jme3/texture/TextureCubeMap.java +++ b/jme3-core/src/main/java/com/jme3/texture/TextureCubeMap.java @@ -70,23 +70,23 @@ public enum Face { PositiveX, NegativeX, PositiveY, NegativeY, PositiveZ, NegativeZ; } - public TextureCubeMap(){ + public TextureCubeMap() { super(); } - public TextureCubeMap(Image img){ + public TextureCubeMap(Image img) { super(); setImage(img); } - - public TextureCubeMap(int width, int height, Image.Format format){ + + public TextureCubeMap(int width, int height, Image.Format format) { this(createEmptyLayeredImage(width, height, 6, format)); } private static Image createEmptyLayeredImage(int width, int height, int layerCount, Image.Format format) { ArrayList layers = new ArrayList<>(); - for(int i = 0; i < layerCount; i++) { + for (int i = 0; i < layerCount; i++) { layers.add(null); } Image image = new Image(format, width, height, 0, layers, ColorSpace.Linear); @@ -105,11 +105,11 @@ public Texture createSimpleClone(Texture rVal) { rVal.setWrap(WrapAxis.R, wrapR); return super.createSimpleClone(rVal); } - + /** * setWrap sets the wrap mode of this texture for a * particular axis. - * + * * @param axis * the texture axis to apply the wrap mode to. * @param mode @@ -139,7 +139,7 @@ public void setWrap(WrapAxis axis, WrapMode mode) { /** * setWrap sets the wrap mode of this texture for all axis. - * + * * @param mode * the wrap mode for the given axis of the texture. * @throws IllegalArgumentException @@ -158,7 +158,7 @@ public void setWrap(WrapMode mode) { /** * getWrap returns the wrap mode for a given coordinate axis * on this texture. - * + * * @param axis * the axis to return for * @return the wrap mode of the texture. diff --git a/jme3-core/src/main/java/com/jme3/texture/image/BitMaskImageCodec.java b/jme3-core/src/main/java/com/jme3/texture/image/BitMaskImageCodec.java index 2de903d96c..a44ffe7cb9 100644 --- a/jme3-core/src/main/java/com/jme3/texture/image/BitMaskImageCodec.java +++ b/jme3-core/src/main/java/com/jme3/texture/image/BitMaskImageCodec.java @@ -34,11 +34,11 @@ import java.nio.ByteBuffer; class BitMaskImageCodec extends ImageCodec { - + // Shifts final int as, rs, gs, bs; boolean be = false; - + public BitMaskImageCodec(int bpp, int flags, int ac, int rc, int gc, int bc, int as, int rs, int gs, int bs) { super(bpp, flags, (int) (((long) 1 << ac) - 1), @@ -49,13 +49,13 @@ public BitMaskImageCodec(int bpp, int flags, int ac, int rc, int gc, int bc, int if (bpp > 4) { throw new UnsupportedOperationException("Use ByteAlignedImageCodec for codecs with pixel sizes larger than 4 bytes"); } - + this.as = as; this.rs = rs; this.gs = gs; this.bs = bs; } - + private static int readPixelRaw(ByteBuffer buf, int idx, int bpp) { //idx += bpp; //int original = buf.get(--idx) & 0xff; @@ -71,7 +71,7 @@ private static int readPixelRaw(ByteBuffer buf, int idx, int bpp) { } return pixel; } - + private void writePixelRaw(ByteBuffer buf, int idx, int pixel, int bpp){ // buf.position(idx); // if (!be){ @@ -87,15 +87,16 @@ private void writePixelRaw(ByteBuffer buf, int idx, int pixel, int bpp){ // buf.put(idx + i, bt); // } // } - + buf.position(idx); for (int i = 0; i < bpp; i++) { - buf.put( (byte)((pixel >> (8 * i)) & 0xff) ); + buf.put((byte) ((pixel >> (8 * i)) & 0xff)); } } @Override - public void readComponents(ByteBuffer buf, int x, int y, int width, int offset, int[] components, byte[] tmp) { + public void readComponents(ByteBuffer buf, int x, int y, int width, int offset, + int[] components, byte[] tmp) { int inputPixel = readPixelRaw(buf, (x + y * width) * bpp + offset, bpp); components[0] = (inputPixel >> as) & maxAlpha; components[1] = (inputPixel >> rs) & maxRed; @@ -104,14 +105,15 @@ public void readComponents(ByteBuffer buf, int x, int y, int width, int offset, } @Override - public void writeComponents(ByteBuffer buf, int x, int y, int width, int offset, int[] components, byte[] tmp) { + public void writeComponents(ByteBuffer buf, int x, int y, int width, int offset, + int[] components, byte[] tmp) { // Shift components then mask them // Map all components into a single bitspace int outputPixel = ((components[0] & maxAlpha) << as) | ((components[1] & maxRed) << rs) | ((components[2] & maxGreen) << gs) | ((components[3] & maxBlue) << bs); - + // Find index in image where to write pixel. // Write the resultant bitspace into the pixel. writePixelRaw(buf, (x + y * width) * bpp + offset, outputPixel, bpp); diff --git a/jme3-core/src/main/java/com/jme3/texture/image/ByteAlignedImageCodec.java b/jme3-core/src/main/java/com/jme3/texture/image/ByteAlignedImageCodec.java index 970471e2d6..3b9d2f3dcf 100644 --- a/jme3-core/src/main/java/com/jme3/texture/image/ByteAlignedImageCodec.java +++ b/jme3-core/src/main/java/com/jme3/texture/image/ByteAlignedImageCodec.java @@ -34,17 +34,17 @@ import java.nio.ByteBuffer; class ByteAlignedImageCodec extends ImageCodec { - + private final int ap, az, rp, rz, gp, gz, bp, bz; boolean be; - + public ByteAlignedImageCodec(int bpp, int flags, int az, int rz, int gz, int bz, int ap, int rp, int gp, int bp) { // Cast to long to compute max values, since some components could be as high as 32 bits. - super(bpp, flags, - (int)(((long)1 << (az << 3)) - 1), - (int)(((long)1 << (rz << 3)) - 1), - (int)(((long)1 << (gz << 3)) - 1), - (int)(((long)1 << (bz << 3)) - 1)); + super(bpp, flags, + (int) (((long)1 << (az << 3)) - 1), + (int) (((long)1 << (rz << 3)) - 1), + (int) (((long)1 << (gz << 3)) - 1), + (int) (((long)1 << (bz << 3)) - 1)); this.ap = ap; this.az = az; @@ -56,12 +56,12 @@ public ByteAlignedImageCodec(int bpp, int flags, int az, int rz, int gz, int bz, this.bp = bp; this.bz = bz; } - + private static void readPixelRaw(ByteBuffer buf, int idx, int bpp, byte[] result) { buf.position(idx); buf.get(result, 0, bpp); } - + private static void writePixelRaw(ByteBuffer buf, int idx, byte[] pixel, int bpp) { // try { buf.position(idx); @@ -70,7 +70,7 @@ private static void writePixelRaw(ByteBuffer buf, int idx, byte[] pixel, int bpp // System.out.println("!"); // } } - + private static int readComponent(byte[] encoded, int position, int size) { // int component = encoded[position] & 0xff; // while ((--size) > 0){ @@ -84,7 +84,7 @@ private static int readComponent(byte[] encoded, int position, int size) { } return component; // position += size - 1; -// +// // while ((--size) >= 0) { // component = (component << 8) | (encoded[position--] & 0xff); // } @@ -94,7 +94,7 @@ private static int readComponent(byte[] encoded, int position, int size) { return 0; } } - + private void writeComponent(int component, int position, int size, byte[] result) { // if (!be) { // while ((--size) >= 0){ @@ -108,16 +108,17 @@ private void writeComponent(int component, int position, int size, byte[] result } // } } - + @Override - public void readComponents(ByteBuffer buf, int x, int y, int width, int offset, int[] components, byte[] tmp) { - readPixelRaw(buf, (x + y * width ) * bpp + offset, bpp, tmp); + public void readComponents(ByteBuffer buf, int x, int y, int width, int offset, + int[] components, byte[] tmp) { + readPixelRaw(buf, (x + y * width) * bpp + offset, bpp, tmp); components[0] = readComponent(tmp, ap, az); components[1] = readComponent(tmp, rp, rz); components[2] = readComponent(tmp, gp, gz); components[3] = readComponent(tmp, bp, bz); } - + @Override public void writeComponents(ByteBuffer buf, int x, int y, int width, int offset, int[] components, byte[] tmp) { writeComponent(components[0], ap, az, tmp); diff --git a/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java b/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java index 1d6c68e25f..58045ae672 100644 --- a/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java +++ b/jme3-core/src/main/java/com/jme3/texture/image/DefaultImageRaster.java @@ -37,7 +37,7 @@ import java.nio.ByteBuffer; public class DefaultImageRaster extends ImageRaster { - + private final int[] components = new int[4]; private ByteBuffer buffer; private final Image image; @@ -48,60 +48,60 @@ public class DefaultImageRaster extends ImageRaster { private final byte[] temp; private final boolean convertToLinear; private int slice; - + private void rangeCheck(int x, int y) { if (x < 0 || y < 0 || x >= width || y >= height) { - throw new IllegalArgumentException("x and y must be inside the image dimensions:" + throw new IllegalArgumentException("x and y must be inside the image dimensions:" + x + ", " + y + " in:" + width + ", " + height); } } - + public DefaultImageRaster(Image image, int slice, int mipMapLevel, boolean convertToLinear) { int[] mipMapSizes = image.getMipMapSizes(); int availableMips = mipMapSizes != null ? mipMapSizes.length : 1; - + if (mipMapLevel >= availableMips) { throw new IllegalStateException("Cannot create image raster for mipmap level #" + mipMapLevel + ". " + "Image only has " + availableMips + " mipmap levels."); } - + if (image.hasMipmaps()) { this.width = Math.max(1, image.getWidth() >> mipMapLevel); this.height = Math.max(1, image.getHeight() >> mipMapLevel); - + int mipOffset = 0; for (int i = 0; i < mipMapLevel; i++) { mipOffset += mipMapSizes[i]; } - + this.offset = mipOffset; } else { this.width = image.getWidth(); this.height = image.getHeight(); this.offset = 0; } - + this.image = image; this.slice = slice; - + // Conversion to linear only needed if image's color space is sRGB. this.convertToLinear = convertToLinear && image.getColorSpace() == ColorSpace.sRGB; - + this.buffer = image.getData(slice); this.codec = ImageCodec.lookup(image.getFormat()); - + if (codec instanceof ByteAlignedImageCodec || codec instanceof ByteOffsetImageCodec) { this.temp = new byte[codec.bpp]; } else { this.temp = null; } } - + public void setSlice(int slice) { this.slice = slice; this.buffer = image.getData(slice); } - + @Override public int getWidth() { return width; @@ -115,13 +115,13 @@ public int getHeight() { @Override public void setPixel(int x, int y, ColorRGBA color) { rangeCheck(x, y); - + if (convertToLinear) { // Input is linear, needs to be converted to sRGB before writing // into image. color = color.getAsSrgb(); } - + // Check flags for grayscale if (codec.isGray) { float gray = color.r * 0.27f + color.g * 0.67f + color.b * 0.06f; @@ -148,22 +148,22 @@ public void setPixel(int x, int y, ColorRGBA color) { components[2] = Math.min( (int) (color.g * codec.maxGreen + 0.5f), codec.maxGreen); components[3] = Math.min( (int) (color.b * codec.maxBlue + 0.5f), codec.maxBlue); break; - } + } codec.writeComponents(getBuffer(), x, y, width, offset, components, temp); image.setUpdateNeeded(); } - + private ByteBuffer getBuffer(){ if(buffer == null){ this.buffer = image.getData(slice); } return buffer; } - + @Override public ColorRGBA getPixel(int x, int y, ColorRGBA store) { rangeCheck(x, y); - + codec.readComponents(getBuffer(), x, y, width, offset, components, temp); if (store == null) { store = new ColorRGBA(); @@ -183,10 +183,10 @@ public ColorRGBA getPixel(int x, int y, ColorRGBA store) { break; case 0: // Convert to float and divide by bitsize to get into range 0.0 - 1.0. - store.set((float)components[1] / codec.maxRed, - (float)components[2] / codec.maxGreen, - (float)components[3] / codec.maxBlue, - (float)components[0] / codec.maxAlpha); + store.set((float) components[1] / codec.maxRed, + (float) components[2] / codec.maxGreen, + (float) components[3] / codec.maxBlue, + (float) components[0] / codec.maxAlpha); break; } if (codec.isGray) { @@ -205,12 +205,12 @@ public ColorRGBA getPixel(int x, int y, ColorRGBA store) { store.a = 1; } } - + if (convertToLinear) { // Input image is sRGB, need to convert to linear. store.setAsSrgb(store.r, store.g, store.b, store.a); } - + return store; } } diff --git a/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java b/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java index 57c5589ad5..1a75203225 100644 --- a/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java +++ b/jme3-core/src/main/java/com/jme3/texture/image/ImageRaster.java @@ -37,12 +37,12 @@ /** * Utility class for reading and writing from jME3 {@link Image images}. *
    - * Allows directly manipulating pixels of the image by writing and + * Allows directly manipulating pixels of the image by writing and * reading {@link ColorRGBA colors} at any coordinate, without * regard to the underlying {@link com.jme3.texture.Image.Format format} of the image. * NOTE: compressed and depth formats are not supported. * Special RGB formats like RGB111110F and RGB9E5 are not supported - * at the moment, but may be added later on. For now + * at the moment, but may be added later on. For now * use RGB16F_to_RGB111110F and RGB16F_to_RGB9E5 to handle * the conversion on the GPU. *

    @@ -51,15 +51,15 @@ * all current instances of ImageReadWrite become invalid, and * new instances must be created in order to properly access * the image data. - * + * * Usage example:
    * * Image myImage = ... * ImageRaster raster = ImageRaster.create(myImage); * raster.setPixel(1, 5, ColorRGBA.Green); - * System.out.println( raster.getPixel(1, 5) ); // Will print [0.0, 1.0, 0.0, 1.0]. + * System.out.println(raster.getPixel(1, 5)); // Will print [0.0, 1.0, 0.0, 1.0]. * - * + * * @author Kirill Vainer */ public abstract class ImageRaster { @@ -70,8 +70,8 @@ public abstract class ImageRaster { * @param image The image to read / write to. * @param slice Which slice to use. Only applies to 3D images, 2D image * arrays or cubemaps. - * @param mipMapLevel The mipmap level to read / write to. To access levels - * other than 0, the image must have + * @param mipMapLevel The mipmap level to read / write to. To access levels + * other than 0, the image must have * {@link Image#setMipMapSizes(int[]) mipmap sizes} set. * @param convertToLinear If true, the application expects read or written * colors to be in linear color space (ImageRaster will @@ -82,7 +82,7 @@ public abstract class ImageRaster { public static ImageRaster create(Image image, int slice, int mipMapLevel, boolean convertToLinear) { return new DefaultImageRaster(image, slice, mipMapLevel, convertToLinear); } - + /** * Create new image reader / writer. * @@ -94,10 +94,10 @@ public static ImageRaster create(Image image, int slice, int mipMapLevel, boolea public static ImageRaster create(Image image, int slice) { return create(image, slice, 0, false); } - + /** * Create new image reader / writer for 2D images. - * + * * @param image The image to read / write to. * @return An ImageRaster to read / write to the image. */ @@ -107,30 +107,30 @@ public static ImageRaster create(Image image) { } return create(image, 0, 0, false); } - + public ImageRaster() { } - + /** * Returns the pixel width of the underlying image. - * + * * @return the pixel width of the underlying image. */ public abstract int getWidth(); - + /** * Returns the pixel height of the underlying image. - * + * * @return the pixel height of the underlying image. */ public abstract int getHeight(); - + /** * Sets the pixel at the given coordinate to the given color. *

    - * For all integer based formats (those not ending in "F"), the + * For all integer based formats (those not ending in "F"), the * color is first clamped to 0.0 - 1.0 before converting it to - * an integer to avoid overflow. For floating point based formats, + * an integer to avoid overflow. For floating point based formats, * components larger than 1.0 can be represented, but components * lower than 0.0 are still not allowed (as all formats are unsigned). *

    @@ -146,14 +146,14 @@ public ImageRaster() { * After writing the color, the image shall be marked as requiring an * update. The next time it is used for rendering, all pixel changes * will be reflected when the image is rendered. - * + * * @param x The x coordinate, from 0 to width - 1. * @param y The y coordinate, from 0 to height - 1. - * @param color The color to write. + * @param color The color to write. * @throws IllegalArgumentException If x or y are outside the image dimensions. */ public abstract void setPixel(int x, int y, ColorRGBA color); - + /** * Retrieve the color at the given coordinate. *

    @@ -164,7 +164,7 @@ public ImageRaster() { * the A component set to the alpha in the image. *

    * For grayscale or luminance formats, the luminance value is replicated - * in the R, G, and B components. + * in the R, G, and B components. *

    * Integer formats are converted to the range 0.0 - 1.0, based * on the maximum possible integer value that can be represented @@ -173,31 +173,31 @@ public ImageRaster() { * contain the integer values 0 - 31, a conversion to floating point * is done by diving the integer value by 31 (done with floating point * precision). - * + * * @param x The x coordinate, from 0 to width - 1. * @param y The y coordinate, from 0 to height - 1. - * @param store Storage location for the read color, if null, + * @param store Storage location for the read color, if null, * then a new ColorRGBA is created and returned with the read color. * @return The store parameter, if it is null, then a new ColorRGBA * with the read color. * @throws IllegalArgumentException If x or y are outside the image dimensions. */ public abstract ColorRGBA getPixel(int x, int y, ColorRGBA store); - + /** * Retrieve the color at the given coordinate. *

    * Convenience method that does not take a store argument. Equivalent - * to calling getPixel(x, y, null). + * to calling getPixel(x, y, null). * See {@link #getPixel(int, int, com.jme3.math.ColorRGBA) } for * more information. - * + * * @param x The x coordinate, from 0 to width - 1. * @param y The y coordinate, from 0 to height - 1. * @return A new ColorRGBA with the read color. * @throws IllegalArgumentException If x or y are outside the image dimensions */ - public ColorRGBA getPixel(int x, int y) { + public ColorRGBA getPixel(int x, int y) { return getPixel(x, y, null); } } diff --git a/jme3-core/src/main/java/com/jme3/util/IntMap.java b/jme3-core/src/main/java/com/jme3/util/IntMap.java index 900d2d08a4..198b380dd8 100644 --- a/jme3-core/src/main/java/com/jme3/util/IntMap.java +++ b/jme3-core/src/main/java/com/jme3/util/IntMap.java @@ -82,7 +82,7 @@ public IntMap(int initialCapacity, float loadFactor) { @Override @SuppressWarnings("unchecked") public IntMap clone(){ - try{ + try { IntMap clone = (IntMap) super.clone(); Entry[] newTable = new Entry[table.length]; for (int i = table.length - 1; i >= 0; i--){ @@ -91,7 +91,7 @@ public IntMap clone(){ } clone.table = newTable; return clone; - }catch (CloneNotSupportedException ex){ + } catch (CloneNotSupportedException ex){ } return null; } @@ -112,7 +112,7 @@ public Object jmeClone() { * Called internally by com.jme3.util.clone.Cloner. Do not call directly. */ @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.table = cloner.clone(table); } @@ -217,7 +217,7 @@ public int size() { public void clear() { Entry[] table = this.table; - for (int index = table.length; --index >= 0;){ + for (int index = table.length; --index >= 0;) { table[index] = null; } size = 0; @@ -267,7 +267,7 @@ public Entry next() { if (el >= size) throw new NoSuchElementException("No more elements!"); - if (cur != null){ + if (cur != null) { Entry e = cur; cur = cur.next; el++; @@ -296,7 +296,6 @@ public Entry next() { @Override public void remove() { } - } public static final class Entry implements Cloneable, JmeCloneable { @@ -327,11 +326,11 @@ public String toString(){ @Override @SuppressWarnings("unchecked") public Entry clone(){ - try{ + try { Entry clone = (Entry) super.clone(); clone.next = next != null ? next.clone() : null; return clone; - }catch (CloneNotSupportedException ex){ + } catch (CloneNotSupportedException ex) { } return null; } @@ -346,7 +345,7 @@ public Object jmeClone() { } @Override - public void cloneFields( Cloner cloner, Object original ) { + public void cloneFields(Cloner cloner, Object original) { this.value = cloner.clone(value); this.next = cloner.clone(next); } diff --git a/jme3-core/src/main/java/com/jme3/util/JmeFormatter.java b/jme3-core/src/main/java/com/jme3/util/JmeFormatter.java index aa77dea3f5..a582da4232 100644 --- a/jme3-core/src/main/java/com/jme3/util/JmeFormatter.java +++ b/jme3-core/src/main/java/com/jme3/util/JmeFormatter.java @@ -66,11 +66,11 @@ public String format(LogRecord record) { format.format(args, store, null); String clazz = null; - try{ + try { clazz = Class.forName(record.getSourceClassName()).getSimpleName(); - } catch (ClassNotFoundException ex){ + } catch (ClassNotFoundException ex) { } - + sb.append(record.getLevel().getLocalizedName()).append(" "); sb.append(clazz).append(" "); sb.append(store.toString()).append(" "); diff --git a/jme3-core/src/main/java/com/jme3/util/MipMapGenerator.java b/jme3-core/src/main/java/com/jme3/util/MipMapGenerator.java index 4a2c9be3b2..7073dfab52 100644 --- a/jme3-core/src/main/java/com/jme3/util/MipMapGenerator.java +++ b/jme3-core/src/main/java/com/jme3/util/MipMapGenerator.java @@ -43,35 +43,35 @@ public class MipMapGenerator { private MipMapGenerator() { } - + public static Image scaleImage(Image inputImage, int outputWidth, int outputHeight) { int size = outputWidth * outputHeight * inputImage.getFormat().getBitsPerPixel() / 8; ByteBuffer buffer = BufferUtils.createByteBuffer(size); - Image outputImage = new Image(inputImage.getFormat(), - outputWidth, - outputHeight, - buffer, + Image outputImage = new Image(inputImage.getFormat(), + outputWidth, + outputHeight, + buffer, inputImage.getColorSpace()); - + ImageRaster input = ImageRaster.create(inputImage, 0, 0, false); ImageRaster output = ImageRaster.create(outputImage, 0, 0, false); - - float xRatio = ((float)(input.getWidth() - 1)) / output.getWidth(); - float yRatio = ((float)(input.getHeight() - 1)) / output.getHeight(); + + float xRatio = ((float) (input.getWidth() - 1)) / output.getWidth(); + float yRatio = ((float) (input.getHeight() - 1)) / output.getHeight(); ColorRGBA outputColor = new ColorRGBA(0, 0, 0, 0); ColorRGBA bottomLeft = new ColorRGBA(); ColorRGBA bottomRight = new ColorRGBA(); ColorRGBA topLeft = new ColorRGBA(); ColorRGBA topRight = new ColorRGBA(); - + for (int y = 0; y < outputHeight; y++) { for (int x = 0; x < outputWidth; x++) { float x2f = x * xRatio; float y2f = y * yRatio; - - int x2 = (int)x2f; - int y2 = (int)y2f; + + int x2 = (int) x2f; + int y2 = (int) y2f; input.getPixel(x2, y2, bottomLeft); input.getPixel(x2 + 1, y2, bottomRight); @@ -92,7 +92,7 @@ public static Image resizeToPowerOf2(Image original){ int potHeight = FastMath.nearestPowerOfTwo(original.getHeight()); return scaleImage(original, potWidth, potHeight); } - + public static void generateMipMaps(Image image){ int width = image.getWidth(); int height = image.getHeight(); @@ -100,7 +100,7 @@ public static void generateMipMaps(Image image){ Image current = image; ArrayList output = new ArrayList<>(); int totalSize = 0; - + while (height >= 1 || width >= 1){ output.add(current.getData(0)); totalSize += current.getData(0).capacity(); diff --git a/jme3-core/src/main/java/com/jme3/util/SafeArrayList.java b/jme3-core/src/main/java/com/jme3/util/SafeArrayList.java index 22bffba3aa..3bf9381526 100644 --- a/jme3-core/src/main/java/com/jme3/util/SafeArrayList.java +++ b/jme3-core/src/main/java/com/jme3/util/SafeArrayList.java @@ -110,15 +110,15 @@ public SafeArrayList clone() { SafeArrayList clone = (SafeArrayList)super.clone(); // Clone whichever backing store is currently active - if( backingArray != null ) { + if (backingArray != null) { clone.backingArray = backingArray.clone(); } - if( buffer != null ) { + if (buffer != null) { clone.buffer = (List)((ArrayList)buffer).clone(); } return clone; - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new AssertionError(); } } @@ -141,32 +141,32 @@ protected final E[] createArray(int size) { * @return either the pre-existing array or a new one */ public final E[] getArray() { - if( backingArray != null ) + if (backingArray != null) return backingArray; - if( buffer == null ) { + if (buffer == null) { backingArray = createArray(0); } else { // Only keep the array or the buffer but never both at // the same time. 1) it saves space, 2) it keeps the rest // of the code safer. - backingArray = buffer.toArray( createArray(buffer.size()) ); + backingArray = buffer.toArray(createArray(buffer.size())); buffer = null; } return backingArray; } protected final List getBuffer() { - if( buffer != null ) + if (buffer != null) return buffer; - if( backingArray == null ) { + if (backingArray == null) { buffer = new ArrayList<>(); } else { // Only keep the array or the buffer but never both at // the same time. 1) it saves space, 2) it keeps the rest // of the code safer. - buffer = new ArrayList<>( Arrays.asList(backingArray) ); + buffer = new ArrayList<>(Arrays.asList(backingArray)); backingArray = null; } return buffer; @@ -206,7 +206,7 @@ public T[] toArray(T[] a) { return (T[])Arrays.copyOf(array, array.length, a.getClass()); } - System.arraycopy( array, 0, a, 0, array.length ); + System.arraycopy(array, 0, a, 0, array.length); if (a.length > array.length) { a[array.length] = null; @@ -286,12 +286,12 @@ public boolean equals(Object o) { List other = (List)o; Iterator i1 = iterator(); Iterator i2 = other.iterator(); - while( i1.hasNext() && i2.hasNext() ) { + while (i1.hasNext() && i2.hasNext()) { Object o1 = i1.next(); Object o2 = i2.next(); - if( o1 == o2 ) + if (o1 == o2) continue; - if( o1 == null || !o1.equals(o2) ) + if (o1 == null || !o1.equals(o2)) return false; } return !(i1.hasNext() || i2.hasNext()); @@ -302,7 +302,7 @@ public int hashCode() { // Exactly the hash code described in the List interface, basically E[] array = getArray(); int result = 1; - for( E e : array ) { + for (E e : array) { result = 31 * result + (e == null ? 0 : e.hashCode()); } return result; @@ -310,11 +310,11 @@ public int hashCode() { @Override public final E get(int index) { - if( backingArray != null ) + if (backingArray != null) return backingArray[index]; - if( buffer != null ) + if (buffer != null) return buffer.get(index); - throw new IndexOutOfBoundsException( "Index:" + index + ", Size:0" ); + throw new IndexOutOfBoundsException("Index:" + index + ", Size:0"); } @Override @@ -338,12 +338,12 @@ public E remove(int index) { @Override public int indexOf(Object o) { E[] array = getArray(); - for( int i = 0; i < array.length; i++ ) { + for (int i = 0; i < array.length; i++) { E element = array[i]; - if( element == o ) { + if (element == o) { return i; } - if( element != null && element.equals(o) ) { + if (element != null && element.equals(o)) { return i; } } @@ -353,12 +353,12 @@ public int indexOf(Object o) { @Override public int lastIndexOf(Object o) { E[] array = getArray(); - for( int i = array.length - 1; i >= 0; i-- ) { + for (int i = array.length - 1; i >= 0; i--) { E element = array[i]; - if( element == o ) { + if (element == o) { return i; } - if( element != null && element.equals(o) ) { + if (element != null && element.equals(o)) { return i; } } @@ -377,7 +377,6 @@ public ListIterator listIterator(int index) { @Override public List subList(int fromIndex, int toIndex) { - // So far, JME doesn't use subList that I can see, so I'm nerfing it. List raw = Arrays.asList(getArray()).subList(fromIndex, toIndex); return Collections.unmodifiableList(raw); @@ -385,19 +384,18 @@ public List subList(int fromIndex, int toIndex) { @Override public String toString() { - E[] array = getArray(); - if( array.length == 0 ) { + if (array.length == 0) { return "[]"; } StringBuilder sb = new StringBuilder(); sb.append('['); - for( int i = 0; i < array.length; i++ ) { - if( i > 0 ) - sb.append( ", " ); + for (int i = 0; i < array.length; i++) { + if (i > 0) + sb.append(", "); E e = array[i]; - sb.append( e == this ? "(this Collection)" : e ); + sb.append(e == this ? "(this Collection)" : e); } sb.append(']'); return sb.toString(); @@ -408,7 +406,7 @@ protected class ArrayIterator implements ListIterator { private int next; private int lastReturned; - protected ArrayIterator( E[] array, int index ) { + protected ArrayIterator(E[] array, int index) { this.array = array; this.next = index; this.lastReturned = -1; @@ -421,7 +419,7 @@ public boolean hasNext() { @Override public E next() { - if( !hasNext() ) + if (!hasNext()) throw new NoSuchElementException(); lastReturned = next++; return array[lastReturned]; @@ -434,7 +432,7 @@ public boolean hasPrevious() { @Override public E previous() { - if( !hasPrevious() ) + if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = --next; return array[lastReturned]; @@ -459,7 +457,7 @@ public void remove() { // correct. If the list had earlier .equals() equivalent // elements then we'll remove one of those instead. Either // way, none of those changes are reflected in this iterator. - SafeArrayList.this.remove( array[lastReturned] ); + SafeArrayList.this.remove(array[lastReturned]); } @Override diff --git a/jme3-core/src/main/java/com/jme3/util/SortUtil.java b/jme3-core/src/main/java/com/jme3/util/SortUtil.java index 3834ebf60e..39c8d71729 100644 --- a/jme3-core/src/main/java/com/jme3/util/SortUtil.java +++ b/jme3-core/src/main/java/com/jme3/util/SortUtil.java @@ -45,9 +45,9 @@ public static void gsort(Object[] a, Comparator comp) { int pos = 1; int last = 0; int length = a.length; - + while (pos < length){ - if ( comp.compare(a[pos], a[pos-1]) >= 0 ){ + if (comp.compare(a[pos], a[pos-1]) >= 0){ if (last != 0){ pos = last; last = 0; @@ -57,18 +57,18 @@ public static void gsort(Object[] a, Comparator comp) { Object tmp = a[pos]; a[pos] = a[pos-1]; a[pos-1] = tmp; - + if (pos > 1){ if (last == 0){ last = pos; } pos --; - }else{ + } else { pos ++; } } } - + // int p = 0; // int l = a.length; // while (p < l) { @@ -86,7 +86,7 @@ public static void gsort(Object[] a, Comparator comp) { private static void test(Float[] original, Float[] sorted, Comparator ic) { long time, dt; - + time = System.nanoTime(); for (int i = 0; i < 1000000; i++) { System.arraycopy(original, 0, sorted, 0, original.length); @@ -140,7 +140,7 @@ public int compare(Float o1, Float o2) { /** * Quick sorts the supplied array using the specified comparator. - * + * * @param a the array to sort (not null, modified) * @param comp the Comparator to use (not null) */ @@ -271,7 +271,7 @@ public static void qsort(int[] a, int lo0, int hi0, Comparator comp) { qsort(a, hi + 1, hi0, comp); } } - + /** * Merge sort * @@ -282,10 +282,10 @@ public static void qsort(int[] a, int lo0, int hi0, Comparator comp) { public static void msort(Object[] src, Object[] dest, Comparator comp){ msort(src, dest, 0, src.length - 1, comp); } - + /** * Merge sort - * + * * @param src Source array * @param dest Destination array * @param low Index of beginning element @@ -301,7 +301,7 @@ public static void msort(Object[] src, Object[] dest, int low, int high, merge(src, dest, low, center + 1, high, comp); } } - + @SuppressWarnings("unchecked") private static void merge(Object[] src, Object[] dest, int low, int middle, int high, Comparator comp) { diff --git a/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java b/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java index c4ce15e69a..6afc55cdf3 100644 --- a/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java +++ b/jme3-core/src/main/java/com/jme3/util/blockparser/BlockLanguageParser.java @@ -39,73 +39,73 @@ import java.util.List; public class BlockLanguageParser { - + private Reader reader; final private ArrayList statementStack = new ArrayList<>(); private Statement lastStatement; private int lineNumber = 1; - + private BlockLanguageParser(){ } - + private void reset(){ statementStack.clear(); statementStack.add(new Statement(0, "")); lastStatement = null; lineNumber = 1; } - - private void pushStatement(StringBuilder buffer){ + + private void pushStatement(StringBuilder buffer) { String content = buffer.toString().trim(); if (content.length() > 0){ // push last statement onto the list lastStatement = new Statement(lineNumber, content); - Statement parent = statementStack.get(statementStack.size()-1); + Statement parent = statementStack.get(statementStack.size() - 1); parent.addStatement(lastStatement); buffer.setLength(0); } } - - private void load(InputStream in) throws IOException{ + + private void load(InputStream in) throws IOException { reset(); - + reader = new InputStreamReader(in, "UTF-8"); - + StringBuilder buffer = new StringBuilder(); boolean insideComment = false; char lastChar = '\0'; - + while (true){ int ci = reader.read(); char c = (char) ci; if (c == '\r'){ continue; } - if (insideComment && c == '\n'){ + if (insideComment && c == '\n') { insideComment = false; - }else if (c == '/' && lastChar == '/'){ - buffer.deleteCharAt(buffer.length()-1); + }else if (c == '/' && lastChar == '/') { + buffer.deleteCharAt(buffer.length() - 1); insideComment = true; pushStatement(buffer); lastChar = '\0'; lineNumber++; }else if (!insideComment){ - if (ci == -1 || c == '{' || c == '}' || c == '\n' || c == ';'){ + if (ci == -1 || c == '{' || c == '}' || c == '\n' || c == ';') { pushStatement(buffer); lastChar = '\0'; - if (c == '{'){ + if (c == '{') { // push last statement onto the stack statementStack.add(lastStatement); continue; - }else if (c == '}'){ + }else if (c == '}') { // pop statement from stack - statementStack.remove(statementStack.size()-1); + statementStack.remove(statementStack.size() - 1); continue; - }else if (c == '\n'){ + }else if (c == '\n') { lineNumber++; - }else if (ci == -1){ + }else if (ci == -1) { break; } }else{ @@ -115,7 +115,7 @@ private void load(InputStream in) throws IOException{ } } } - + public static List parse(InputStream in) throws IOException { BlockLanguageParser parser = new BlockLanguageParser(); parser.load(in); diff --git a/jme3-core/src/main/java/com/jme3/util/clone/CloneFunction.java b/jme3-core/src/main/java/com/jme3/util/clone/CloneFunction.java index 509267b45f..782b8e563b 100644 --- a/jme3-core/src/main/java/com/jme3/util/clone/CloneFunction.java +++ b/jme3-core/src/main/java/com/jme3/util/clone/CloneFunction.java @@ -51,7 +51,7 @@ public interface CloneFunction { * Performs a shallow clone of the specified object. This is similar * to the JmeCloneable.clone() method in semantics and is the first part * of a two part cloning process. Once the shallow clone is created, it - * is cached and CloneFunction.cloneFields() is called. In this way, + * is cached and CloneFunction.cloneFields() is called. In this way, * the CloneFunction interface can completely take over the JmeCloneable * style cloning for an object that doesn't otherwise implement that interface. * @@ -59,24 +59,23 @@ public interface CloneFunction { * @param original The original object that needs to be cloned. * @return a new instance */ - public T cloneObject( Cloner cloner, T original ); - - + public T cloneObject(Cloner cloner, T original); + + /** * Performs a deep clone of the specified clone's fields. This is similar * to the JmeCloneable.cloneFields() method in semantics and is the second part * of a two part cloning process. Once the shallow clone is created, it - * is cached and CloneFunction.cloneFields() is called. In this way, + * is cached and CloneFunction.cloneFields() is called. In this way, * the CloneFunction interface can completely take over the JmeCloneable * style cloning for an object that doesn't otherwise implement that interface. - * + * * @param cloner The cloner performing the cloning operation. * @param clone The clone previously returned from cloneObject(). * @param original The original object that was cloned. This is provided for - * the very special case where field cloning needs to refer to - * the original object. Mostly the necessary fields should already - * be on the clone. + * the very special case where field cloning needs to refer to + * the original object. Mostly the necessary fields should already + * be on the clone. */ - public void cloneFields( Cloner cloner, T clone, T original ); - + public void cloneFields(Cloner cloner, T clone, T original); } diff --git a/jme3-core/src/main/java/com/jme3/util/clone/Cloner.java b/jme3-core/src/main/java/com/jme3/util/clone/Cloner.java index bde1844dfc..5496fbb7bd 100644 --- a/jme3-core/src/main/java/com/jme3/util/clone/Cloner.java +++ b/jme3-core/src/main/java/com/jme3/util/clone/Cloner.java @@ -139,7 +139,7 @@ public Cloner() { * @param object the object to be cloned (may be null) * @return a new instance, or a cached value, or null */ - public static T deepClone( T object ) { + public static T deepClone(T object) { return new Cloner().clone(object); } @@ -164,7 +164,7 @@ public static T deepClone( T object ) { * @param object the object to be cloned (may be null) * @return a new instance, or a cached value, or null */ - public T clone( T object ) { + public T clone(T object) { return clone(object, true); } @@ -173,7 +173,7 @@ public T clone( T object ) { * isolating the 'bad' case into a method with suppressed warnings. */ @SuppressWarnings("unchecked") - private Class objectClass( T object ) { + private Class objectClass(T object) { // This should be 100% allowed without a cast but Java generics // is not that smart sometimes. // Wrapping it in a method at least isolates the warning suppression @@ -207,13 +207,13 @@ private Class objectClass( T object ) { * false→don't use * @return a new instance, or a cached value, or null */ - public T clone( T object, boolean useFunctions ) { + public T clone(T object, boolean useFunctions) { - if( object == null ) { + if (object == null) { return null; } - if( log.isLoggable(Level.FINER) ) { + if (log.isLoggable(Level.FINER)) { log.finer("cloning:" + object.getClass() + "@" + System.identityHashCode(object)); } @@ -221,8 +221,8 @@ public T clone( T object, boolean useFunctions ) { // Check the index to see if we already have it Object clone = index.get(object); - if( clone != null || index.containsKey(object) ) { - if( log.isLoggable(Level.FINER) ) { + if (clone != null || index.containsKey(object)) { + if (log.isLoggable(Level.FINER)) { log.finer("cloned:" + object.getClass() + "@" + System.identityHashCode(object) + " as cached:" + (clone == null ? "null" : (clone.getClass() + "@" + System.identityHashCode(clone)))); } @@ -231,7 +231,7 @@ public T clone( T object, boolean useFunctions ) { // See if there is a custom function... that trumps everything. CloneFunction f = getCloneFunction(type); - if( f != null ) { + if (f != null) { T result = f.cloneObject(this, object); // Store the object in the identity map so that any circular references @@ -241,8 +241,8 @@ public T clone( T object, boolean useFunctions ) { // Now call the function again to deep clone the fields f.cloneFields(this, result, object); - if( log.isLoggable(Level.FINER) ) { - if( result == null ) { + if (log.isLoggable(Level.FINER)) { + if (result == null) { log.finer("cloned:" + object.getClass() + "@" + System.identityHashCode(object) + " as transformed:null"); } else { @@ -253,12 +253,12 @@ public T clone( T object, boolean useFunctions ) { return result; } - if( object.getClass().isArray() ) { + if (object.getClass().isArray()) { // Perform an array clone clone = arrayClone(object); // Array clone already indexes the clone - } else if( object instanceof JmeCloneable ) { + } else if (object instanceof JmeCloneable) { // Use the two-step cloning semantics clone = ((JmeCloneable)object).jmeClone(); @@ -266,13 +266,13 @@ public T clone( T object, boolean useFunctions ) { // are resolvable index.put(object, clone); - ((JmeCloneable)clone).cloneFields(this, object); - } else if( object instanceof Cloneable ) { + ((JmeCloneable) clone).cloneFields(this, object); + } else if (object instanceof Cloneable) { // Perform a regular Java shallow clone try { clone = javaClone(object); - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new IllegalArgumentException("Object is not cloneable, type:" + type, e); } @@ -283,7 +283,7 @@ public T clone( T object, boolean useFunctions ) { throw new IllegalArgumentException("Object is not cloneable, type:" + type); } - if( log.isLoggable(Level.FINER) ) { + if(log.isLoggable(Level.FINER)) { log.finer("cloned:" + object.getClass() + "@" + System.identityHashCode(object) + " as " + clone.getClass() + "@" + System.identityHashCode(clone)); } @@ -303,8 +303,8 @@ public T clone( T object, boolean useFunctions ) { * @param function the function to set, or null to cancel any previous * setting */ - public void setCloneFunction( Class type, CloneFunction function ) { - if( function == null ) { + public void setCloneFunction(Class type, CloneFunction function) { + if (function == null) { functions.remove(type); } else { functions.put(type, function); @@ -320,17 +320,17 @@ public void setCloneFunction( Class type, CloneFunction function ) { * @return the registered function, or null if none */ @SuppressWarnings("unchecked") - public CloneFunction getCloneFunction( Class type ) { + public CloneFunction getCloneFunction(Class type) { CloneFunction result = functions.get(type); - if( result == null ) { + if (result == null) { // Do a more exhaustive search - for( Map.Entry e : functions.entrySet() ) { - if( e.getKey().isAssignableFrom(type) ) { + for (Map.Entry e : functions.entrySet()) { + if (e.getKey().isAssignableFrom(type)) { result = e.getValue(); break; } } - if( result != null ) { + if (result != null) { // Cache it for later functions.put(type, result); } @@ -344,12 +344,12 @@ public CloneFunction getCloneFunction( Class type ) { * This can be used to stub out specific values from being cloned or to * force global shared instances to be used even if the object is cloneable * normally. - * + * * @param the type of object to be detected and returned * @param original the instance to be detected (alias created) * @param clone the instance to be returned (alias created) */ - public void setClonedValue( T original, T clone ) { + public void setClonedValue(T original, T clone) { index.put(original, clone); } @@ -362,7 +362,7 @@ public void setClonedValue( T original, T clone ) { * @param o the object to be tested * @return true if the object has been cloned, otherwise false */ - public boolean isCloned( Object o ) { + public boolean isCloned(Object o) { return index.containsKey(o); } @@ -388,16 +388,16 @@ public void clearIndex() { * @return a new instance or null * @throws CloneNotSupportedException if the object has no public clone method */ - public T javaClone( T object ) throws CloneNotSupportedException { - if( object == null ) { + public T javaClone(T object) throws CloneNotSupportedException { + if (object == null) { return null; } Method m = methodCache.get(object.getClass()); - if( m == null ) { + if (m == null) { try { // Lookup the method and cache it m = object.getClass().getMethod("clone"); - } catch( NoSuchMethodException e ) { + } catch (NoSuchMethodException e) { throw new CloneNotSupportedException("No public clone method found for:" + object.getClass()); } methodCache.put(object.getClass(), m); @@ -408,7 +408,7 @@ public T javaClone( T object ) throws CloneNotSupportedException { try { Class type = objectClass(object); return type.cast(m.invoke(object)); - } catch( IllegalAccessException | InvocationTargetException e ) { + } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Error cloning object of type:" + object.getClass(), e); } } @@ -422,8 +422,7 @@ public T javaClone( T object ) throws CloneNotSupportedException { * @param object the array to be cloned * @return a new array */ - protected T arrayClone( T object ) { - + protected T arrayClone(T object) { // Java doesn't support the cloning of arrays through reflection unless // you open access to Object's protected clone array... which requires // elevated privileges. So we will do a work-around that is slightly less @@ -438,12 +437,12 @@ protected T arrayClone( T object ) { // Store the clone for later lookups index.put(object, clone); - if( elementType.isPrimitive() ) { + if (elementType.isPrimitive()) { // Then our job is a bit easier System.arraycopy(object, 0, clone, 0, size); } else { // Else it's an object array, so we'll clone it and its children. - for( int i = 0; i < size; i++ ) { + for (int i = 0; i < size; i++) { Object element = clone(Array.get(object, i)); Array.set(clone, i, element); } diff --git a/jme3-core/src/main/java/com/jme3/util/clone/IdentityCloneFunction.java b/jme3-core/src/main/java/com/jme3/util/clone/IdentityCloneFunction.java index a3d475388f..bdf376f8d3 100644 --- a/jme3-core/src/main/java/com/jme3/util/clone/IdentityCloneFunction.java +++ b/jme3-core/src/main/java/com/jme3/util/clone/IdentityCloneFunction.java @@ -47,14 +47,14 @@ public class IdentityCloneFunction implements CloneFunction { * Returns the object directly. */ @Override - public T cloneObject( Cloner cloner, T object ) { + public T cloneObject(Cloner cloner, T object) { return object; } - + /** * Does nothing. - */ + */ @Override - public void cloneFields( Cloner cloner, T clone, T object ) { + public void cloneFields(Cloner cloner, T clone, T object) { } } diff --git a/jme3-core/src/main/java/com/jme3/util/clone/JmeCloneable.java b/jme3-core/src/main/java/com/jme3/util/clone/JmeCloneable.java index f9521df7f6..1a9c22418d 100644 --- a/jme3-core/src/main/java/com/jme3/util/clone/JmeCloneable.java +++ b/jme3-core/src/main/java/com/jme3/util/clone/JmeCloneable.java @@ -40,8 +40,8 @@ * their local dependencies in a way that will be equivalent to the * original object graph. In other words, if two objects in the graph * share the same target reference then the cloned version will share - * the cloned reference. - * + * the cloned reference. + * *

    For example, if an object wishes to deep clone one of its fields * then it will call cloner.clone(object) instead of object.clone(). * The cloner will keep track of any clones already created for 'object' @@ -77,25 +77,25 @@ public interface JmeCloneable extends Cloneable { * * @return a new instance */ - public Object jmeClone(); + public Object jmeClone(); /** * Implemented to perform deep cloning for this object, resolving * local cloned references using the specified cloner. The object * can call cloner.clone(fieldValue) to deep clone any of its fields. - * + * *

    Note: during normal clone operations the original object * will not be needed as the clone has already had all of the fields * shallow copied.

    * - * @param cloner The cloner that is performing the cloning operation. The + * @param cloner The cloner that is performing the cloning operation. The * cloneFields method can call back into the cloner to make - * clones of its subordinate fields. + * clones of its subordinate fields. * @param original The original object from which this object was cloned. * This is provided for the very rare case that this object needs * to refer to its original for some reason. In general, all of * the relevant values should have been transferred during the * shallow clone, and this object need only clone what it wants. */ - public void cloneFields( Cloner cloner, Object original ); + public void cloneFields(Cloner cloner, Object original); } diff --git a/jme3-core/src/main/java/com/jme3/util/clone/ListCloneFunction.java b/jme3-core/src/main/java/com/jme3/util/clone/ListCloneFunction.java index b431729806..8c91b8d7b0 100644 --- a/jme3-core/src/main/java/com/jme3/util/clone/ListCloneFunction.java +++ b/jme3-core/src/main/java/com/jme3/util/clone/ListCloneFunction.java @@ -43,22 +43,22 @@ public class ListCloneFunction implements CloneFunction { @Override - public T cloneObject( Cloner cloner, T object ) { + public T cloneObject(Cloner cloner, T object) { try { - T clone = cloner.javaClone(object); + T clone = cloner.javaClone(object); return clone; - } catch( CloneNotSupportedException e ) { + } catch (CloneNotSupportedException e) { throw new IllegalArgumentException("Clone not supported for type:" + object.getClass(), e); } } - + /** * Clones the elements of the list. - */ + */ @SuppressWarnings("unchecked") @Override - public void cloneFields( Cloner cloner, T clone, T object ) { - for( int i = 0; i < clone.size(); i++ ) { + public void cloneFields(Cloner cloner, T clone, T object) { + for (int i = 0; i < clone.size(); i++) { // Need to clone the clones... because T might // have done something special in its clone method that // we will have to adhere to. For example, clone may have nulled diff --git a/jme3-core/src/main/java/com/jme3/util/xml/SAXUtil.java b/jme3-core/src/main/java/com/jme3/util/xml/SAXUtil.java index 76eeb008bf..c3c7bc0e88 100644 --- a/jme3-core/src/main/java/com/jme3/util/xml/SAXUtil.java +++ b/jme3-core/src/main/java/com/jme3/util/xml/SAXUtil.java @@ -50,65 +50,65 @@ private SAXUtil() { /** * Parses an integer from a string, if the string is null returns * def. - * + * * @param i The string to parse * @param def The default value if the string is null * @return the parsed value or def * @throws SAXException in case of a syntax error */ - public static int parseInt(String i, int def) throws SAXException{ + public static int parseInt(String i, int def) throws SAXException { if (i == null) return def; else{ try { return Integer.parseInt(i); } catch (NumberFormatException ex){ - throw new SAXException("Expected an integer, got '"+i+"'"); + throw new SAXException("Expected an integer, got '" + i + "'"); } } } - public static int parseInt(String i) throws SAXException{ + public static int parseInt(String i) throws SAXException { if (i == null) throw new SAXException("Expected an integer"); else{ try { return Integer.parseInt(i); } catch (NumberFormatException ex){ - throw new SAXException("Expected an integer, got '"+i+"'"); + throw new SAXException("Expected an integer, got '" + i + "'"); } } } - public static float parseFloat(String f, float def) throws SAXException{ + public static float parseFloat(String f, float def) throws SAXException { if (f == null) return def; else{ try { return Float.parseFloat(f); } catch (NumberFormatException ex){ - throw new SAXException("Expected a decimal, got '"+f+"'"); + throw new SAXException("Expected a decimal, got '" + f + "'"); } } } - public static float parseFloat(String f) throws SAXException{ + public static float parseFloat(String f) throws SAXException { if (f == null) throw new SAXException("Expected a decimal"); else{ try { return Float.parseFloat(f); } catch (NumberFormatException ex){ - throw new SAXException("Expected a decimal, got '"+f+"'"); + throw new SAXException("Expected a decimal, got '" + f + "'"); } } } - public static boolean parseBool(String bool, boolean def) throws SAXException{ + public static boolean parseBool(String bool, boolean def) throws SAXException { if (bool == null || bool.equals("")) return def; else - return Boolean.valueOf(bool); + return Boolean.valueOf(bool); //else // throw new SAXException("Expected a boolean, got'"+bool+"'"); } @@ -120,25 +120,24 @@ public static String parseString(String str, String def){ return str; } - public static String parseString(String str) throws SAXException{ + public static String parseString(String str) throws SAXException { if (str == null) throw new SAXException("Expected a string"); else return str; } - public static Vector3f parseVector3(Attributes attribs) throws SAXException{ + public static Vector3f parseVector3(Attributes attribs) throws SAXException { float x = parseFloat(attribs.getValue("x")); float y = parseFloat(attribs.getValue("y")); float z = parseFloat(attribs.getValue("z")); return new Vector3f(x,y,z); } - public static ColorRGBA parseColor(Attributes attribs) throws SAXException{ + public static ColorRGBA parseColor(Attributes attribs) throws SAXException { float r = parseFloat(attribs.getValue("r")); float g = parseFloat(attribs.getValue("g")); float b = parseFloat(attribs.getValue("b")); return new ColorRGBA(r, g, b, 1f); } - }