code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.anddev.andengine.entity.scene.background; import org.anddev.andengine.util.modifier.IModifier; import org.anddev.andengine.util.modifier.ModifierList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:08:17 - 19.07.2010 */ public abstract class BaseBackground implements IBackground { // =========================================================== // Constants // =========================================================== private static final int BACKGROUNDMODIFIERS_CAPACITY_DEFAULT = 4; // =========================================================== // Fields // =========================================================== private final ModifierList<IBackground> mBackgroundModifiers = new ModifierList<IBackground>(this, BACKGROUNDMODIFIERS_CAPACITY_DEFAULT); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void addBackgroundModifier(final IModifier<IBackground> pBackgroundModifier) { this.mBackgroundModifiers.add(pBackgroundModifier); } @Override public boolean removeBackgroundModifier(final IModifier<IBackground> pBackgroundModifier) { return this.mBackgroundModifiers.remove(pBackgroundModifier); } @Override public void clearBackgroundModifiers() { this.mBackgroundModifiers.clear(); } @Override public void onUpdate(final float pSecondsElapsed) { this.mBackgroundModifiers.onUpdate(pSecondsElapsed); } @Override public void reset() { this.mBackgroundModifiers.reset(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.scene.background; import static org.anddev.andengine.util.constants.ColorConstants.COLOR_FACTOR_INT_TO_FLOAT; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:45:24 - 19.07.2010 */ public class ColorBackground extends BaseBackground { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mRed = 0.0f; private float mGreen = 0.0f; private float mBlue = 0.0f; private float mAlpha = 1.0f; private boolean mColorEnabled = true; // =========================================================== // Constructors // =========================================================== protected ColorBackground() { } public ColorBackground(final float pRed, final float pGreen, final float pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; } public ColorBackground(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.mAlpha = pAlpha; } // =========================================================== // Getter & Setter // =========================================================== /** * Sets the color using the arithmetic scheme (0.0f - 1.0f RGB triple). * @param pRed The red color value. Should be between 0.0 and 1.0, inclusive. * @param pGreen The green color value. Should be between 0.0 and 1.0, inclusive. * @param pBlue The blue color value. Should be between 0.0 and 1.0, inclusive. */ @Override public void setColor(final float pRed, final float pGreen, final float pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; } /** * Sets the color using the arithmetic scheme (0.0f - 1.0f RGB quadruple). * @param pRed The red color value. Should be between 0.0 and 1.0, inclusive. * @param pGreen The green color value. Should be between 0.0 and 1.0, inclusive. * @param pBlue The blue color value. Should be between 0.0 and 1.0, inclusive. * @param pAlpha The alpha color value. Should be between 0.0 and 1.0, inclusive. */ @Override public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.setColor(pRed, pGreen, pBlue); this.mAlpha = pAlpha; } /** * Sets the color using the digital 8-bit per channel scheme (0 - 255 RGB triple). * @param pRed The red color value. Should be between 0 and 255, inclusive. * @param pGreen The green color value. Should be between 0 and 255, inclusive. * @param pBlue The blue color value. Should be between 0 and 255, inclusive. */ public void setColor(final int pRed, final int pGreen, final int pBlue) throws IllegalArgumentException { this.setColor(pRed / COLOR_FACTOR_INT_TO_FLOAT, pGreen / COLOR_FACTOR_INT_TO_FLOAT, pBlue / COLOR_FACTOR_INT_TO_FLOAT); } /** * Sets the color using the digital 8-bit per channel scheme (0 - 255 RGB quadruple). * @param pRed The red color value. Should be between 0 and 255, inclusive. * @param pGreen The green color value. Should be between 0 and 255, inclusive. * @param pBlue The blue color value. Should be between 0 and 255, inclusive. */ public void setColor(final int pRed, final int pGreen, final int pBlue, final int pAlpha) throws IllegalArgumentException { this.setColor(pRed / COLOR_FACTOR_INT_TO_FLOAT, pGreen / COLOR_FACTOR_INT_TO_FLOAT, pBlue / COLOR_FACTOR_INT_TO_FLOAT, pAlpha / COLOR_FACTOR_INT_TO_FLOAT); } public void setColorEnabled(final boolean pColorEnabled) { this.mColorEnabled = pColorEnabled; } public boolean isColorEnabled() { return this.mColorEnabled; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onDraw(final GL10 pGL, final Camera pCamera) { if(this.mColorEnabled) { pGL.glClearColor(this.mRed, this.mGreen, this.mBlue, this.mAlpha); pGL.glClear(GL10.GL_COLOR_BUFFER_BIT); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.scene.background.modifier; import org.anddev.andengine.entity.scene.background.IBackground; import org.anddev.andengine.util.modifier.LoopModifier; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:03:53 - 03.09.2010 */ public class LoopBackgroundModifier extends LoopModifier<IBackground> implements IBackgroundModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier) { super(pBackgroundModifier); } public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount) { super(pBackgroundModifier, pLoopCount); } public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final ILoopBackgroundModifierListener pLoopModifierListener) { super(pBackgroundModifier, pLoopCount, pLoopModifierListener, (IBackgroundModifierListener)null); } public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final IBackgroundModifierListener pBackgroundModifierListener) { super(pBackgroundModifier, pLoopCount, pBackgroundModifierListener); } public LoopBackgroundModifier(final IBackgroundModifier pBackgroundModifier, final int pLoopCount, final ILoopBackgroundModifierListener pLoopModifierListener, final IBackgroundModifierListener pBackgroundModifierListener) { super(pBackgroundModifier, pLoopCount, pLoopModifierListener, pBackgroundModifierListener); } protected LoopBackgroundModifier(final LoopBackgroundModifier pLoopBackgroundModifier) throws DeepCopyNotSupportedException { super(pLoopBackgroundModifier); } @Override public LoopBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { return new LoopBackgroundModifier(this); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public interface ILoopBackgroundModifierListener extends ILoopModifierListener<IBackground> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== } }
Java
package org.anddev.andengine.entity.scene.background.modifier; import org.anddev.andengine.entity.scene.background.IBackground; import org.anddev.andengine.util.modifier.BaseTripleValueSpanModifier; import org.anddev.andengine.util.modifier.ease.IEaseFunction; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:51:03 - 03.09.2010 */ public class ColorModifier extends BaseTripleValueSpanModifier<IBackground> implements IBackgroundModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue) { this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, IEaseFunction.DEFAULT); } public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IEaseFunction pEaseFunction) { this(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, null, pEaseFunction); } public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IBackgroundModifierListener pBackgroundModifierListener) { super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pBackgroundModifierListener, IEaseFunction.DEFAULT); } public ColorModifier(final float pDuration, final float pFromRed, final float pToRed, final float pFromGreen, final float pToGreen, final float pFromBlue, final float pToBlue, final IBackgroundModifierListener pBackgroundModifierListener, final IEaseFunction pEaseFunction) { super(pDuration, pFromRed, pToRed, pFromGreen, pToGreen, pFromBlue, pToBlue, pBackgroundModifierListener, pEaseFunction); } protected ColorModifier(final ColorModifier pColorModifier) { super(pColorModifier); } @Override public ColorModifier deepCopy(){ return new ColorModifier(this); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onSetInitialValues(final IBackground pBackground, final float pRed, final float pGreen, final float pBlue) { pBackground.setColor(pRed, pGreen, pBlue); } @Override protected void onSetValues(final IBackground pBackground, final float pPerctentageDone, final float pRed, final float pGreen, final float pBlue) { pBackground.setColor(pRed, pGreen, pBlue); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.scene.background.modifier; import org.anddev.andengine.entity.scene.background.IBackground; import org.anddev.andengine.util.modifier.ParallelModifier; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:03:57 - 03.09.2010 */ public class ParallelBackgroundModifier extends ParallelModifier<IBackground> implements IBackgroundModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ParallelBackgroundModifier(final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pBackgroundModifiers); } public ParallelBackgroundModifier(final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pBackgroundModifierListener, pBackgroundModifiers); } protected ParallelBackgroundModifier(final ParallelBackgroundModifier pParallelBackgroundModifier) throws DeepCopyNotSupportedException { super(pParallelBackgroundModifier); } @Override public ParallelBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { return new ParallelBackgroundModifier(this); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.scene.background.modifier; import org.anddev.andengine.entity.scene.background.IBackground; import org.anddev.andengine.util.modifier.SequenceModifier; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:04:02 - 03.09.2010 */ public class SequenceBackgroundModifier extends SequenceModifier<IBackground> implements IBackgroundModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SequenceBackgroundModifier(final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pBackgroundModifiers); } public SequenceBackgroundModifier(final ISubSequenceBackgroundModifierListener pSubSequenceBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pSubSequenceBackgroundModifierListener, pBackgroundModifiers); } public SequenceBackgroundModifier(final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pBackgroundModifierListener, pBackgroundModifiers); } public SequenceBackgroundModifier(final ISubSequenceBackgroundModifierListener pSubSequenceBackgroundModifierListener, final IBackgroundModifierListener pBackgroundModifierListener, final IBackgroundModifier... pBackgroundModifiers) throws IllegalArgumentException { super(pSubSequenceBackgroundModifierListener, pBackgroundModifierListener, pBackgroundModifiers); } protected SequenceBackgroundModifier(final SequenceBackgroundModifier pSequenceBackgroundModifier) throws DeepCopyNotSupportedException { super(pSequenceBackgroundModifier); } @Override public SequenceBackgroundModifier deepCopy() throws DeepCopyNotSupportedException { return new SequenceBackgroundModifier(this); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public interface ISubSequenceBackgroundModifierListener extends ISubSequenceModifierListener<IBackground> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== } }
Java
package org.anddev.andengine.entity.scene.background.modifier; import org.anddev.andengine.entity.scene.background.IBackground; import org.anddev.andengine.util.modifier.IModifier; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:55:54 - 03.09.2010 */ public interface IBackgroundModifier extends IModifier<IBackground> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== @Override public IBackgroundModifier deepCopy() throws DeepCopyNotSupportedException; // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IBackgroundModifierListener extends IModifierListener<IBackground>{ // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== } }
Java
package org.anddev.andengine.entity.scene.background; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.shape.Shape; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:36:26 - 19.07.2010 */ public class ParallaxBackground extends ColorBackground { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ArrayList<ParallaxEntity> mParallaxEntities = new ArrayList<ParallaxEntity>(); private int mParallaxEntityCount; protected float mParallaxValue; // =========================================================== // Constructors // =========================================================== public ParallaxBackground(final float pRed, final float pGreen, final float pBlue) { super(pRed, pGreen, pBlue); } // =========================================================== // Getter & Setter // =========================================================== public void setParallaxValue(final float pParallaxValue) { this.mParallaxValue = pParallaxValue; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onDraw(final GL10 pGL, final Camera pCamera) { super.onDraw(pGL, pCamera); final float parallaxValue = this.mParallaxValue; final ArrayList<ParallaxEntity> parallaxEntities = this.mParallaxEntities; for(int i = 0; i < this.mParallaxEntityCount; i++) { parallaxEntities.get(i).onDraw(pGL, parallaxValue, pCamera); } } // =========================================================== // Methods // =========================================================== public void attachParallaxEntity(final ParallaxEntity pParallaxEntity) { this.mParallaxEntities.add(pParallaxEntity); this.mParallaxEntityCount++; } public boolean detachParallaxEntity(final ParallaxEntity pParallaxEntity) { this.mParallaxEntityCount--; final boolean success = this.mParallaxEntities.remove(pParallaxEntity); if(!success) { this.mParallaxEntityCount++; } return success; } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class ParallaxEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== final float mParallaxFactor; final Shape mShape; // =========================================================== // Constructors // =========================================================== public ParallaxEntity(final float pParallaxFactor, final Shape pShape) { this.mParallaxFactor = pParallaxFactor; this.mShape = pShape; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void onDraw(final GL10 pGL, final float pParallaxValue, final Camera pCamera) { pGL.glPushMatrix(); { final float cameraWidth = pCamera.getWidth(); final float shapeWidthScaled = this.mShape.getWidthScaled(); float baseOffset = (pParallaxValue * this.mParallaxFactor) % shapeWidthScaled; while(baseOffset > 0) { baseOffset -= shapeWidthScaled; } pGL.glTranslatef(baseOffset, 0, 0); float currentMaxX = baseOffset; do { this.mShape.onDraw(pGL, pCamera); pGL.glTranslatef(shapeWidthScaled, 0, 0); currentMaxX += shapeWidthScaled; } while(currentMaxX < cameraWidth); } pGL.glPopMatrix(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.entity.scene.background; import org.anddev.andengine.entity.sprite.BaseSprite; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:01:43 - 19.07.2010 */ public class SpriteBackground extends EntityBackground { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SpriteBackground(final BaseSprite pBaseSprite) { super(pBaseSprite); } public SpriteBackground(final float pRed, final float pGreen, final float pBlue, final BaseSprite pBaseSprite) { super(pRed, pGreen, pBlue, pBaseSprite); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.scene.background; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:44:31 - 19.07.2010 */ public class AutoParallaxBackground extends ParallaxBackground { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mParallaxChangePerSecond; // =========================================================== // Constructors // =========================================================== public AutoParallaxBackground(final float pRed, final float pGreen, final float pBlue, final float pParallaxChangePerSecond) { super(pRed, pGreen, pBlue); this.mParallaxChangePerSecond = pParallaxChangePerSecond; } // =========================================================== // Getter & Setter // =========================================================== public void setParallaxChangePerSecond(final float pParallaxChangePerSecond) { this.mParallaxChangePerSecond = pParallaxChangePerSecond; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed); this.mParallaxValue += this.mParallaxChangePerSecond * pSecondsElapsed; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.scene; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.input.touch.TouchEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:35:53 - 29.03.2010 */ public class CameraScene extends Scene { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected Camera mCamera; // =========================================================== // Constructors // =========================================================== /** * {@link CameraScene#setCamera(Camera)} needs to be called manually. Otherwise nothing will be drawn. */ public CameraScene() { this(null); } public CameraScene(final Camera pCamera) { this.mCamera = pCamera; } // =========================================================== // Getter & Setter // =========================================================== public Camera getCamera() { return this.mCamera; } public void setCamera(final Camera pCamera) { this.mCamera = pCamera; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean onSceneTouchEvent(final TouchEvent pSceneTouchEvent) { if(this.mCamera == null) { return false; } else { this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); final boolean handled = super.onSceneTouchEvent(pSceneTouchEvent); if(handled) { return true; } else { this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); return false; } } } @Override protected boolean onChildSceneTouchEvent(final TouchEvent pSceneTouchEvent) { final boolean childIsCameraScene = this.mChildScene instanceof CameraScene; if(childIsCameraScene) { this.mCamera.convertCameraSceneToSceneTouchEvent(pSceneTouchEvent); final boolean result = super.onChildSceneTouchEvent(pSceneTouchEvent); this.mCamera.convertSceneToCameraSceneTouchEvent(pSceneTouchEvent); return result; } else { return super.onChildSceneTouchEvent(pSceneTouchEvent); } } @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { if(this.mCamera != null) { pGL.glMatrixMode(GL10.GL_PROJECTION); this.mCamera.onApplyCameraSceneMatrix(pGL); { pGL.glMatrixMode(GL10.GL_MODELVIEW); pGL.glPushMatrix(); pGL.glLoadIdentity(); super.onManagedDraw(pGL, pCamera); pGL.glPopMatrix(); } pGL.glMatrixMode(GL10.GL_PROJECTION); } } // =========================================================== // Methods // =========================================================== public void centerShapeInCamera(final Shape pShape) { final Camera camera = this.mCamera; pShape.setPosition((camera.getWidth() - pShape.getWidth()) * 0.5f, (camera.getHeight() - pShape.getHeight()) * 0.5f); } public void centerShapeInCameraHorizontally(final Shape pShape) { pShape.setPosition((this.mCamera.getWidth() - pShape.getWidth()) * 0.5f, pShape.getY()); } public void centerShapeInCameraVertically(final Shape pShape) { pShape.setPosition(pShape.getX(), (this.mCamera.getHeight() - pShape.getHeight()) * 0.5f); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.handler.UpdateHandlerList; import org.anddev.andengine.entity.modifier.EntityModifierList; import org.anddev.andengine.entity.modifier.IEntityModifier; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierMatcher; import org.anddev.andengine.util.ParameterCallable; import org.anddev.andengine.util.SmartList; import org.anddev.andengine.util.Transformation; import org.anddev.andengine.util.constants.Constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:48 - 08.03.2010 */ public class Entity implements IEntity { // =========================================================== // Constants // =========================================================== private static final int CHILDREN_CAPACITY_DEFAULT = 4; private static final int ENTITYMODIFIERS_CAPACITY_DEFAULT = 4; private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 4; private static final float[] VERTICES_SCENE_TO_LOCAL_TMP = new float[2]; private static final float[] VERTICES_LOCAL_TO_SCENE_TMP = new float[2]; private static final ParameterCallable<IEntity> PARAMETERCALLABLE_DETACHCHILD = new ParameterCallable<IEntity>() { @Override public void call(final IEntity pEntity) { pEntity.setParent(null); pEntity.onDetached(); } }; // =========================================================== // Fields // =========================================================== protected boolean mVisible = true; protected boolean mIgnoreUpdate = false; protected boolean mChildrenVisible = true; protected boolean mChildrenIgnoreUpdate = false; protected int mZIndex = 0; private IEntity mParent; protected SmartList<IEntity> mChildren; private EntityModifierList mEntityModifiers; private UpdateHandlerList mUpdateHandlers; protected float mRed = 1f; protected float mGreen = 1f; protected float mBlue = 1f; protected float mAlpha = 1f; protected float mX; protected float mY; private final float mInitialX; private final float mInitialY; protected float mRotation = 0; protected float mRotationCenterX = 0; protected float mRotationCenterY = 0; protected float mScaleX = 1f; protected float mScaleY = 1f; protected float mScaleCenterX = 0; protected float mScaleCenterY = 0; private boolean mLocalToParentTransformationDirty = true; private boolean mParentToLocalTransformationDirty = true; private final Transformation mLocalToParentTransformation = new Transformation(); private final Transformation mParentToLocalTransformation = new Transformation(); private final Transformation mLocalToSceneTransformation = new Transformation(); private final Transformation mSceneToLocalTransformation = new Transformation(); private Object mUserData; // =========================================================== // Constructors // =========================================================== public Entity() { this(0, 0); } public Entity(final float pX, final float pY) { this.mInitialX = pX; this.mInitialY = pY; this.mX = pX; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean isVisible() { return this.mVisible; } @Override public void setVisible(final boolean pVisible) { this.mVisible = pVisible; } @Override public boolean isChildrenVisible() { return this.mChildrenVisible; } @Override public void setChildrenVisible(final boolean pChildrenVisible) { this.mChildrenVisible = pChildrenVisible; } @Override public boolean isIgnoreUpdate() { return this.mIgnoreUpdate; } @Override public void setIgnoreUpdate(final boolean pIgnoreUpdate) { this.mIgnoreUpdate = pIgnoreUpdate; } @Override public boolean isChildrenIgnoreUpdate() { return this.mChildrenIgnoreUpdate; } @Override public void setChildrenIgnoreUpdate(final boolean pChildrenIgnoreUpdate) { this.mChildrenIgnoreUpdate = pChildrenIgnoreUpdate; } @Override public boolean hasParent() { return this.mParent != null; } @Override public IEntity getParent() { return this.mParent; } @Override public void setParent(final IEntity pEntity) { this.mParent = pEntity; } @Override public int getZIndex() { return this.mZIndex; } @Override public void setZIndex(final int pZIndex) { this.mZIndex = pZIndex; } @Override public float getX() { return this.mX; } @Override public float getY() { return this.mY; } @Override public float getInitialX() { return this.mInitialX; } @Override public float getInitialY() { return this.mInitialY; } @Override public void setPosition(final IEntity pOtherEntity) { this.setPosition(pOtherEntity.getX(), pOtherEntity.getY()); } @Override public void setPosition(final float pX, final float pY) { this.mX = pX; this.mY = pY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setInitialPosition() { this.mX = this.mInitialX; this.mY = this.mInitialY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public float getRotation() { return this.mRotation; } @Override public boolean isRotated() { return this.mRotation != 0; } @Override public void setRotation(final float pRotation) { this.mRotation = pRotation; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public float getRotationCenterX() { return this.mRotationCenterX; } @Override public float getRotationCenterY() { return this.mRotationCenterY; } @Override public void setRotationCenterX(final float pRotationCenterX) { this.mRotationCenterX = pRotationCenterX; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setRotationCenterY(final float pRotationCenterY) { this.mRotationCenterY = pRotationCenterY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setRotationCenter(final float pRotationCenterX, final float pRotationCenterY) { this.mRotationCenterX = pRotationCenterX; this.mRotationCenterY = pRotationCenterY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public boolean isScaled() { return this.mScaleX != 1 || this.mScaleY != 1; } @Override public float getScaleX() { return this.mScaleX; } @Override public float getScaleY() { return this.mScaleY; } @Override public void setScaleX(final float pScaleX) { this.mScaleX = pScaleX; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setScaleY(final float pScaleY) { this.mScaleY = pScaleY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setScale(final float pScale) { this.mScaleX = pScale; this.mScaleY = pScale; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setScale(final float pScaleX, final float pScaleY) { this.mScaleX = pScaleX; this.mScaleY = pScaleY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public float getScaleCenterX() { return this.mScaleCenterX; } @Override public float getScaleCenterY() { return this.mScaleCenterY; } @Override public void setScaleCenterX(final float pScaleCenterX) { this.mScaleCenterX = pScaleCenterX; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setScaleCenterY(final float pScaleCenterY) { this.mScaleCenterY = pScaleCenterY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public void setScaleCenter(final float pScaleCenterX, final float pScaleCenterY) { this.mScaleCenterX = pScaleCenterX; this.mScaleCenterY = pScaleCenterY; this.mLocalToParentTransformationDirty = true; this.mParentToLocalTransformationDirty = true; } @Override public float getRed() { return this.mRed; } @Override public float getGreen() { return this.mGreen; } @Override public float getBlue() { return this.mBlue; } @Override public float getAlpha() { return this.mAlpha; } /** * @param pAlpha from <code>0.0f</code> (transparent) to <code>1.0f</code> (opaque) */ @Override public void setAlpha(final float pAlpha) { this.mAlpha = pAlpha; } /** * @param pRed from <code>0.0f</code> to <code>1.0f</code> * @param pGreen from <code>0.0f</code> to <code>1.0f</code> * @param pBlue from <code>0.0f</code> to <code>1.0f</code> */ @Override public void setColor(final float pRed, final float pGreen, final float pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; } /** * @param pRed from <code>0.0f</code> to <code>1.0f</code> * @param pGreen from <code>0.0f</code> to <code>1.0f</code> * @param pBlue from <code>0.0f</code> to <code>1.0f</code> * @param pAlpha from <code>0.0f</code> (transparent) to <code>1.0f</code> (opaque) */ @Override public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.mAlpha = pAlpha; } @Override public int getChildCount() { if(this.mChildren == null) { return 0; } return this.mChildren.size(); } @Override public IEntity getChild(final int pIndex) { if(this.mChildren == null) { return null; } return this.mChildren.get(pIndex); } @Override public int getChildIndex(final IEntity pEntity) { if (this.mChildren == null || pEntity.getParent() != this) { return -1; } return this.mChildren.indexOf(pEntity); } @Override public boolean setChildIndex(final IEntity pEntity, final int pIndex) { if (this.mChildren == null || pEntity.getParent() != this) { return false; } try { this.mChildren.remove(pEntity); this.mChildren.add(pIndex, pEntity); return true; } catch (final IndexOutOfBoundsException e) { return false; } } @Override public IEntity getFirstChild() { if(this.mChildren == null) { return null; } return this.mChildren.get(0); } @Override public IEntity getLastChild() { if(this.mChildren == null) { return null; } return this.mChildren.get(this.mChildren.size() - 1); } @Override public boolean detachSelf() { final IEntity parent = this.mParent; if(parent != null) { return parent.detachChild(this); } else { return false; } } @Override public void detachChildren() { if(this.mChildren == null) { return; } this.mChildren.clear(PARAMETERCALLABLE_DETACHCHILD); } @Override public void attachChild(final IEntity pEntity) throws IllegalStateException { if(pEntity.hasParent()) { throw new IllegalStateException("pEntity already has a parent!"); } if(this.mChildren == null) { this.allocateChildren(); } this.mChildren.add(pEntity); pEntity.setParent(this); pEntity.onAttached(); } @Override public boolean attachChild(final IEntity pEntity, final int pIndex) throws IllegalStateException { if(pEntity.hasParent()) { throw new IllegalStateException("pEntity already has a parent!"); } if (this.mChildren == null) { this.allocateChildren(); } try { this.mChildren.add(pIndex, pEntity); pEntity.setParent(this); pEntity.onAttached(); return true; } catch (final IndexOutOfBoundsException e) { return false; } } @Override public IEntity findChild(final IEntityMatcher pEntityMatcher) { if(this.mChildren == null) { return null; } return this.mChildren.find(pEntityMatcher); } @Override public boolean swapChildren(final IEntity pEntityA, final IEntity pEntityB) { return this.swapChildren(this.getChildIndex(pEntityA), this.getChildIndex(pEntityB)); } @Override public boolean swapChildren(final int pIndexA, final int pIndexB) { try { Collections.swap(this.mChildren, pIndexA, pIndexB); return true; } catch (final IndexOutOfBoundsException e) { return false; } } @Override public void sortChildren() { if(this.mChildren == null) { return; } ZIndexSorter.getInstance().sort(this.mChildren); } @Override public void sortChildren(final Comparator<IEntity> pEntityComparator) { if(this.mChildren == null) { return; } ZIndexSorter.getInstance().sort(this.mChildren, pEntityComparator); } @Override public boolean detachChild(final IEntity pEntity) { if(this.mChildren == null) { return false; } return this.mChildren.remove(pEntity, PARAMETERCALLABLE_DETACHCHILD); } @Override public IEntity detachChild(final IEntityMatcher pEntityMatcher) { if(this.mChildren == null) { return null; } return this.mChildren.remove(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); } @Override public boolean detachChildren(final IEntityMatcher pEntityMatcher) { if(this.mChildren == null) { return false; } return this.mChildren.removeAll(pEntityMatcher, Entity.PARAMETERCALLABLE_DETACHCHILD); } @Override public void callOnChildren(final IEntityCallable pEntityCallable) { if(this.mChildren == null) { return; } this.mChildren.call(pEntityCallable); } @Override public void callOnChildren(final IEntityMatcher pEntityMatcher, final IEntityCallable pEntityCallable) { if(this.mChildren == null) { return; } this.mChildren.call(pEntityMatcher, pEntityCallable); } @Override public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) { if(this.mUpdateHandlers == null) { this.allocateUpdateHandlers(); } this.mUpdateHandlers.add(pUpdateHandler); } @Override public boolean unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) { if(this.mUpdateHandlers == null) { return false; } return this.mUpdateHandlers.remove(pUpdateHandler); } @Override public boolean unregisterUpdateHandlers(final IUpdateHandlerMatcher pUpdateHandlerMatcher) { if(this.mUpdateHandlers == null) { return false; } return this.mUpdateHandlers.removeAll(pUpdateHandlerMatcher); } @Override public void clearUpdateHandlers() { if(this.mUpdateHandlers == null) { return; } this.mUpdateHandlers.clear(); } @Override public void registerEntityModifier(final IEntityModifier pEntityModifier) { if(this.mEntityModifiers == null) { this.allocateEntityModifiers(); } this.mEntityModifiers.add(pEntityModifier); } @Override public boolean unregisterEntityModifier(final IEntityModifier pEntityModifier) { if(this.mEntityModifiers == null) { return false; } return this.mEntityModifiers.remove(pEntityModifier); } @Override public boolean unregisterEntityModifiers(final IEntityModifierMatcher pEntityModifierMatcher) { if(this.mEntityModifiers == null) { return false; } return this.mEntityModifiers.removeAll(pEntityModifierMatcher); } @Override public void clearEntityModifiers() { if(this.mEntityModifiers == null) { return; } this.mEntityModifiers.clear(); } @Override public float[] getSceneCenterCoordinates() { return this.convertLocalToSceneCoordinates(0, 0); } public Transformation getLocalToParentTransformation() { final Transformation localToParentTransformation = this.mLocalToParentTransformation; if(this.mLocalToParentTransformationDirty) { localToParentTransformation.setToIdentity(); /* Scale. */ final float scaleX = this.mScaleX; final float scaleY = this.mScaleY; if(scaleX != 1 || scaleY != 1) { final float scaleCenterX = this.mScaleCenterX; final float scaleCenterY = this.mScaleCenterY; /* TODO Check if it is worth to check for scaleCenterX == 0 && scaleCenterY == 0 as the two postTranslate can be saved. * The same obviously applies for all similar occurrences of this pattern in this class. */ localToParentTransformation.postTranslate(-scaleCenterX, -scaleCenterY); localToParentTransformation.postScale(scaleX, scaleY); localToParentTransformation.postTranslate(scaleCenterX, scaleCenterY); } /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. * In that case the last postTranslate of the scale and the first postTranslate of the rotation is superfluous. */ /* Rotation. */ final float rotation = this.mRotation; if(rotation != 0) { final float rotationCenterX = this.mRotationCenterX; final float rotationCenterY = this.mRotationCenterY; localToParentTransformation.postTranslate(-rotationCenterX, -rotationCenterY); localToParentTransformation.postRotate(rotation); localToParentTransformation.postTranslate(rotationCenterX, rotationCenterY); } /* Translation. */ localToParentTransformation.postTranslate(this.mX, this.mY); this.mLocalToParentTransformationDirty = false; } return localToParentTransformation; } public Transformation getParentToLocalTransformation() { final Transformation parentToLocalTransformation = this.mParentToLocalTransformation; if(this.mParentToLocalTransformationDirty) { parentToLocalTransformation.setToIdentity(); /* Translation. */ parentToLocalTransformation.postTranslate(-this.mX, -this.mY); /* Rotation. */ final float rotation = this.mRotation; if(rotation != 0) { final float rotationCenterX = this.mRotationCenterX; final float rotationCenterY = this.mRotationCenterY; parentToLocalTransformation.postTranslate(-rotationCenterX, -rotationCenterY); parentToLocalTransformation.postRotate(-rotation); parentToLocalTransformation.postTranslate(rotationCenterX, rotationCenterY); } /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. * In that case the last postTranslate of the rotation and the first postTranslate of the scale is superfluous. */ /* Scale. */ final float scaleX = this.mScaleX; final float scaleY = this.mScaleY; if(scaleX != 1 || scaleY != 1) { final float scaleCenterX = this.mScaleCenterX; final float scaleCenterY = this.mScaleCenterY; parentToLocalTransformation.postTranslate(-scaleCenterX, -scaleCenterY); parentToLocalTransformation.postScale(1 / scaleX, 1 / scaleY); parentToLocalTransformation.postTranslate(scaleCenterX, scaleCenterY); } this.mParentToLocalTransformationDirty = false; } return parentToLocalTransformation; } @Override public Transformation getLocalToSceneTransformation() { // TODO Cache if parent(recursive) not dirty. final Transformation localToSceneTransformation = this.mLocalToSceneTransformation; localToSceneTransformation.setTo(this.getLocalToParentTransformation()); final IEntity parent = this.mParent; if(parent != null) { localToSceneTransformation.postConcat(parent.getLocalToSceneTransformation()); } return localToSceneTransformation; } @Override public Transformation getSceneToLocalTransformation() { // TODO Cache if parent(recursive) not dirty. final Transformation sceneToLocalTransformation = this.mSceneToLocalTransformation; sceneToLocalTransformation.setTo(this.getParentToLocalTransformation()); final IEntity parent = this.mParent; if(parent != null) { sceneToLocalTransformation.postConcat(parent.getSceneToLocalTransformation()); } return sceneToLocalTransformation; } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float) */ @Override public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { return this.convertLocalToSceneCoordinates(pX, pY, VERTICES_LOCAL_TO_SCENE_TMP); } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float, float, float[]) */ @Override public float[] convertLocalToSceneCoordinates(final float pX, final float pY, final float[] pReuse) { pReuse[Constants.VERTEX_INDEX_X] = pX; pReuse[Constants.VERTEX_INDEX_Y] = pY; this.getLocalToSceneTransformation().transform(pReuse); return pReuse; } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[]) */ @Override public float[] convertLocalToSceneCoordinates(final float[] pCoordinates) { return this.convertSceneToLocalCoordinates(pCoordinates, VERTICES_LOCAL_TO_SCENE_TMP); } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertLocalToSceneCoordinates(float[], float[]) */ @Override public float[] convertLocalToSceneCoordinates(final float[] pCoordinates, final float[] pReuse) { pReuse[Constants.VERTEX_INDEX_X] = pCoordinates[Constants.VERTEX_INDEX_X]; pReuse[Constants.VERTEX_INDEX_Y] = pCoordinates[Constants.VERTEX_INDEX_Y]; this.getLocalToSceneTransformation().transform(pReuse); return pReuse; } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float) */ @Override public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { return this.convertSceneToLocalCoordinates(pX, pY, VERTICES_SCENE_TO_LOCAL_TMP); } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float, float, float[]) */ @Override public float[] convertSceneToLocalCoordinates(final float pX, final float pY, final float[] pReuse) { pReuse[Constants.VERTEX_INDEX_X] = pX; pReuse[Constants.VERTEX_INDEX_Y] = pY; this.getSceneToLocalTransformation().transform(pReuse); return pReuse; } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[]) */ @Override public float[] convertSceneToLocalCoordinates(final float[] pCoordinates) { return this.convertSceneToLocalCoordinates(pCoordinates, VERTICES_SCENE_TO_LOCAL_TMP); } /* (non-Javadoc) * @see org.anddev.andengine.entity.IEntity#convertSceneToLocalCoordinates(float[], float[]) */ @Override public float[] convertSceneToLocalCoordinates(final float[] pCoordinates, final float[] pReuse) { pReuse[Constants.VERTEX_INDEX_X] = pCoordinates[Constants.VERTEX_INDEX_X]; pReuse[Constants.VERTEX_INDEX_Y] = pCoordinates[Constants.VERTEX_INDEX_Y]; this.getSceneToLocalTransformation().transform(pReuse); return pReuse; } @Override public void onAttached() { } @Override public void onDetached() { } @Override public Object getUserData() { return this.mUserData; } @Override public void setUserData(final Object pUserData) { this.mUserData = pUserData; } @Override public final void onDraw(final GL10 pGL, final Camera pCamera) { if(this.mVisible) { this.onManagedDraw(pGL, pCamera); } } @Override public final void onUpdate(final float pSecondsElapsed) { if(!this.mIgnoreUpdate) { this.onManagedUpdate(pSecondsElapsed); } } @Override public void reset() { this.mVisible = true; this.mIgnoreUpdate = false; this.mChildrenVisible = true; this.mChildrenIgnoreUpdate = false; this.mX = this.mInitialX; this.mY = this.mInitialY; this.mRotation = 0; this.mScaleX = 1; this.mScaleY = 1; this.mRed = 1.0f; this.mGreen = 1.0f; this.mBlue = 1.0f; this.mAlpha = 1.0f; if(this.mEntityModifiers != null) { this.mEntityModifiers.reset(); } if(this.mChildren != null) { final ArrayList<IEntity> entities = this.mChildren; for(int i = entities.size() - 1; i >= 0; i--) { entities.get(i).reset(); } } } // =========================================================== // Methods // =========================================================== /** * @param pGL the OpenGL GL1.0 Context (potentially higher than 1.0) to use for drawing. * @param pCamera the currently active {@link Camera} i.e. to be used for culling. */ protected void doDraw(final GL10 pGL, final Camera pCamera) { } private void allocateEntityModifiers() { this.mEntityModifiers = new EntityModifierList(this, Entity.ENTITYMODIFIERS_CAPACITY_DEFAULT); } private void allocateChildren() { this.mChildren = new SmartList<IEntity>(Entity.CHILDREN_CAPACITY_DEFAULT); } private void allocateUpdateHandlers() { this.mUpdateHandlers = new UpdateHandlerList(Entity.UPDATEHANDLERS_CAPACITY_DEFAULT); } protected void onApplyTransformations(final GL10 pGL) { /* Translation. */ this.applyTranslation(pGL); /* Rotation. */ this.applyRotation(pGL); /* Scale. */ this.applyScale(pGL); } protected void applyTranslation(final GL10 pGL) { pGL.glTranslatef(this.mX, this.mY, 0); } protected void applyRotation(final GL10 pGL) { final float rotation = this.mRotation; if(rotation != 0) { final float rotationCenterX = this.mRotationCenterX; final float rotationCenterY = this.mRotationCenterY; pGL.glTranslatef(rotationCenterX, rotationCenterY, 0); pGL.glRotatef(rotation, 0, 0, 1); pGL.glTranslatef(-rotationCenterX, -rotationCenterY, 0); /* TODO There is a special, but very likely case when mRotationCenter and mScaleCenter are the same. * In that case the last glTranslatef of the rotation and the first glTranslatef of the scale is superfluous. * The problem is that applyRotation and applyScale would need to be "merged" in order to efficiently check for that condition. */ } } protected void applyScale(final GL10 pGL) { final float scaleX = this.mScaleX; final float scaleY = this.mScaleY; if(scaleX != 1 || scaleY != 1) { final float scaleCenterX = this.mScaleCenterX; final float scaleCenterY = this.mScaleCenterY; pGL.glTranslatef(scaleCenterX, scaleCenterY, 0); pGL.glScalef(scaleX, scaleY, 1); pGL.glTranslatef(-scaleCenterX, -scaleCenterY, 0); } } protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { pGL.glPushMatrix(); { this.onApplyTransformations(pGL); this.doDraw(pGL, pCamera); this.onDrawChildren(pGL, pCamera); } pGL.glPopMatrix(); } protected void onDrawChildren(final GL10 pGL, final Camera pCamera) { if(this.mChildren != null && this.mChildrenVisible) { this.onManagedDrawChildren(pGL, pCamera); } } public void onManagedDrawChildren(final GL10 pGL, final Camera pCamera) { final ArrayList<IEntity> children = this.mChildren; final int childCount = children.size(); for(int i = 0; i < childCount; i++) { children.get(i).onDraw(pGL, pCamera); } } protected void onManagedUpdate(final float pSecondsElapsed) { if(this.mEntityModifiers != null) { this.mEntityModifiers.onUpdate(pSecondsElapsed); } if(this.mUpdateHandlers != null) { this.mUpdateHandlers.onUpdate(pSecondsElapsed); } if(this.mChildren != null && !this.mChildrenIgnoreUpdate) { final ArrayList<IEntity> entities = this.mChildren; final int entityCount = entities.size(); for(int i = 0; i < entityCount; i++) { entities.get(i).onUpdate(pSecondsElapsed); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.util; import org.anddev.andengine.util.constants.TimeConstants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ public abstract class AverageFPSCounter extends FPSCounter implements TimeConstants { // =========================================================== // Constants // =========================================================== private static final float AVERAGE_DURATION_DEFAULT = 5; // =========================================================== // Fields // =========================================================== protected final float mAverageDuration; // =========================================================== // Constructors // =========================================================== public AverageFPSCounter() { this(AVERAGE_DURATION_DEFAULT); } public AverageFPSCounter(final float pAverageDuration) { this.mAverageDuration = pAverageDuration; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onHandleAverageDurationElapsed(final float pFPS); @Override public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed); if(this.mSecondsElapsed > this.mAverageDuration){ this.onHandleAverageDurationElapsed(this.getFPS()); this.mSecondsElapsed -= this.mAverageDuration; this.mFrames = 0; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.util; import org.anddev.andengine.engine.handler.IUpdateHandler; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:00:55 - 22.06.2010 */ public class FrameCounter implements IUpdateHandler { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private int mFrames; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public int getFrames() { return this.mFrames; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { this.mFrames++; } @Override public void reset() { this.mFrames = 0; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.util; import org.anddev.andengine.engine.handler.IUpdateHandler; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ public class FPSCounter implements IUpdateHandler { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mSecondsElapsed; protected int mFrames; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public float getFPS() { return this.mFrames / this.mSecondsElapsed; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { this.mFrames++; this.mSecondsElapsed += pSecondsElapsed; } @Override public void reset() { this.mFrames = 0; this.mSecondsElapsed = 0; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.util; import org.anddev.andengine.util.Debug; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ public class FPSLogger extends AverageFPSCounter { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected float mShortestFrame = Float.MAX_VALUE; protected float mLongestFrame = Float.MIN_VALUE; // =========================================================== // Constructors // =========================================================== public FPSLogger() { super(); } public FPSLogger(final float pAverageDuration) { super(pAverageDuration); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onHandleAverageDurationElapsed(final float pFPS) { this.onLogFPS(); this.mLongestFrame = Float.MIN_VALUE; this.mShortestFrame = Float.MAX_VALUE; } @Override public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed); this.mShortestFrame = Math.min(this.mShortestFrame, pSecondsElapsed); this.mLongestFrame = Math.max(this.mLongestFrame, pSecondsElapsed); } @Override public void reset() { super.reset(); this.mShortestFrame = Float.MAX_VALUE; this.mLongestFrame = Float.MIN_VALUE; } // =========================================================== // Methods // =========================================================== protected void onLogFPS() { Debug.d(String.format("FPS: %.2f (MIN: %.0f ms | MAX: %.0f ms)", this.mFrames / this.mSecondsElapsed, this.mShortestFrame * MILLISECONDSPERSECOND, this.mLongestFrame * MILLISECONDSPERSECOND)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.util; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.constants.TimeConstants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:52:31 - 09.03.2010 */ public class FrameCountCrasher implements IUpdateHandler, TimeConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private int mFramesLeft; private final float[] mFrameLengths; // =========================================================== // Constructors // =========================================================== public FrameCountCrasher(final int pFrameCount) { this.mFramesLeft = pFrameCount; this.mFrameLengths = new float[pFrameCount]; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { this.mFramesLeft--; final float[] frameLengths = this.mFrameLengths; if(this.mFramesLeft >= 0) { frameLengths[this.mFramesLeft] = pSecondsElapsed; } else { for(int i = frameLengths.length - 1; i >= 0; i--) { Debug.d("Elapsed: " + frameLengths[i]); } throw new RuntimeException(); } } @Override public void reset() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.util; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.Entity; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:27:22 - 10.01.2011 */ public class ScreenGrabber extends Entity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private int mGrabX; private int mGrabY; private int mGrabWidth; private int mGrabHeight; private boolean mScreenGrabPending = false; private IScreenGrabberCallback mScreenGrabCallback; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { if(this.mScreenGrabPending) { try { final Bitmap screenGrab = ScreenGrabber.grab(this.mGrabX, this.mGrabY, this.mGrabWidth, this.mGrabHeight, pGL); this.mScreenGrabCallback.onScreenGrabbed(screenGrab); } catch (final Exception e) { this.mScreenGrabCallback.onScreenGrabFailed(e); } this.mScreenGrabPending = false; } } @Override protected void onManagedUpdate(final float pSecondsElapsed) { /* Nothing */ } @Override public void reset() { /* Nothing */ } // =========================================================== // Methods // =========================================================== public void grab(final int pGrabWidth, final int pGrabHeight, final IScreenGrabberCallback pScreenGrabCallback) { this.grab(0, 0, pGrabWidth, pGrabHeight, pScreenGrabCallback); } public void grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final int pGrabHeight, final IScreenGrabberCallback pScreenGrabCallback) { this.mGrabX = pGrabX; this.mGrabY = pGrabY; this.mGrabWidth = pGrabWidth; this.mGrabHeight = pGrabHeight; this.mScreenGrabCallback = pScreenGrabCallback; this.mScreenGrabPending = true; } private static Bitmap grab(final int pGrabX, final int pGrabY, final int pGrabWidth, final int pGrabHeight, final GL10 pGL) { final int[] source = new int[pGrabWidth * (pGrabY + pGrabHeight)]; final IntBuffer sourceBuffer = IntBuffer.wrap(source); sourceBuffer.position(0); // TODO Check availability of OpenGL and GL10.GL_RGBA combinations that require less conversion operations. // Note: There is (said to be) a bug with glReadPixels when 'y != 0', so we simply read starting from 'y == 0'. pGL.glReadPixels(pGrabX, 0, pGrabWidth, pGrabY + pGrabHeight, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, sourceBuffer); final int[] pixels = new int[pGrabWidth * pGrabHeight]; // Convert from RGBA_8888 (Which is actually ABGR as the whole buffer seems to be inverted) --> ARGB_8888 for (int y = 0; y < pGrabHeight; y++) { for (int x = 0; x < pGrabWidth; x++) { final int pixel = source[x + ((pGrabY + y) * pGrabWidth)]; final int blue = (pixel & 0x00FF0000) >> 16; final int red = (pixel & 0x000000FF) << 16; final int greenAlpha = pixel & 0xFF00FF00; pixels[x + ((pGrabHeight - y - 1) * pGrabWidth)] = greenAlpha | red | blue; } } return Bitmap.createBitmap(pixels, pGrabWidth, pGrabHeight, Config.ARGB_8888); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IScreenGrabberCallback { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public void onScreenGrabbed(final Bitmap pBitmap); public void onScreenGrabFailed(final Exception pException); } }
Java
package org.anddev.andengine.entity.util; import java.io.FileNotFoundException; import java.io.FileOutputStream; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.util.ScreenGrabber.IScreenGrabberCallback; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.StreamUtils; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:11:50 - 15.03.2010 */ public class ScreenCapture extends Entity implements IScreenGrabberCallback { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private String mFilePath; private final ScreenGrabber mScreenGrabber = new ScreenGrabber(); private IScreenCaptureCallback mScreenCaptureCallback; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { this.mScreenGrabber.onManagedDraw(pGL, pCamera); } @Override protected void onManagedUpdate(final float pSecondsElapsed) { /* Nothing */ } @Override public void reset() { /* Nothing */ } @Override public void onScreenGrabbed(final Bitmap pBitmap) { try { ScreenCapture.saveCapture(pBitmap, this.mFilePath); this.mScreenCaptureCallback.onScreenCaptured(this.mFilePath); } catch (final FileNotFoundException e) { this.mScreenCaptureCallback.onScreenCaptureFailed(this.mFilePath, e); } } @Override public void onScreenGrabFailed(final Exception pException) { this.mScreenCaptureCallback.onScreenCaptureFailed(this.mFilePath, pException); } // =========================================================== // Methods // =========================================================== public void capture(final int pCaptureWidth, final int pCaptureHeight, final String pFilePath, final IScreenCaptureCallback pScreenCaptureCallback) { this.capture(0, 0, pCaptureWidth, pCaptureHeight, pFilePath, pScreenCaptureCallback); } public void capture(final int pCaptureX, final int pCaptureY, final int pCaptureWidth, final int pCaptureHeight, final String pFilePath, final IScreenCaptureCallback pScreencaptureCallback) { this.mFilePath = pFilePath; this.mScreenCaptureCallback = pScreencaptureCallback; this.mScreenGrabber.grab(pCaptureX, pCaptureY, pCaptureWidth, pCaptureHeight, this); } private static void saveCapture(final Bitmap pBitmap, final String pFilePath) throws FileNotFoundException { FileOutputStream fos = null; try { fos = new FileOutputStream(pFilePath); pBitmap.compress(CompressFormat.PNG, 100, fos); } catch (final FileNotFoundException e) { StreamUtils.flushCloseStream(fos); Debug.e("Error saving file to: " + pFilePath, e); throw e; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IScreenCaptureCallback { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public void onScreenCaptured(final String pFilePath); public void onScreenCaptureFailed(final String pFilePath, final Exception pException); } }
Java
package org.anddev.andengine.entity.primitive; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.entity.shape.RectangularShape; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:05:49 - 11.04.2010 */ public abstract class BaseRectangle extends RectangularShape { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public BaseRectangle(final float pX, final float pY, final float pWidth, final float pHeight) { super(pX, pY, pWidth, pHeight, new RectangleVertexBuffer(GL11.GL_STATIC_DRAW, true)); this.updateVertexBuffer(); } public BaseRectangle(final float pX, final float pY, final float pWidth, final float pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public RectangleVertexBuffer getVertexBuffer() { return (RectangleVertexBuffer)this.mVertexBuffer; } @Override protected void onUpdateVertexBuffer(){ this.getVertexBuffer().update(this.mWidth, this.mHeight); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.primitive; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:18:49 - 13.03.2010 */ public class Rectangle extends BaseRectangle { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public Rectangle(final float pX, final float pY, final float pWidth, final float pHeight) { super(pX, pY, pWidth, pHeight); } public Rectangle(final float pX, final float pY, final float pWidth, final float pHeight, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pWidth, pHeight, pRectangleVertexBuffer); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onInitDraw(final GL10 pGL) { super.onInitDraw(pGL); GLHelper.disableTextures(pGL); GLHelper.disableTexCoordArray(pGL); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.entity.primitive; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.collision.LineCollisionChecker; import org.anddev.andengine.collision.RectangularShapeCollisionChecker; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.shape.IShape; import org.anddev.andengine.entity.shape.RectangularShape; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.LineVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 09:50:36 - 04.04.2010 */ public class Line extends Shape { // =========================================================== // Constants // =========================================================== private static final float LINEWIDTH_DEFAULT = 1.0f; // =========================================================== // Fields // =========================================================== protected float mX2; protected float mY2; private float mLineWidth; private final LineVertexBuffer mLineVertexBuffer; // =========================================================== // Constructors // =========================================================== public Line(final float pX1, final float pY1, final float pX2, final float pY2) { this(pX1, pY1, pX2, pY2, LINEWIDTH_DEFAULT); } public Line(final float pX1, final float pY1, final float pX2, final float pY2, final float pLineWidth) { super(pX1, pY1); this.mX2 = pX2; this.mY2 = pY2; this.mLineWidth = pLineWidth; this.mLineVertexBuffer = new LineVertexBuffer(GL11.GL_STATIC_DRAW, true); this.updateVertexBuffer(); final float width = this.getWidth(); final float height = this.getHeight(); this.mRotationCenterX = width * 0.5f; this.mRotationCenterY = height * 0.5f; this.mScaleCenterX = this.mRotationCenterX; this.mScaleCenterY = this.mRotationCenterY; } // =========================================================== // Getter & Setter // =========================================================== /** * @deprecated Instead use {@link Line#getX1()} or {@link Line#getX2()}. */ @Deprecated @Override public float getX() { return super.getX(); } /** * @deprecatedInstead use {@link Line#getY1()} or {@link Line#getY2()}. */ @Deprecated @Override public float getY() { return super.getY(); } public float getX1() { return super.getX(); } public float getY1() { return super.getY(); } public float getX2() { return this.mX2; } public float getY2() { return this.mY2; } public float getLineWidth() { return this.mLineWidth; } public void setLineWidth(final float pLineWidth) { this.mLineWidth = pLineWidth; } @Override public float getBaseHeight() { return this.mY2 - this.mY; } @Override public float getBaseWidth() { return this.mX2 - this.mX; } @Override public float getHeight() { return this.mY2 - this.mY; } @Override public float getWidth() { return this.mX2 - this.mX; } /** * @deprecated Instead use {@link Line#setPosition(float, float, float, float)}. */ @Deprecated @Override public void setPosition(final float pX, final float pY) { final float dX = this.mX - pX; final float dY = this.mY - pY; super.setPosition(pX, pY); this.mX2 += dX; this.mY2 += dY; } public void setPosition(final float pX1, final float pY1, final float pX2, final float pY2) { this.mX2 = pX2; this.mY2 = pY2; super.setPosition(pX1, pY1); this.updateVertexBuffer(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected boolean isCulled(final Camera pCamera) { return pCamera.isLineVisible(this); } @Override protected void onInitDraw(final GL10 pGL) { super.onInitDraw(pGL); GLHelper.disableTextures(pGL); GLHelper.disableTexCoordArray(pGL); GLHelper.lineWidth(pGL, this.mLineWidth); } @Override public LineVertexBuffer getVertexBuffer() { return this.mLineVertexBuffer; } @Override protected void onUpdateVertexBuffer() { this.mLineVertexBuffer.update(0, 0, this.mX2 - this.mX, this.mY2 - this.mY); } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { pGL.glDrawArrays(GL10.GL_LINES, 0, LineVertexBuffer.VERTICES_PER_LINE); } @Override public float[] getSceneCenterCoordinates() { return null; // TODO // return convertLocalToSceneCoordinates(this, (this.mX + this.mX2) * 0.5f, (this.mY + this.mY2) * 0.5f); } @Override @Deprecated public boolean contains(final float pX, final float pY) { return false; } @Override @Deprecated public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { return null; } @Override @Deprecated public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { return null; } @Override public boolean collidesWith(final IShape pOtherShape) { if(pOtherShape instanceof Line) { final Line otherLine = (Line) pOtherShape; return LineCollisionChecker.checkLineCollision(this.mX, this.mY, this.mX2, this.mY2, otherLine.mX, otherLine.mY, otherLine.mX2, otherLine.mY2); } else if(pOtherShape instanceof RectangularShape) { final RectangularShape rectangularShape = (RectangularShape) pOtherShape; return RectangularShapeCollisionChecker.checkCollision(rectangularShape, this); } else { return false; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor; import java.util.Arrays; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:50:44 - 10.03.2010 */ public class BaseSensorData { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final float[] mValues; protected int mAccuracy; protected int mDisplayRotation; // =========================================================== // Constructors // =========================================================== public BaseSensorData(final int pValueCount, int pDisplayRotation) { this.mValues = new float[pValueCount]; this.mDisplayRotation = pDisplayRotation; } // =========================================================== // Getter & Setter // =========================================================== public float[] getValues() { return this.mValues; } public void setValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mValues, 0, pValues.length); } public void setAccuracy(final int pAccuracy) { this.mAccuracy = pAccuracy; } public int getAccuracy() { return this.mAccuracy; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Values: " + Arrays.toString(this.mValues); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.orientation; import org.anddev.andengine.sensor.SensorDelay; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:12:36 - 31.10.2010 */ public class OrientationSensorOptions { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== final SensorDelay mSensorDelay; // =========================================================== // Constructors // =========================================================== public OrientationSensorOptions(final SensorDelay pSensorDelay) { this.mSensorDelay = pSensorDelay; } // =========================================================== // Getter & Setter // =========================================================== public SensorDelay getSensorDelay() { return this.mSensorDelay; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.orientation; import java.util.Arrays; import org.anddev.andengine.sensor.BaseSensorData; import org.anddev.andengine.util.constants.MathConstants; import android.hardware.SensorManager; import android.view.Surface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:30:33 - 25.05.2010 */ public class OrientationData extends BaseSensorData { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float[] mAccelerometerValues = new float[3]; private final float[] mMagneticFieldValues = new float[3]; private final float[] mRotationMatrix = new float[16]; private int mMagneticFieldAccuracy; // =========================================================== // Constructors // =========================================================== public OrientationData(final int pDisplayRotation) { super(3, pDisplayRotation); } // =========================================================== // Getter & Setter // =========================================================== public float getRoll() { return super.mValues[SensorManager.DATA_Z]; } public float getPitch() { return super.mValues[SensorManager.DATA_Y]; } public float getYaw() { return super.mValues[SensorManager.DATA_X]; } @Override @Deprecated public void setValues(final float[] pValues) { super.setValues(pValues); } @Override @Deprecated public void setAccuracy(final int pAccuracy) { super.setAccuracy(pAccuracy); } public void setAccelerometerValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mAccelerometerValues, 0, pValues.length); this.updateOrientation(); } public void setMagneticFieldValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length); this.updateOrientation(); } private void updateOrientation() { SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerometerValues, this.mMagneticFieldValues); // TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons. switch(this.mDisplayRotation) { case Surface.ROTATION_0: /* Nothing. */ break; case Surface.ROTATION_90: SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix); break; // case Surface.ROTATION_180: // SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); // break; // case Surface.ROTATION_270: // SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); // break; } final float[] values = this.mValues; SensorManager.getOrientation(this.mRotationMatrix, values); for(int i = values.length - 1; i >= 0; i--) { values[i] = values[i] * MathConstants.RAD_TO_DEG; } } public int getAccelerometerAccuracy() { return this.getAccuracy(); } public void setAccelerometerAccuracy(final int pAccelerometerAccuracy) { super.setAccuracy(pAccelerometerAccuracy); } public int getMagneticFieldAccuracy() { return this.mMagneticFieldAccuracy; } public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy) { this.mMagneticFieldAccuracy = pMagneticFieldAccuracy; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Orientation: " + Arrays.toString(this.mValues); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.orientation; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:30:42 - 25.05.2010 */ public interface IOrientationListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onOrientationChanged(final OrientationData pOrientationData); }
Java
package org.anddev.andengine.sensor.location; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:55:57 - 31.10.2010 */ public enum LocationProviderStatus { // =========================================================== // Elements // =========================================================== AVAILABLE, OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.location; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:39:23 - 31.10.2010 */ public interface ILocationListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * @see {@link LocationListener#onProviderEnabled(String)} */ public void onLocationProviderEnabled(); /** * @see {@link LocationListener#onLocationChanged(Location)} */ public void onLocationChanged(final Location pLocation); public void onLocationLost(); /** * @see {@link LocationListener#onProviderDisabled(String)} */ public void onLocationProviderDisabled(); /** * @see {@link LocationListener#onStatusChanged(String, int, android.os.Bundle)} */ public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle); }
Java
package org.anddev.andengine.sensor.location; import org.anddev.andengine.util.constants.TimeConstants; import android.location.Criteria; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:02:12 - 31.10.2010 */ public class LocationSensorOptions extends Criteria { // =========================================================== // Constants // =========================================================== private static final long MINIMUMTRIGGERTIME_DEFAULT = 1 * TimeConstants.MILLISECONDSPERSECOND; private static final long MINIMUMTRIGGERDISTANCE_DEFAULT = 10; // =========================================================== // Fields // =========================================================== private boolean mEnabledOnly = true; private long mMinimumTriggerTime = MINIMUMTRIGGERTIME_DEFAULT; private long mMinimumTriggerDistance = MINIMUMTRIGGERDISTANCE_DEFAULT; // =========================================================== // Constructors // =========================================================== /** * @see {@link LocationSensorOptions#setAccuracy(int)}, * {@link LocationSensorOptions#setAltitudeRequired(boolean)}, * {@link LocationSensorOptions#setBearingRequired(boolean)}, * {@link LocationSensorOptions#setCostAllowed(boolean)}, * {@link LocationSensorOptions#setEnabledOnly(boolean)}, * {@link LocationSensorOptions#setMinimumTriggerDistance(long)}, * {@link LocationSensorOptions#setMinimumTriggerTime(long)}, * {@link LocationSensorOptions#setPowerRequirement(int)}, * {@link LocationSensorOptions#setSpeedRequired(boolean)}. */ public LocationSensorOptions() { } /** * @param pAccuracy * @param pAltitudeRequired * @param pBearingRequired * @param pCostAllowed * @param pPowerRequirement * @param pSpeedRequired * @param pEnabledOnly * @param pMinimumTriggerTime * @param pMinimumTriggerDistance */ public LocationSensorOptions(final int pAccuracy, final boolean pAltitudeRequired, final boolean pBearingRequired, final boolean pCostAllowed, final int pPowerRequirement, final boolean pSpeedRequired, final boolean pEnabledOnly, final long pMinimumTriggerTime, final long pMinimumTriggerDistance) { this.mEnabledOnly = pEnabledOnly; this.mMinimumTriggerTime = pMinimumTriggerTime; this.mMinimumTriggerDistance = pMinimumTriggerDistance; this.setAccuracy(pAccuracy); this.setAltitudeRequired(pAltitudeRequired); this.setBearingRequired(pBearingRequired); this.setCostAllowed(pCostAllowed); this.setPowerRequirement(pPowerRequirement); this.setSpeedRequired(pSpeedRequired); } // =========================================================== // Getter & Setter // =========================================================== public void setEnabledOnly(final boolean pEnabledOnly) { this.mEnabledOnly = pEnabledOnly; } public boolean isEnabledOnly() { return this.mEnabledOnly; } public long getMinimumTriggerTime() { return this.mMinimumTriggerTime; } public void setMinimumTriggerTime(final long pMinimumTriggerTime) { this.mMinimumTriggerTime = pMinimumTriggerTime; } public long getMinimumTriggerDistance() { return this.mMinimumTriggerDistance; } public void setMinimumTriggerDistance(final long pMinimumTriggerDistance) { this.mMinimumTriggerDistance = pMinimumTriggerDistance; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor; import android.hardware.SensorManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:14:38 - 31.10.2010 */ public enum SensorDelay { // =========================================================== // Elements // =========================================================== NORMAL(SensorManager.SENSOR_DELAY_NORMAL), UI(SensorManager.SENSOR_DELAY_UI), GAME(SensorManager.SENSOR_DELAY_GAME), FASTEST(SensorManager.SENSOR_DELAY_FASTEST); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mDelay; // =========================================================== // Constructors // =========================================================== private SensorDelay(final int pDelay) { this.mDelay = pDelay; } // =========================================================== // Getter & Setter // =========================================================== public int getDelay() { return this.mDelay; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.accelerometer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:58:38 - 10.03.2010 */ public interface IAccelerometerListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onAccelerometerChanged(final AccelerometerData pAccelerometerData); }
Java
package org.anddev.andengine.sensor.accelerometer; import java.util.Arrays; import org.anddev.andengine.sensor.BaseSensorData; import android.hardware.SensorManager; import android.view.Surface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:50:44 - 10.03.2010 */ public class AccelerometerData extends BaseSensorData { // =========================================================== // Constants // =========================================================== private static final IAxisSwap AXISSWAPS[] = new IAxisSwap[4]; static { AXISSWAPS[Surface.ROTATION_0] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = -pValues[SensorManager.DATA_X]; final float y = pValues[SensorManager.DATA_Y]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; AXISSWAPS[Surface.ROTATION_90] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = pValues[SensorManager.DATA_Y]; final float y = pValues[SensorManager.DATA_X]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; AXISSWAPS[Surface.ROTATION_180] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = pValues[SensorManager.DATA_X]; final float y = -pValues[SensorManager.DATA_Y]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; AXISSWAPS[Surface.ROTATION_270] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = -pValues[SensorManager.DATA_Y]; final float y = -pValues[SensorManager.DATA_X]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; } // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public AccelerometerData(final int pDisplayOrientation) { super(3, pDisplayOrientation); } // =========================================================== // Getter & Setter // =========================================================== public float getX() { return this.mValues[SensorManager.DATA_X]; } public float getY() { return this.mValues[SensorManager.DATA_Y]; } public float getZ() { return this.mValues[SensorManager.DATA_Z]; } public void setX(final float pX) { this.mValues[SensorManager.DATA_X] = pX; } public void setY(final float pY) { this.mValues[SensorManager.DATA_Y] = pY; } public void setZ(final float pZ) { this.mValues[SensorManager.DATA_Z] = pZ; } @Override public void setValues(final float[] pValues) { super.setValues(pValues); AccelerometerData.AXISSWAPS[this.mDisplayRotation].swapAxis(this.mValues); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Accelerometer: " + Arrays.toString(this.mValues); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== private static interface IAxisSwap { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void swapAxis(final float[] pValues); } }
Java
package org.anddev.andengine.sensor.accelerometer; import org.anddev.andengine.sensor.SensorDelay; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:10:34 - 31.10.2010 */ public class AccelerometerSensorOptions { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== final SensorDelay mSensorDelay; // =========================================================== // Constructors // =========================================================== public AccelerometerSensorOptions(final SensorDelay pSensorDelay) { this.mSensorDelay = pSensorDelay; } // =========================================================== // Getter & Setter // =========================================================== public SensorDelay getSensorDelay() { return this.mSensorDelay; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui.dialog; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.widget.EditText; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 09:35:55 - 14.12.2009 */ public abstract class GenericInputDialogBuilder<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final Callback<T> mSuccessCallback; protected final OnCancelListener mOnCancelListener; protected final int mTitleResID; protected final int mMessageResID; protected final int mIconResID; protected final Context mContext; private final int mErrorResID; private final String mDefaultText; // =========================================================== // Constructors // =========================================================== public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback<T> pSuccessCallback, final OnCancelListener pOnCancelListener){ this(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, "", pSuccessCallback, pOnCancelListener); } public GenericInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback<T> pSuccessCallback, final OnCancelListener pOnCancelListener){ this.mContext = pContext; this.mTitleResID = pTitleResID; this.mMessageResID = pMessageResID; this.mErrorResID = pErrorResID; this.mIconResID = pIconResID; this.mDefaultText = pDefaultText; this.mSuccessCallback = pSuccessCallback; this.mOnCancelListener = pOnCancelListener; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract T generateResult(final String pInput); // =========================================================== // Methods // =========================================================== public Dialog create() { final EditText etInput = new EditText(this.mContext); etInput.setText(this.mDefaultText); final AlertDialog.Builder ab = new AlertDialog.Builder(this.mContext); if(this.mTitleResID != 0) { ab.setTitle(this.mTitleResID); } if(this.mMessageResID != 0) { ab.setMessage(this.mMessageResID); } if(this.mIconResID != 0) { ab.setIcon(this.mIconResID); } this.setView(ab, etInput); ab.setOnCancelListener(this.mOnCancelListener) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { final T result; try{ result = GenericInputDialogBuilder.this.generateResult(etInput.getText().toString()); } catch (final IllegalArgumentException e) { Debug.e("Error in GenericInputDialogBuilder.generateResult()", e); Toast.makeText(GenericInputDialogBuilder.this.mContext, GenericInputDialogBuilder.this.mErrorResID, Toast.LENGTH_SHORT).show(); return; } GenericInputDialogBuilder.this.mSuccessCallback.onCallback(result); pDialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { GenericInputDialogBuilder.this.mOnCancelListener.onCancel(pDialog); pDialog.dismiss(); } }); return ab.create(); } protected void setView(final AlertDialog.Builder pBuilder, final EditText pInputEditText) { pBuilder.setView(pInputEditText); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui.dialog; import org.anddev.andengine.util.Callback; import android.content.Context; import android.content.DialogInterface.OnCancelListener; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 09:46:00 - 14.12.2009 */ public class StringInputDialogBuilder extends GenericInputDialogBuilder<String> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final Callback<String> pSuccessCallback, final OnCancelListener pOnCancelListener) { super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pSuccessCallback, pOnCancelListener); } public StringInputDialogBuilder(final Context pContext, final int pTitleResID, final int pMessageResID, final int pErrorResID, final int pIconResID, final String pDefaultText, final Callback<String> pSuccessCallback, final OnCancelListener pOnCancelListener) { super(pContext, pTitleResID, pMessageResID, pErrorResID, pIconResID, pDefaultText, pSuccessCallback, pOnCancelListener); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected String generateResult(final String pInput) { return pInput; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.entity.scene.Scene; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:03:08 - 14.03.2010 */ public interface IGameInterface { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public Engine onLoadEngine(); public void onLoadResources(); public void onUnloadResources(); public Scene onLoadScene(); public void onLoadComplete(); public void onPauseGame(); public void onResumeGame(); }
Java
package org.anddev.andengine.ui.activity; import java.util.concurrent.Callable; import org.anddev.andengine.util.ActivityUtils; import org.anddev.andengine.util.AsyncCallable; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.progress.ProgressCallable; import android.app.Activity; import android.app.ProgressDialog; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:35:28 - 29.08.2009 */ public abstract class BaseActivity extends Activity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * Performs a task in the background, showing a {@link ProgressDialog}, * while the {@link Callable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pCallable * @param pCallback */ protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback) { this.doAsync(pTitleResID, pMessageResID, pCallable, pCallback, null); } /** * Performs a task in the background, showing a indeterminate {@link ProgressDialog}, * while the {@link Callable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback); } /** * Performs a task in the background, showing a {@link ProgressDialog} with an ProgressBar, * while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pAsyncCallable * @param pCallback */ protected <T> void doProgressAsync(final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) { this.doProgressAsync(pTitleResID, pCallable, pCallback, null); } /** * Performs a task in the background, showing a {@link ProgressDialog} with a ProgressBar, * while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pAsyncCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doProgressAsync(final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doProgressAsync(this, pTitleResID, pCallable, pCallback, pExceptionCallback); } /** * Performs a task in the background, showing an indeterminate {@link ProgressDialog}, * while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResID * @param pMessageResID * @param pErrorMessageResID * @param pAsyncCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doAsync(final int pTitleResID, final int pMessageResID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doAsync(this, pTitleResID, pMessageResID, pAsyncCallable, pCallback, pExceptionCallback); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class CancelledException extends Exception { private static final long serialVersionUID = -78123211381435596L; } }
Java
package org.anddev.andengine.ui.activity; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.IResolutionPolicy; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.SplashScene; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.bitmap.BitmapTexture.BitmapTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.app.Activity; import android.content.Intent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 08:25:31 - 03.05.2010 */ public abstract class BaseSplashActivity extends BaseGameActivity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Camera mCamera; private IBitmapTextureAtlasSource mSplashTextureAtlasSource; private TextureRegion mLoadingScreenTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract ScreenOrientation getScreenOrientation(); protected abstract IBitmapTextureAtlasSource onGetSplashTextureAtlasSource(); protected abstract float getSplashDuration(); protected abstract Class<? extends Activity> getFollowUpActivity(); protected float getSplashScaleFrom() { return 1f; } protected float getSplashScaleTo() { return 1f; } @Override public void onLoadComplete() { } @Override public Engine onLoadEngine() { this.mSplashTextureAtlasSource = this.onGetSplashTextureAtlasSource(); final int width = this.mSplashTextureAtlasSource.getWidth(); final int height = this.mSplashTextureAtlasSource.getHeight(); this.mCamera = this.getSplashCamera(width, height); return new Engine(new EngineOptions(true, this.getScreenOrientation(), this.getSplashResolutionPolicy(width, height), this.mCamera)); } @Override public void onLoadResources() { final BitmapTextureAtlas loadingScreenBitmapTextureAtlas = BitmapTextureAtlasFactory.createForTextureAtlasSourceSize(BitmapTextureFormat.RGBA_8888, this.mSplashTextureAtlasSource, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mLoadingScreenTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(loadingScreenBitmapTextureAtlas, this.mSplashTextureAtlasSource, 0, 0); this.getEngine().getTextureManager().loadTexture(loadingScreenBitmapTextureAtlas); } @Override public Scene onLoadScene() { final float splashDuration = this.getSplashDuration(); final SplashScene splashScene = new SplashScene(this.mCamera, this.mLoadingScreenTextureRegion, splashDuration, this.getSplashScaleFrom(), this.getSplashScaleTo()); splashScene.registerUpdateHandler(new TimerHandler(splashDuration, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseSplashActivity.this.startActivity(new Intent(BaseSplashActivity.this, BaseSplashActivity.this.getFollowUpActivity())); BaseSplashActivity.this.finish(); } })); return splashScene; } // =========================================================== // Methods // =========================================================== protected Camera getSplashCamera(final int pSplashwidth, final int pSplashHeight) { return new Camera(0, 0, pSplashwidth, pSplashHeight); } protected IResolutionPolicy getSplashResolutionPolicy(final int pSplashwidth, final int pSplashHeight) { return new RatioResolutionPolicy(pSplashwidth, pSplashHeight); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui.activity; import org.anddev.andengine.audio.music.MusicManager; import org.anddev.andengine.audio.sound.SoundManager; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.WakeLockOptions; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.opengl.font.FontManager; import org.anddev.andengine.opengl.texture.TextureManager; import org.anddev.andengine.opengl.view.RenderSurfaceView; import org.anddev.andengine.sensor.accelerometer.AccelerometerSensorOptions; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.sensor.location.ILocationListener; import org.anddev.andengine.sensor.location.LocationSensorOptions; import org.anddev.andengine.sensor.orientation.IOrientationListener; import org.anddev.andengine.sensor.orientation.OrientationSensorOptions; import org.anddev.andengine.ui.IGameInterface; import org.anddev.andengine.util.ActivityUtils; import org.anddev.andengine.util.Debug; import android.content.Context; import android.content.pm.ActivityInfo; import android.media.AudioManager; import android.os.Bundle; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.view.Gravity; import android.widget.FrameLayout.LayoutParams; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:27:06 - 08.03.2010 */ public abstract class BaseGameActivity extends BaseActivity implements IGameInterface { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected Engine mEngine; private WakeLock mWakeLock; protected RenderSurfaceView mRenderSurfaceView; protected boolean mHasWindowFocused; private boolean mPaused; private boolean mGameLoaded; // =========================================================== // Constructors // =========================================================== @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.mPaused = true; this.mEngine = this.onLoadEngine(); this.applyEngineOptions(this.mEngine.getEngineOptions()); this.onSetContentView(); } @Override protected void onResume() { super.onResume(); if(this.mPaused && this.mHasWindowFocused) { this.doResume(); } } @Override public void onWindowFocusChanged(final boolean pHasWindowFocus) { super.onWindowFocusChanged(pHasWindowFocus); if(pHasWindowFocus) { if(this.mPaused) { this.doResume(); } this.mHasWindowFocused = true; } else { if(!this.mPaused) { this.doPause(); } this.mHasWindowFocused = false; } } @Override protected void onPause() { super.onPause(); if(!this.mPaused) { this.doPause(); } } @Override protected void onDestroy() { super.onDestroy(); this.mEngine.interruptUpdateThread(); this.onUnloadResources(); } @Override public void onUnloadResources() { if(this.mEngine.getEngineOptions().needsMusic()) { this.getMusicManager().releaseAll(); } if(this.mEngine.getEngineOptions().needsSound()) { this.getSoundManager().releaseAll(); } } // =========================================================== // Getter & Setter // =========================================================== public Engine getEngine() { return this.mEngine; } public TextureManager getTextureManager() { return this.mEngine.getTextureManager(); } public FontManager getFontManager() { return this.getFontManager(); } public SoundManager getSoundManager() { return this.mEngine.getSoundManager(); } public MusicManager getMusicManager() { return this.mEngine.getMusicManager(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onResumeGame() { } @Override public void onPauseGame() { } // =========================================================== // Methods // =========================================================== private void doResume() { if(!this.mGameLoaded) { this.onLoadResources(); final Scene scene = this.onLoadScene(); this.mEngine.onLoadComplete(scene); this.onLoadComplete(); this.mGameLoaded = true; } this.mPaused = false; this.acquireWakeLock(this.mEngine.getEngineOptions().getWakeLockOptions()); this.mEngine.onResume(); this.mRenderSurfaceView.onResume(); this.mEngine.start(); this.onResumeGame(); } private void doPause() { this.mPaused = true; this.releaseWakeLock(); this.mEngine.onPause(); this.mEngine.stop(); this.mRenderSurfaceView.onPause(); this.onPauseGame(); } public void runOnUpdateThread(final Runnable pRunnable) { this.mEngine.runOnUpdateThread(pRunnable); } protected void onSetContentView() { this.mRenderSurfaceView = new RenderSurfaceView(this); this.mRenderSurfaceView.setEGLConfigChooser(false); this.mRenderSurfaceView.setRenderer(this.mEngine); this.setContentView(this.mRenderSurfaceView, this.createSurfaceViewLayoutParams()); } private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) { if(pWakeLockOptions == WakeLockOptions.SCREEN_ON) { ActivityUtils.keepScreenOn(this); } else { final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); this.mWakeLock = pm.newWakeLock(pWakeLockOptions.getFlag() | PowerManager.ON_AFTER_RELEASE, "AndEngine"); try { this.mWakeLock.acquire(); } catch (final SecurityException e) { Debug.e("You have to add\n\t<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>\nto your AndroidManifest.xml !", e); } } } private void releaseWakeLock() { if(this.mWakeLock != null && this.mWakeLock.isHeld()) { this.mWakeLock.release(); } } private void applyEngineOptions(final EngineOptions pEngineOptions) { if(pEngineOptions.isFullscreen()) { ActivityUtils.requestFullscreen(this); } if(pEngineOptions.needsMusic() || pEngineOptions.needsSound()) { this.setVolumeControlStream(AudioManager.STREAM_MUSIC); } switch(pEngineOptions.getScreenOrientation()) { case LANDSCAPE: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case PORTRAIT: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; } } protected LayoutParams createSurfaceViewLayoutParams() { final LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layoutParams.gravity = Gravity.CENTER; return layoutParams; } protected void enableVibrator() { this.mEngine.enableVibrator(this); } /** * @see {@link Engine#enableLocationSensor(Context, ILocationListener, LocationSensorOptions)} */ protected void enableLocationSensor(final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions) { this.mEngine.enableLocationSensor(this, pLocationListener, pLocationSensorOptions); } /** * @see {@link Engine#disableLocationSensor(Context)} */ protected void disableLocationSensor() { this.mEngine.disableLocationSensor(this); } /** * @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener)} */ protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener) { return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener); } /** * @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener, AccelerometerSensorOptions)} */ protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener, final AccelerometerSensorOptions pAccelerometerSensorOptions) { return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener, pAccelerometerSensorOptions); } /** * @see {@link Engine#disableAccelerometerSensor(Context)} */ protected boolean disableAccelerometerSensor() { return this.mEngine.disableAccelerometerSensor(this); } /** * @see {@link Engine#enableOrientationSensor(Context, IOrientationListener)} */ protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener) { return this.mEngine.enableOrientationSensor(this, pOrientationListener); } /** * @see {@link Engine#enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)} */ protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener, final OrientationSensorOptions pLocationSensorOptions) { return this.mEngine.enableOrientationSensor(this, pOrientationListener, pLocationSensorOptions); } /** * @see {@link Engine#disableOrientationSensor(Context)} */ protected boolean disableOrientationSensor() { return this.mEngine.disableOrientationSensor(this); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.ui.activity; import org.anddev.andengine.opengl.view.RenderSurfaceView; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:18:50 - 06.10.2010 */ public abstract class LayoutGameActivity extends BaseGameActivity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract int getLayoutID(); protected abstract int getRenderSurfaceViewID(); @Override protected void onSetContentView() { super.setContentView(this.getLayoutID()); this.mRenderSurfaceView = (RenderSurfaceView) this.findViewById(this.getRenderSurfaceViewID()); this.mRenderSurfaceView.setEGLConfigChooser(false); this.mRenderSurfaceView.setRenderer(this.mEngine); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.collision; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:50:19 - 11.03.2010 */ public class BaseCollisionChecker { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkAxisAlignedRectangleCollision(final float pLeftA, final float pTopA, final float pRightA, final float pBottomA, final float pLeftB, final float pTopB, final float pRightB, final float pBottomB) { return (pLeftA < pRightB && pLeftB < pRightA && pTopA < pBottomB && pTopB < pBottomA); } /** * Returns an indicator of where the specified point (PX,&nbsp;PY) lies with * respect to the line segment from (X1,&nbsp;Y1) to (X2,&nbsp;Y2). The * return value can be either 1, -1, or 0 and indicates in which direction * the specified line must pivot around its first endpoint, (X1,&nbsp;Y1), * in order to point at the specified point (PX,&nbsp;PY). * <p> * A return value of 1 indicates that the line segment must turn in the * direction that takes the positive X axis towards the negative Y axis. In * the default coordinate system used by Java 2D, this direction is * counterclockwise. * <p> * A return value of -1 indicates that the line segment must turn in the * direction that takes the positive X axis towards the positive Y axis. In * the default coordinate system, this direction is clockwise. * <p> * A return value of 0 indicates that the point lies exactly on the line * segment. Note that an indicator value of 0 is rare and not useful for * determining colinearity because of floating point rounding issues. * <p> * If the point is colinear with the line segment, but not between the * endpoints, then the value will be -1 if the point lies * "beyond (X1,&nbsp;Y1)" or 1 if the point lies "beyond (X2,&nbsp;Y2)". * * @param pX1 * ,&nbsp;Y1 the coordinates of the beginning of the specified * line segment * @param pX2 * ,&nbsp;Y2 the coordinates of the end of the specified line * segment * @param pPX * ,&nbsp;PY the coordinates of the specified point to be * compared with the specified line segment * @return an integer that indicates the position of the third specified * coordinates with respect to the line segment formed by the first * two specified coordinates. */ public static int relativeCCW(final float pX1, final float pY1, float pX2, float pY2, float pPX, float pPY) { pX2 -= pX1; pY2 -= pY1; pPX -= pX1; pPY -= pY1; float ccw = pPX * pY2 - pPY * pX2; if (ccw == 0.0f) { // The point is colinear, classify based on which side of // the segment the point falls on. We can calculate a // relative value using the projection of PX,PY onto the // segment - a negative value indicates the point projects // outside of the segment in the direction of the particular // endpoint used as the origin for the projection. ccw = pPX * pX2 + pPY * pY2; if (ccw > 0.0f) { // Reverse the projection to be relative to the original X2,Y2 // X2 and Y2 are simply negated. // PX and PY need to have (X2 - X1) or (Y2 - Y1) subtracted // from them (based on the original values) // Since we really want to get a positive answer when the // point is "beyond (X2,Y2)", then we want to calculate // the inverse anyway - thus we leave X2 & Y2 negated. pPX -= pX2; pPY -= pY2; ccw = pPX * pX2 + pPY * pY2; if (ccw < 0.0f) { ccw = 0.0f; } } } return (ccw < 0.0f) ? -1 : ((ccw > 0.0f) ? 1 : 0); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.collision; import org.anddev.andengine.util.constants.Constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:50:19 - 11.03.2010 */ public class ShapeCollisionChecker extends BaseCollisionChecker { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkCollision(final int pVerticesALength, final float[] pVerticesA, final int pVerticesBLength, final float[] pVerticesB) { /* Check all the lines of A ... */ for(int a = pVerticesALength - 4; a >= 0; a -= 2) { /* ... against all lines in B. */ if(ShapeCollisionChecker.checkCollisionSub(a, a + 2, pVerticesA, pVerticesB, pVerticesBLength)){ return true; } } /* Also check the 'around the corner of the array' line of A against all lines in B. */ if(ShapeCollisionChecker.checkCollisionSub(pVerticesALength - 2, 0, pVerticesA, pVerticesB, pVerticesBLength)){ return true; } else { /* At last check if one polygon 'contains' the other one by checking * if one vertex of the one vertices is contained by all of the other vertices. */ if(ShapeCollisionChecker.checkContains(pVerticesA, pVerticesALength, pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])) { return true; } else if(ShapeCollisionChecker.checkContains(pVerticesB, pVerticesBLength, pVerticesA[Constants.VERTEX_INDEX_X], pVerticesA[Constants.VERTEX_INDEX_Y])) { return true; } else { return false; } } } /** * Checks line specified by pVerticesA[pVertexIndexA1] and pVerticesA[pVertexIndexA2] against all lines in pVerticesB. */ private static boolean checkCollisionSub(final int pVertexIndexA1, final int pVertexIndexA2, final float[] pVerticesA, final float[] pVerticesB, final int pVerticesBLength) { /* Check against all the lines of B. */ final float vertexA1X = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_X]; final float vertexA1Y = pVerticesA[pVertexIndexA1 + Constants.VERTEX_INDEX_Y]; final float vertexA2X = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_X]; final float vertexA2Y = pVerticesA[pVertexIndexA2 + Constants.VERTEX_INDEX_Y]; for(int b = pVerticesBLength - 4; b >= 0; b -= 2) { if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[b + Constants.VERTEX_INDEX_X], pVerticesB[b + Constants.VERTEX_INDEX_Y], pVerticesB[b + 2 + Constants.VERTEX_INDEX_X], pVerticesB[b + 2 + Constants.VERTEX_INDEX_Y])){ return true; } } /* Also check the 'around the corner of the array' line of B. */ if(LineCollisionChecker.checkLineCollision(vertexA1X, vertexA1Y, vertexA2X, vertexA2Y, pVerticesB[pVerticesBLength - 2], pVerticesB[pVerticesBLength - 1], pVerticesB[Constants.VERTEX_INDEX_X], pVerticesB[Constants.VERTEX_INDEX_Y])){ return true; } return false; } public static boolean checkContains(final float[] pVertices, final int pVerticesLength, final float pX, final float pY) { int edgeResultSum = 0; for(int i = pVerticesLength - 4; i >= 0; i -= 2) { final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[i], pVertices[i + 1], pVertices[i + 2], pVertices[i + 3], pX, pY); if(edgeResult == 0) { return true; } else { edgeResultSum += edgeResult; } } /* Also check the 'around the corner of the array' line. */ final int edgeResult = BaseCollisionChecker.relativeCCW(pVertices[pVerticesLength - 2], pVertices[pVerticesLength - 1], pVertices[Constants.VERTEX_INDEX_X], pVertices[Constants.VERTEX_INDEX_Y], pX, pY); if(edgeResult == 0){ return true; } else { edgeResultSum += edgeResult; } final int vertexCount = pVerticesLength / 2; /* Point is not on the edge, so check if the edge is on the same side(left or right) of all edges. */ return edgeResultSum == vertexCount || edgeResultSum == -vertexCount ; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.collision; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import org.anddev.andengine.entity.primitive.Line; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:27:22 - 17.07.2010 */ public class LineCollisionChecker extends ShapeCollisionChecker { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkLineCollision(final float pX1, final float pY1, final float pX2, final float pY2, final float pX3, final float pY3, final float pX4, final float pY4) { return ((BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX3, pY3) * BaseCollisionChecker.relativeCCW(pX1, pY1, pX2, pY2, pX4, pY4) <= 0) && (BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX1, pY1) * BaseCollisionChecker.relativeCCW(pX3, pY3, pX4, pY4, pX2, pY2) <= 0)); } public static void fillVertices(final Line pLine, final float[] pVertices) { pVertices[0 + VERTEX_INDEX_X] = 0; pVertices[0 + VERTEX_INDEX_Y] = 0; pVertices[2 + VERTEX_INDEX_X] = pLine.getX2() - pLine.getX1(); pVertices[2 + VERTEX_INDEX_Y] = pLine.getY2() - pLine.getY1(); pLine.getLocalToSceneTransformation().transform(pVertices); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.collision; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.shape.RectangularShape; import org.anddev.andengine.util.MathUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:50:19 - 11.03.2010 */ public class RectangularShapeCollisionChecker extends ShapeCollisionChecker { // =========================================================== // Constants // =========================================================== private static final int RECTANGULARSHAPE_VERTEX_COUNT = 4; private static final int LINE_VERTEX_COUNT = 2; private static final float[] VERTICES_CONTAINS_TMP = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; private static final float[] VERTICES_COLLISION_TMP_A = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; private static final float[] VERTICES_COLLISION_TMP_B = new float[2 * RECTANGULARSHAPE_VERTEX_COUNT]; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static boolean checkContains(final RectangularShape pRectangularShape, final float pX, final float pY) { RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_CONTAINS_TMP); return ShapeCollisionChecker.checkContains(VERTICES_CONTAINS_TMP, 2 * RECTANGULARSHAPE_VERTEX_COUNT, pX, pY); } public static boolean isVisible(final Camera pCamera, final RectangularShape pRectangularShape) { RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static boolean isVisible(final Camera pCamera, final Line pLine) { RectangularShapeCollisionChecker.fillVertices(pCamera, VERTICES_COLLISION_TMP_A); LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static boolean checkCollision(final RectangularShape pRectangularShapeA, final RectangularShape pRectangularShapeB) { RectangularShapeCollisionChecker.fillVertices(pRectangularShapeA, VERTICES_COLLISION_TMP_A); RectangularShapeCollisionChecker.fillVertices(pRectangularShapeB, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static boolean checkCollision(final RectangularShape pRectangularShape, final Line pLine) { RectangularShapeCollisionChecker.fillVertices(pRectangularShape, VERTICES_COLLISION_TMP_A); LineCollisionChecker.fillVertices(pLine, VERTICES_COLLISION_TMP_B); return ShapeCollisionChecker.checkCollision(2 * RECTANGULARSHAPE_VERTEX_COUNT, VERTICES_COLLISION_TMP_A, 2 * LINE_VERTEX_COUNT, VERTICES_COLLISION_TMP_B); } public static void fillVertices(final RectangularShape pRectangularShape, final float[] pVertices) { final float left = 0; final float top = 0; final float right = pRectangularShape.getWidth(); final float bottom = pRectangularShape.getHeight(); pVertices[0 + VERTEX_INDEX_X] = left; pVertices[0 + VERTEX_INDEX_Y] = top; pVertices[2 + VERTEX_INDEX_X] = right; pVertices[2 + VERTEX_INDEX_Y] = top; pVertices[4 + VERTEX_INDEX_X] = right; pVertices[4 + VERTEX_INDEX_Y] = bottom; pVertices[6 + VERTEX_INDEX_X] = left; pVertices[6 + VERTEX_INDEX_Y] = bottom; pRectangularShape.getLocalToSceneTransformation().transform(pVertices); } private static void fillVertices(final Camera pCamera, final float[] pVertices) { pVertices[0 + VERTEX_INDEX_X] = pCamera.getMinX(); pVertices[0 + VERTEX_INDEX_Y] = pCamera.getMinY(); pVertices[2 + VERTEX_INDEX_X] = pCamera.getMaxX(); pVertices[2 + VERTEX_INDEX_Y] = pCamera.getMinY(); pVertices[4 + VERTEX_INDEX_X] = pCamera.getMaxX(); pVertices[4 + VERTEX_INDEX_Y] = pCamera.getMaxY(); pVertices[6 + VERTEX_INDEX_X] = pCamera.getMinX(); pVertices[6 + VERTEX_INDEX_Y] = pCamera.getMaxY(); MathUtils.rotateAroundCenter(pVertices, pCamera.getRotation(), pCamera.getCenterX(), pCamera.getCenterY()); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:02:06 - 13.06.2010 */ public interface IAudioManager<T extends IAudioEntity> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public float getMasterVolume(); public void setMasterVolume(final float pMasterVolume); public void add(final T pAudioEntity); public void releaseAll(); }
Java
package org.anddev.andengine.audio; import java.util.ArrayList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:07:02 - 13.06.2010 */ public abstract class BaseAudioManager<T extends IAudioEntity> implements IAudioManager<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final ArrayList<T> mAudioEntities = new ArrayList<T>(); protected float mMasterVolume = 1.0f; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getMasterVolume() { return this.mMasterVolume; } @Override public void setMasterVolume(final float pMasterVolume) { this.mMasterVolume = pMasterVolume; final ArrayList<T> audioEntities = this.mAudioEntities; for(int i = audioEntities.size() - 1; i >= 0; i--) { final T audioEntity = audioEntities.get(i); audioEntity.onMasterVolumeChanged(pMasterVolume); } } @Override public void add(final T pAudioEntity) { this.mAudioEntities.add(pAudioEntity); } @Override public void releaseAll() { final ArrayList<T> audioEntities = this.mAudioEntities; for(int i = audioEntities.size() - 1; i >= 0; i--) { final T audioEntity = audioEntities.get(i); audioEntity.stop(); audioEntity.release(); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import org.anddev.andengine.audio.BaseAudioEntity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:22:15 - 11.03.2010 */ public class Sound extends BaseAudioEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mSoundID; private int mStreamID = 0; private int mLoopCount = 0; private float mRate = 1.0f; // =========================================================== // Constructors // =========================================================== Sound(final SoundManager pSoundManager, final int pSoundID) { super(pSoundManager); this.mSoundID = pSoundID; } // =========================================================== // Getter & Setter // =========================================================== public void setLoopCount(final int pLoopCount) { this.mLoopCount = pLoopCount; if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().setLoop(this.mStreamID, pLoopCount); } } public void setRate(final float pRate) { this.mRate = pRate; if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().setRate(this.mStreamID, pRate); } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override protected SoundManager getAudioManager() { return (SoundManager)super.getAudioManager(); } @Override public void play() { final float masterVolume = this.getMasterVolume(); final float leftVolume = this.mLeftVolume * masterVolume; final float rightVolume = this.mRightVolume * masterVolume; this.mStreamID = this.getAudioManager().getSoundPool().play(this.mSoundID, leftVolume, rightVolume, 1, this.mLoopCount, this.mRate); } @Override public void stop() { if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().stop(this.mStreamID); } } @Override public void resume() { if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().resume(this.mStreamID); } } @Override public void pause() { if(this.mStreamID != 0) { this.getAudioManager().getSoundPool().pause(this.mStreamID); } } @Override public void release() { } @Override public void setLooping(final boolean pLooping) { this.setLoopCount((pLooping) ? -1 : 0); } @Override public void setVolume(final float pLeftVolume, final float pRightVolume) { super.setVolume(pLeftVolume, pRightVolume); if(this.mStreamID != 0){ final float masterVolume = this.getMasterVolume(); final float leftVolume = this.mLeftVolume * masterVolume; final float rightVolume = this.mRightVolume * masterVolume; this.getAudioManager().getSoundPool().setVolume(this.mStreamID, leftVolume, rightVolume); } } @Override public void onMasterVolumeChanged(final float pMasterVolume) { this.setVolume(this.mLeftVolume, this.mRightVolume); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import java.io.FileDescriptor; import java.io.IOException; import android.content.Context; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:23:03 - 11.03.2010 */ public class SoundFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static String sAssetBasePath = ""; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== /** * @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>. */ public static void setAssetBasePath(final String pAssetBasePath) { if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { SoundFactory.sAssetBasePath = pAssetBasePath; } else { throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); } } public static void reset() { SoundFactory.setAssetBasePath(""); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static Sound createSoundFromPath(final SoundManager pSoundManager, final String pPath) throws IOException { final int soundID = pSoundManager.getSoundPool().load(pPath, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } public static Sound createSoundFromAsset(final SoundManager pSoundManager, final Context pContext, final String pAssetPath) throws IOException { final int soundID = pSoundManager.getSoundPool().load(pContext.getAssets().openFd(SoundFactory.sAssetBasePath + pAssetPath), 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } public static Sound createSoundFromResource(final SoundManager pSoundManager, final Context pContext, final int pSoundResID) { final int soundID = pSoundManager.getSoundPool().load(pContext, pSoundResID, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } public static Sound createSoundFromFileDescriptor(final SoundManager pSoundManager, final FileDescriptor pFileDescriptor, final long pOffset, final long pLength) throws IOException { final int soundID = pSoundManager.getSoundPool().load(pFileDescriptor, pOffset, pLength, 1); final Sound sound = new Sound(pSoundManager, soundID); pSoundManager.add(sound); return sound; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import org.anddev.andengine.util.Library; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:41:56 - 20.08.2010 */ public class SoundLibrary extends Library<Sound> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.sound; import org.anddev.andengine.audio.BaseAudioManager; import android.media.AudioManager; import android.media.SoundPool; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:22:59 - 11.03.2010 */ public class SoundManager extends BaseAudioManager<Sound> { // =========================================================== // Constants // =========================================================== private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5; // =========================================================== // Fields // =========================================================== private final SoundPool mSoundPool; // =========================================================== // Constructors // =========================================================== public SoundManager() { this(MAX_SIMULTANEOUS_STREAMS_DEFAULT); } public SoundManager(final int pMaxSimultaneousStreams) { this.mSoundPool = new SoundPool(pMaxSimultaneousStreams, AudioManager.STREAM_MUSIC, 0); } // =========================================================== // Getter & Setter // =========================================================== SoundPool getSoundPool() { return this.mSoundPool; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override public void releaseAll() { super.releaseAll(); this.mSoundPool.release(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:35:37 - 13.06.2010 */ public abstract class BaseAudioEntity implements IAudioEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final IAudioManager<? extends IAudioEntity> mAudioManager; protected float mLeftVolume = 1.0f; protected float mRightVolume = 1.0f; // =========================================================== // Constructors // =========================================================== public BaseAudioEntity(final IAudioManager<? extends IAudioEntity> pAudioManager) { this.mAudioManager = pAudioManager; } // =========================================================== // Getter & Setter // =========================================================== protected IAudioManager<? extends IAudioEntity> getAudioManager() { return this.mAudioManager; } public float getActualLeftVolume() { return this.mLeftVolume * this.getMasterVolume(); } public float getActualRightVolume() { return this.mRightVolume * this.getMasterVolume(); } protected float getMasterVolume() { return this.mAudioManager.getMasterVolume(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getVolume() { return (this.mLeftVolume + this.mRightVolume) * 0.5f; } @Override public float getLeftVolume() { return this.mLeftVolume; } @Override public float getRightVolume() { return this.mRightVolume; } @Override public final void setVolume(final float pVolume) { this.setVolume(pVolume, pVolume); } @Override public void setVolume(final float pLeftVolume, final float pRightVolume) { this.mLeftVolume = pLeftVolume; this.mRightVolume = pRightVolume; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:53:29 - 13.06.2010 */ public interface IAudioEntity { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void play(); public void pause(); public void resume(); public void stop(); public float getVolume(); public void setVolume(final float pVolume); public float getLeftVolume(); public float getRightVolume(); public void setVolume(final float pLeftVolume, final float pRightVolume); public void onMasterVolumeChanged(final float pMasterVolume); public void setLooping(final boolean pLooping); public void release(); }
Java
package org.anddev.andengine.audio.music; import org.anddev.andengine.audio.BaseAudioEntity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:53:12 - 13.06.2010 */ public class Music extends BaseAudioEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final MediaPlayer mMediaPlayer; // =========================================================== // Constructors // =========================================================== Music(final MusicManager pMusicManager, final MediaPlayer pMediaPlayer) { super(pMusicManager); this.mMediaPlayer = pMediaPlayer; } // =========================================================== // Getter & Setter // =========================================================== public boolean isPlaying() { return this.mMediaPlayer.isPlaying(); } public MediaPlayer getMediaPlayer() { return this.mMediaPlayer; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected MusicManager getAudioManager() { return (MusicManager)super.getAudioManager(); } @Override public void play() { this.mMediaPlayer.start(); } @Override public void stop() { this.mMediaPlayer.stop(); } @Override public void resume() { this.mMediaPlayer.start(); } @Override public void pause() { this.mMediaPlayer.pause(); } @Override public void release() { this.mMediaPlayer.release(); } @Override public void setLooping(final boolean pLooping) { this.mMediaPlayer.setLooping(pLooping); } @Override public void setVolume(final float pLeftVolume, final float pRightVolume) { super.setVolume(pLeftVolume, pRightVolume); final float masterVolume = this.getAudioManager().getMasterVolume(); final float actualLeftVolume = pLeftVolume * masterVolume; final float actualRightVolume = pRightVolume * masterVolume; this.mMediaPlayer.setVolume(actualLeftVolume, actualRightVolume); } @Override public void onMasterVolumeChanged(final float pMasterVolume) { this.setVolume(this.mLeftVolume, this.mRightVolume); } // =========================================================== // Methods // =========================================================== public void seekTo(final int pMilliseconds) { this.mMediaPlayer.seekTo(pMilliseconds); } public void setOnCompletionListener(final OnCompletionListener pOnCompletionListener) { this.mMediaPlayer.setOnCompletionListener(pOnCompletionListener); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.music; import org.anddev.andengine.audio.BaseAudioManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:01:23 - 13.06.2010 */ public class MusicManager extends BaseAudioManager<Music> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public MusicManager() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.audio.music; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:05:49 - 13.06.2010 */ public class MusicFactory { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static String sAssetBasePath = ""; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== /** * @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>. */ public static void setAssetBasePath(final String pAssetBasePath) { if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { MusicFactory.sAssetBasePath = pAssetBasePath; } else { throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); } } public static void reset() { MusicFactory.setAssetBasePath(""); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static Music createMusicFromFile(final MusicManager pMusicManager, final File pFile) throws IOException { final MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(new FileInputStream(pFile).getFD()); mediaPlayer.prepare(); final Music music = new Music(pMusicManager, mediaPlayer); pMusicManager.add(music); return music; } public static Music createMusicFromAsset(final MusicManager pMusicManager, final Context pContext, final String pAssetPath) throws IOException { final MediaPlayer mediaPlayer = new MediaPlayer(); final AssetFileDescriptor assetFileDescritor = pContext.getAssets().openFd(MusicFactory.sAssetBasePath + pAssetPath); mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); mediaPlayer.prepare(); final Music music = new Music(pMusicManager, mediaPlayer); pMusicManager.add(music); return music; } public static Music createMusicFromResource(final MusicManager pMusicManager, final Context pContext, final int pMusicResID) throws IOException { final MediaPlayer mediaPlayer = MediaPlayer.create(pContext, pMusicResID); mediaPlayer.prepare(); final Music music = new Music(pMusicManager, mediaPlayer); pMusicManager.add(music); return music; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:49:25 - 26.07.2010 */ public interface TimeConstants { // =========================================================== // Final Fields // =========================================================== public static final int MONTHSPERYEAR = 12; public static final int DAYSPERWEEK = 7; public static final int DAYSPERMONTH = 30; public static final int HOURSPERDAY = 24; public static final int MINUTESPERHOUR = 60; public static final int MILLISECONDSPERSECOND = 1000; public static final int MICROSECONDSPERSECOND = 1000000; public static final long NANOSECONDSPERSECOND = 1000000000; public static final long MICROSECONDSPERMILLISECOND = MICROSECONDSPERSECOND / MILLISECONDSPERSECOND; public static final long NANOSECONDSPERMICROSECOND = NANOSECONDSPERSECOND / MICROSECONDSPERSECOND; public static final long NANOSECONDSPERMILLISECOND = NANOSECONDSPERSECOND / MILLISECONDSPERSECOND; public static final float SECONDSPERNANOSECOND = 1f / NANOSECONDSPERSECOND; public static final float SECONDSPERMICROSECOND = 1f / MICROSECONDSPERSECOND; public static final float SECONDSPERMILLISECOND = 1f / MILLISECONDSPERSECOND; public static final int SECONDSPERMINUTE = 60; public static final int SECONDSPERHOUR = SECONDSPERMINUTE * MINUTESPERHOUR; public static final int SECONDSPERDAY = SECONDSPERHOUR * HOURSPERDAY; public static final int SECONDSPERWEEK = SECONDSPERDAY * DAYSPERWEEK; public static final int SECONDSPERMONTH = SECONDSPERDAY * DAYSPERMONTH; public static final int SECONDSPERYEAR = SECONDSPERMONTH * MONTHSPERYEAR; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:21:46 - 19.07.2010 */ public interface ColorConstants { // =========================================================== // Final Fields // =========================================================== public static final float COLOR_FACTOR_INT_TO_FLOAT = 255.0f; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:58:20 - 10.01.2011 */ public interface MIMETypes { // =========================================================== // Final Fields // =========================================================== public static final String JPEG = "image/jpeg"; public static final String GIF = "image/gif"; public static final String PNG = "image/png"; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:59:55 - 14.07.2011 */ public interface DataConstants { // =========================================================== // Final Fields // =========================================================== public static final int BITS_PER_BYTE = 8; public static final int BYTES_PER_BYTE = 1; public static final int BYTES_PER_SHORT = Short.SIZE / Byte.SIZE; public static final int BYTES_PER_INT = Integer.SIZE / Byte.SIZE; public static final int BYTES_PER_FLOAT = Float.SIZE / Byte.SIZE; public static final int BYTES_PER_LONG = Long.SIZE / Byte.SIZE; public static final int BYTES_PER_KILOBYTE = 1024; public static final int BYTES_PER_MEGABYTE = 1024 * DataConstants.BYTES_PER_KILOBYTE; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:52:21 - 08.03.2010 */ public interface Constants { // =========================================================== // Final Fields // =========================================================== public static final String DEBUGTAG = "AndEngine"; public static final int VERTEX_INDEX_X = 0; public static final int VERTEX_INDEX_Y = 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:49:25 - 26.07.2010 */ public interface MathConstants { // =========================================================== // Final Fields // =========================================================== public static final float PI = (float) Math.PI; public static float PI_TWICE = PI * 2.0f; public static float PI_HALF = PI * 0.5f; public static final float DEG_TO_RAD = PI / 180.0f; public static final float RAD_TO_DEG = 180.0f / PI; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.util; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Scanner; import java.util.regex.MatchResult; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:50:31 - 14.07.2010 */ public class SystemUtils { // =========================================================== // Constants // =========================================================== private static final String BOGOMIPS_PATTERN = "BogoMIPS[\\s]*:[\\s]*(\\d+\\.\\d+)[\\s]*\n"; private static final String MEMTOTAL_PATTERN = "MemTotal[\\s]*:[\\s]*(\\d+)[\\s]*kB\n"; private static final String MEMFREE_PATTERN = "MemFree[\\s]*:[\\s]*(\\d+)[\\s]*kB\n"; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static int getPackageVersionCode(final Context pContext) { return SystemUtils.getPackageInfo(pContext).versionCode; } public static String getPackageVersionName(final Context pContext) { return SystemUtils.getPackageInfo(pContext).versionName; } private static PackageInfo getPackageInfo(final Context pContext) { try { return pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0); } catch (final NameNotFoundException e) { Debug.e(e); return null; } } public static boolean hasSystemFeature(final Context pContext, final String pFeature) { try { final Method PackageManager_hasSystemFeatures = PackageManager.class.getMethod("hasSystemFeature", new Class[] { String.class }); return (PackageManager_hasSystemFeatures == null) ? false : (Boolean) PackageManager_hasSystemFeatures.invoke(pContext.getPackageManager(), pFeature); } catch (final Throwable t) { return false; } } /** * @param pBuildVersionCode taken from {@link Build.VERSION_CODES}. */ public static boolean isAndroidVersionOrHigher(final int pBuildVersionCode) { return Integer.parseInt(Build.VERSION.SDK) >= pBuildVersionCode; } public static float getCPUBogoMips() throws SystemUtilsException { final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/cpuinfo", BOGOMIPS_PATTERN, 1000); try { if(matchResult.groupCount() > 0) { return Float.parseFloat(matchResult.group(1)); } else { throw new SystemUtilsException(); } } catch (final NumberFormatException e) { throw new SystemUtilsException(e); } } /** * @return in kiloBytes. * @throws SystemUtilsException */ public static int getMemoryTotal() throws SystemUtilsException { final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMTOTAL_PATTERN, 1000); try { if(matchResult.groupCount() > 0) { return Integer.parseInt(matchResult.group(1)); } else { throw new SystemUtilsException(); } } catch (final NumberFormatException e) { throw new SystemUtilsException(e); } } /** * @return in kiloBytes. * @throws SystemUtilsException */ public static int getMemoryFree() throws SystemUtilsException { final MatchResult matchResult = SystemUtils.matchSystemFile("/proc/meminfo", MEMFREE_PATTERN, 1000); try { if(matchResult.groupCount() > 0) { return Integer.parseInt(matchResult.group(1)); } else { throw new SystemUtilsException(); } } catch (final NumberFormatException e) { throw new SystemUtilsException(e); } } /** * @return in kiloHertz. * @throws SystemUtilsException */ public static int getCPUFrequencyCurrent() throws SystemUtilsException { return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ public static int getCPUFrequencyMin() throws SystemUtilsException { return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ public static int getCPUFrequencyMax() throws SystemUtilsException { return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ public static int getCPUFrequencyMinScaling() throws SystemUtilsException { return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"); } /** * @return in kiloHertz. * @throws SystemUtilsException */ public static int getCPUFrequencyMaxScaling() throws SystemUtilsException { return SystemUtils.readSystemFileAsInt("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"); } private static MatchResult matchSystemFile(final String pSystemFile, final String pPattern, final int pHorizon) throws SystemUtilsException { InputStream in = null; try { final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start(); in = process.getInputStream(); final Scanner scanner = new Scanner(in); final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null; if(matchFound) { return scanner.match(); } else { throw new SystemUtilsException(); } } catch (final IOException e) { throw new SystemUtilsException(e); } finally { StreamUtils.close(in); } } private static int readSystemFileAsInt(final String pSystemFile) throws SystemUtilsException { InputStream in = null; try { final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start(); in = process.getInputStream(); final String content = StreamUtils.readFully(in); return Integer.parseInt(content); } catch (final IOException e) { throw new SystemUtilsException(e); } catch (final NumberFormatException e) { throw new SystemUtilsException(e); } finally { StreamUtils.close(in); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class SystemUtilsException extends Exception { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = -7256483361095147596L; // =========================================================== // Methods // =========================================================== public SystemUtilsException() { } public SystemUtilsException(final Throwable pThrowable) { super(pThrowable); } } }
Java
package org.anddev.andengine.util; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.nio.ByteBuffer; import java.util.Scanner; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:48:56 - 03.09.2009 */ public class StreamUtils { // =========================================================== // Constants // =========================================================== public static final int IO_BUFFER_SIZE = 8 * 1024; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static final String readFully(final InputStream pInputStream) throws IOException { final StringBuilder sb = new StringBuilder(); final Scanner sc = new Scanner(pInputStream); while(sc.hasNextLine()) { sb.append(sc.nextLine()); } return sb.toString(); } public static byte[] streamToBytes(final InputStream pInputStream) throws IOException { return StreamUtils.streamToBytes(pInputStream, -1); } public static byte[] streamToBytes(final InputStream pInputStream, final int pReadLimit) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream((pReadLimit == -1) ? IO_BUFFER_SIZE : pReadLimit); StreamUtils.copy(pInputStream, os, pReadLimit); return os.toByteArray(); } public static void copy(final InputStream pInputStream, final OutputStream pOutputStream) throws IOException { StreamUtils.copy(pInputStream, pOutputStream, -1); } public static void copy(final InputStream pInputStream, final byte[] pData) throws IOException { int dataOffset = 0; final byte[] buf = new byte[IO_BUFFER_SIZE]; int read; while((read = pInputStream.read(buf)) != -1) { System.arraycopy(buf, 0, pData, dataOffset, read); dataOffset += read; } } public static void copy(final InputStream pInputStream, final ByteBuffer pByteBuffer) throws IOException { final byte[] buf = new byte[IO_BUFFER_SIZE]; int read; while((read = pInputStream.read(buf)) != -1) { pByteBuffer.put(buf, 0, read); } } /** * Copy the content of the input stream into the output stream, using a temporary * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}. * * @param pInputStream The input stream to copy from. * @param pOutputStream The output stream to copy to. * @param pByteLimit not more than so much bytes to read, or unlimited if smaller than 0. * * @throws IOException If any error occurs during the copy. */ public static void copy(final InputStream pInputStream, final OutputStream pOutputStream, final long pByteLimit) throws IOException { if(pByteLimit < 0) { final byte[] buf = new byte[IO_BUFFER_SIZE]; int read; while((read = pInputStream.read(buf)) != -1) { pOutputStream.write(buf, 0, read); } } else { final byte[] buf = new byte[IO_BUFFER_SIZE]; final int bufferReadLimit = Math.min((int)pByteLimit, IO_BUFFER_SIZE); long pBytesLeftToRead = pByteLimit; int read; while((read = pInputStream.read(buf, 0, bufferReadLimit)) != -1) { if(pBytesLeftToRead > read) { pOutputStream.write(buf, 0, read); pBytesLeftToRead -= read; } else { pOutputStream.write(buf, 0, (int) pBytesLeftToRead); break; } } } pOutputStream.flush(); } public static boolean copyAndClose(final InputStream pInputStream, final OutputStream pOutputStream) { try { StreamUtils.copy(pInputStream, pOutputStream, -1); return true; } catch (final IOException e) { return false; } finally { StreamUtils.close(pInputStream); StreamUtils.close(pOutputStream); } } /** * Closes the specified stream. * * @param pCloseable The stream to close. */ public static void close(final Closeable pCloseable) { if(pCloseable != null) { try { pCloseable.close(); } catch (final IOException e) { e.printStackTrace(); } } } /** * Flushes and closes the specified stream. * * @param pOutputStream The stream to close. */ public static void flushCloseStream(final OutputStream pOutputStream) { if(pOutputStream != null) { try { pOutputStream.flush(); } catch (final IOException e) { e.printStackTrace(); } finally { StreamUtils.close(pOutputStream); } } } /** * Flushes and closes the specified stream. * * @param pWriter The Writer to close. */ public static void flushCloseWriter(final Writer pWriter) { if(pWriter != null) { try { pWriter.flush(); } catch (final IOException e) { e.printStackTrace(); } finally { StreamUtils.close(pWriter); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:55:35 - 08.09.2009 */ public class ViewUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static View inflate(final Context pContext, final int pLayoutID){ return LayoutInflater.from(pContext).inflate(pLayoutID, null); } public static View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){ return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import java.util.ArrayList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:54:24 - 07.11.2010 */ public class ProbabilityGenerator<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mProbabilitySum; private final ArrayList<Entry<T>> mEntries = new ArrayList<Entry<T>>(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void add(final float pFactor, final T ... pElements){ this.mProbabilitySum += pFactor; this.mEntries.add(new Entry<T>(pFactor, pElements)); } public T next() { float random = MathUtils.random(0, this.mProbabilitySum); final ArrayList<Entry<T>> factors = this.mEntries; for(int i = factors.size() - 1; i >= 0; i--){ final Entry<T> entry = factors.get(i); random -= entry.mFactor; if(random <= 0){ return entry.getReturnValue(); } } final Entry<T> lastEntry = factors.get(factors.size() - 1); return lastEntry.getReturnValue(); } public void clear() { this.mProbabilitySum = 0; this.mEntries.clear(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== private static class Entry<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public final float mFactor; public final T[] mData; // =========================================================== // Constructors // =========================================================== public Entry(final float pFactor, final T[] pData){ this.mFactor = pFactor; this.mData = pData; } // =========================================================== // Getter & Setter // =========================================================== public T getReturnValue() { if(this.mData.length == 1){ return this.mData[0]; }else{ return ArrayUtils.random(mData); } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:52:44 - 03.01.2010 */ public interface Callable<T> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * Computes a result, or throws an exception if unable to do so. * * @return the computed result. * @throws Exception if unable to compute a result. */ public T call() throws Exception; }
Java
package org.anddev.andengine.util; import org.anddev.andengine.util.constants.Constants; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:55:12 - 02.08.2010 */ public class SimplePreferences implements Constants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static SharedPreferences INSTANCE; private static Editor EDITORINSTANCE; // =========================================================== // Constructors // =========================================================== public static SharedPreferences getInstance(final Context pContext) { if(SimplePreferences.INSTANCE == null) { SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext); } return SimplePreferences.INSTANCE; } public static Editor getEditorInstance(final Context pContext) { if(SimplePreferences.EDITORINSTANCE == null) { SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit(); } return SimplePreferences.EDITORINSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static int incrementAccessCount(final Context pContext, final String pKey) { return SimplePreferences.incrementAccessCount(pContext, pKey, 1); } public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) { final SharedPreferences prefs = SimplePreferences.getInstance(pContext); final int accessCount = prefs.getInt(pKey, 0); final int newAccessCount = accessCount + pIncrement; prefs.edit().putInt(pKey, newAccessCount).commit(); return newAccessCount; } public static int getAccessCount(final Context pCtx, final String pKey) { return SimplePreferences.getInstance(pCtx).getInt(pKey, 0); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.util.FloatMath; /** * <p>This class is basically a java-space replacement for the native {@link android.graphics.Matrix} class.</p> * * <p>Math taken from <a href="http://www.senocular.com/flash/tutorials/transformmatrix/">senocular.com</a>.</p> * * This class represents an affine transformation with the following matrix: * <pre> [ a , b , 0 ] * [ c , d , 0 ] * [ tx, ty, 1 ]</pre> * where: * <ul> * <li><b>a</b> is the <b>x scale</b></li> * <li><b>b</b> is the <b>y skew</b></li> * <li><b>c</b> is the <b>x skew</b></li> * <li><b>d</b> is the <b>y scale</b></li> * <li><b>tx</b> is the <b>x translation</b></li> * <li><b>ty</b> is the <b>y translation</b></li> * </ul> * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:47:18 - 23.12.2010 */ public class Transformation { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float a = 1.0f; /* x scale */ private float b = 0.0f; /* y skew */ private float c = 0.0f; /* x skew */ private float d = 1.0f; /* y scale */ private float tx = 0.0f; /* x translation */ private float ty = 0.0f; /* y translation */ // =========================================================== // Constructors // =========================================================== public Transformation() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Transformation{[" + this.a + ", " + this.c + ", " + this.tx + "][" + this.b + ", " + this.d + ", " + this.ty + "][0.0, 0.0, 1.0]}"; } // =========================================================== // Methods // =========================================================== public void reset() { this.setToIdentity(); } public void setToIdentity() { this.a = 1.0f; this.d = 1.0f; this.b = 0.0f; this.c = 0.0f; this.tx = 0.0f; this.ty = 0.0f; } public void setTo(final Transformation pTransformation) { this.a = pTransformation.a; this.d = pTransformation.d; this.b = pTransformation.b; this.c = pTransformation.c; this.tx = pTransformation.tx; this.ty = pTransformation.ty; } public void preTranslate(final float pX, final float pY) { this.tx += pX * this.a + pY * this.c; this.ty += pX * this.b + pY * this.d; } public void postTranslate(final float pX, final float pY) { this.tx += pX; this.ty += pY; } public Transformation setToTranslate(final float pX, final float pY) { this.a = 1.0f; this.b = 0.0f; this.c = 0.0f; this.d = 1.0f; this.tx = pX; this.ty = pY; return this; } public void preScale(final float pScaleX, final float pScaleY) { this.a *= pScaleX; this.b *= pScaleX; this.c *= pScaleY; this.d *= pScaleY; } public void postScale(final float pScaleX, final float pScaleY) { this.a = this.a * pScaleX; this.b = this.b * pScaleY; this.c = this.c * pScaleX; this.d = this.d * pScaleY; this.tx = this.tx * pScaleX; this.ty = this.ty * pScaleY; } public Transformation setToScale(final float pScaleX, final float pScaleY) { this.a = pScaleX; this.b = 0.0f; this.c = 0.0f; this.d = pScaleY; this.tx = 0.0f; this.ty = 0.0f; return this; } public void preRotate(final float pAngle) { final float angleRad = MathUtils.degToRad(pAngle); final float sin = FloatMath.sin(angleRad); final float cos = FloatMath.cos(angleRad); final float a = this.a; final float b = this.b; final float c = this.c; final float d = this.d; this.a = cos * a + sin * c; this.b = cos * b + sin * d; this.c = cos * c - sin * a; this.d = cos * d - sin * b; } public void postRotate(final float pAngle) { final float angleRad = MathUtils.degToRad(pAngle); final float sin = FloatMath.sin(angleRad); final float cos = FloatMath.cos(angleRad); final float a = this.a; final float b = this.b; final float c = this.c; final float d = this.d; final float tx = this.tx; final float ty = this.ty; this.a = a * cos - b * sin; this.b = a * sin + b * cos; this.c = c * cos - d * sin; this.d = c * sin + d * cos; this.tx = tx * cos - ty * sin; this.ty = tx * sin + ty * cos; } public Transformation setToRotate(final float pAngle) { final float angleRad = MathUtils.degToRad(pAngle); final float sin = FloatMath.sin(angleRad); final float cos = FloatMath.cos(angleRad); this.a = cos; this.b = sin; this.c = -sin; this.d = cos; this.tx = 0.0f; this.ty = 0.0f; return this; } public void postConcat(final Transformation pTransformation) { this.postConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); } private void postConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { final float a = this.a; final float b = this.b; final float c = this.c; final float d = this.d; final float tx = this.tx; final float ty = this.ty; this.a = a * pA + b * pC; this.b = a * pB + b * pD; this.c = c * pA + d * pC; this.d = c * pB + d * pD; this.tx = tx * pA + ty * pC + pTX; this.ty = tx * pB + ty * pD + pTY; } public void preConcat(final Transformation pTransformation) { this.preConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); } private void preConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { final float a = this.a; final float b = this.b; final float c = this.c; final float d = this.d; final float tx = this.tx; final float ty = this.ty; this.a = pA * a + pB * c; this.b = pA * b + pB * d; this.c = pC * a + pD * c; this.d = pC * b + pD * d; this.tx = pTX * a + pTY * c + tx; this.ty = pTX * b + pTY * d + ty; } public void transform(final float[] pVertices) { int count = pVertices.length >> 1; int i = 0; int j = 0; while(--count >= 0) { final float x = pVertices[i++]; final float y = pVertices[i++]; pVertices[j++] = x * this.a + y * this.c + this.tx; pVertices[j++] = x * this.b + y * this.d + this.ty; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import org.anddev.andengine.util.constants.DataConstants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:01:49 - 20.03.2011 */ public class DataUtils implements DataConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public static int unsignedByteToInt(final byte bByte) { return bByte & 0xFF; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.anddev.andengine.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * An InputStream that does Base64 decoding on the data read through * it. */ public class Base64InputStream extends FilterInputStream { private final Base64.Coder coder; private static byte[] EMPTY = new byte[0]; private static final int BUFFER_SIZE = 2048; private boolean eof; private byte[] inputBuffer; private int outputStart; private int outputEnd; /** * An InputStream that performs Base64 decoding on the data read * from the wrapped stream. * * @param in the InputStream to read the source data from * @param flags bit flags for controlling the decoder; see the * constants in {@link Base64} */ public Base64InputStream(final InputStream in, final int flags) { this(in, flags, false); } /** * Performs Base64 encoding or decoding on the data read from the * wrapped InputStream. * * @param in the InputStream to read the source data from * @param flags bit flags for controlling the decoder; see the * constants in {@link Base64} * @param encode true to encode, false to decode * * @hide */ public Base64InputStream(final InputStream in, final int flags, final boolean encode) { super(in); this.eof = false; this.inputBuffer = new byte[BUFFER_SIZE]; if (encode) { this.coder = new Base64.Encoder(flags, null); } else { this.coder = new Base64.Decoder(flags, null); } this.coder.output = new byte[this.coder.maxOutputSize(BUFFER_SIZE)]; this.outputStart = 0; this.outputEnd = 0; } @Override public boolean markSupported() { return false; } @Override public void mark(final int readlimit) { throw new UnsupportedOperationException(); } @Override public void reset() { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { this.in.close(); this.inputBuffer = null; } @Override public int available() { return this.outputEnd - this.outputStart; } @Override public long skip(final long n) throws IOException { if (this.outputStart >= this.outputEnd) { this.refill(); } if (this.outputStart >= this.outputEnd) { return 0; } final long bytes = Math.min(n, this.outputEnd-this.outputStart); this.outputStart += bytes; return bytes; } @Override public int read() throws IOException { if (this.outputStart >= this.outputEnd) { this.refill(); } if (this.outputStart >= this.outputEnd) { return -1; } else { return this.coder.output[this.outputStart++]; } } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (this.outputStart >= this.outputEnd) { this.refill(); } if (this.outputStart >= this.outputEnd) { return -1; } final int bytes = Math.min(len, this.outputEnd-this.outputStart); System.arraycopy(this.coder.output, this.outputStart, b, off, bytes); this.outputStart += bytes; return bytes; } /** * Read data from the input stream into inputBuffer, then * decode/encode it into the empty coder.output, and reset the * outputStart and outputEnd pointers. */ private void refill() throws IOException { if (this.eof) { return; } final int bytesRead = this.in.read(this.inputBuffer); boolean success; if (bytesRead == -1) { this.eof = true; success = this.coder.process(EMPTY, 0, 0, true); } else { success = this.coder.process(this.inputBuffer, 0, bytesRead, false); } if (!success) { throw new IOException("bad base-64"); } this.outputEnd = this.coder.op; this.outputStart = 0; } }
Java
package org.anddev.andengine.util.sort; import java.util.Comparator; import java.util.List; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:14:39 - 06.08.2010 * @param <T> */ public abstract class Sorter<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public abstract void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator); public abstract void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator); // =========================================================== // Methods // =========================================================== public final void sort(final T[] pArray, final Comparator<T> pComparator){ this.sort(pArray, 0, pArray.length, pComparator); } public final void sort(final List<T> pList, final Comparator<T> pComparator){ this.sort(pList, 0, pList.size(), pComparator); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.sort; import java.util.Comparator; import java.util.List; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:14:31 - 06.08.2010 * @param <T> */ public class InsertionSorter<T> extends Sorter<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator) { for(int i = pStart + 1; i < pEnd; i++) { final T current = pArray[i]; T prev = pArray[i - 1]; if(pComparator.compare(current, prev) < 0) { int j = i; do { pArray[j--] = prev; } while(j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0); pArray[j] = current; } } return; } @Override public void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator) { for(int i = pStart + 1; i < pEnd; i++) { final T current = pList.get(i); T prev = pList.get(i - 1); if(pComparator.compare(current, prev) < 0) { int j = i; do { pList.set(j--, prev); } while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); pList.set(j, current); } } return; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.anddev.andengine.util; import java.io.UnsupportedEncodingException; /** * Utilities for encoding and decoding the Base64 representation of * binary data. See RFCs <a * href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and <a * href="http://www.ietf.org/rfc/rfc3548.txt">3548</a>. */ public class Base64 { /** * Default values for encoder/decoder flags. */ public static final int DEFAULT = 0; /** * Encoder flag bit to omit the padding '=' characters at the end * of the output (if any). */ public static final int NO_PADDING = 1; /** * Encoder flag bit to omit all line terminators (i.e., the output * will be on one long line). */ public static final int NO_WRAP = 2; /** * Encoder flag bit to indicate lines should be terminated with a * CRLF pair instead of just an LF. Has no effect if {@code * NO_WRAP} is specified as well. */ public static final int CRLF = 4; /** * Encoder/decoder flag bit to indicate using the "URL and * filename safe" variant of Base64 (see RFC 3548 section 4) where * {@code -} and {@code _} are used in place of {@code +} and * {@code /}. */ public static final int URL_SAFE = 8; /** * Flag to pass to {@link Base64OutputStream} to indicate that it * should not close the output stream it is wrapping when it * itself is closed. */ public static final int NO_CLOSE = 16; // -------------------------------------------------------- // shared code // -------------------------------------------------------- /* package */ static abstract class Coder { public byte[] output; public int op; /** * Encode/decode another block of input data. this.output is * provided by the caller, and must be big enough to hold all * the coded data. On exit, this.opwill be set to the length * of the coded data. * * @param finish true if this is the final call to process for * this object. Will finalize the coder state and * include any final bytes in the output. * * @return true if the input so far is good; false if some * error has been detected in the input stream.. */ public abstract boolean process(byte[] input, int offset, int len, boolean finish); /** * @return the maximum number of bytes a call to process() * could produce for the given number of input bytes. This may * be an overestimate. */ public abstract int maxOutputSize(int len); } // -------------------------------------------------------- // decoding // -------------------------------------------------------- /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param str the input String to decode, which is converted to * bytes using the default charset * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(final String str, final int flags) { return Base64.decode(str.getBytes(), flags); } /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param input the input array to decode * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(final byte[] input, final int flags) { return Base64.decode(input, 0, input.length, flags); } /** * Decode the Base64-encoded data in input and return the data in * a new byte array. * * <p>The padding '=' characters at the end are considered optional, but * if any are present, there must be the correct number of them. * * @param input the data to decode * @param offset the position within the input array at which to start * @param len the number of bytes of input to decode * @param flags controls certain features of the decoded output. * Pass {@code DEFAULT} to decode standard Base64. * * @throws IllegalArgumentException if the input contains * incorrect padding */ public static byte[] decode(final byte[] input, final int offset, final int len, final int flags) { // Allocate space for the most data the input could represent. // (It could contain less if it contains whitespace, etc.) final Decoder decoder = new Decoder(flags, new byte[len*3/4]); if (!decoder.process(input, offset, len, true)) { throw new IllegalArgumentException("bad base-64"); } // Maybe we got lucky and allocated exactly enough output space. if (decoder.op == decoder.output.length) { return decoder.output; } // Need to shorten the array, so allocate a new one of the // right size and copy. final byte[] temp = new byte[decoder.op]; System.arraycopy(decoder.output, 0, temp, 0, decoder.op); return temp; } /* package */ static class Decoder extends Coder { /** * Lookup table for turning bytes into their position in the * Base64 alphabet. */ private static final int DECODE[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** * Decode lookup table for the "web safe" variant (RFC 3548 * sec. 4) where - and _ replace + and /. */ private static final int DECODE_WEBSAFE[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** Non-data values in the DECODE arrays. */ private static final int SKIP = -1; private static final int EQUALS = -2; /** * States 0-3 are reading through the next input tuple. * State 4 is having read one '=' and expecting exactly * one more. * State 5 is expecting no more data or padding characters * in the input. * State 6 is the error state; an error has been detected * in the input and no future input can "fix" it. */ private int state; // state number (0 to 6) private int value; final private int[] alphabet; public Decoder(final int flags, final byte[] output) { this.output = output; this.alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE; this.state = 0; this.value = 0; } /** * @return an overestimate for the number of bytes {@code * len} bytes could decode to. */ @Override public int maxOutputSize(final int len) { return len * 3/4 + 10; } /** * Decode another block of input data. * * @return true if the state machine is still healthy. false if * bad base-64 data has been detected in the input stream. */ @Override public boolean process(final byte[] input, final int offset, int len, final boolean finish) { if (this.state == 6) { return false; } int p = offset; len += offset; // Using local variables makes the decoder about 12% // faster than if we manipulate the member variables in // the loop. (Even alphabet makes a measurable // difference, which is somewhat surprising to me since // the member variable is final.) int state = this.state; int value = this.value; int op = 0; final byte[] output = this.output; final int[] alphabet = this.alphabet; while (p < len) { // Try the fast path: we're starting a new tuple and the // next four bytes of the input stream are all data // bytes. This corresponds to going through states // 0-1-2-3-0. We expect to use this method for most of // the data. // // If any of the next four bytes of input are non-data // (whitespace, etc.), value will end up negative. (All // the non-data values in decode are small negative // numbers, so shifting any of them up and or'ing them // together will result in a value with its top bit set.) // // You can remove this whole block and the output should // be the same, just slower. if (state == 0) { while (p+4 <= len && (value = ((alphabet[input[p] & 0xff] << 18) | (alphabet[input[p+1] & 0xff] << 12) | (alphabet[input[p+2] & 0xff] << 6) | (alphabet[input[p+3] & 0xff]))) >= 0) { output[op+2] = (byte) value; output[op+1] = (byte) (value >> 8); output[op] = (byte) (value >> 16); op += 3; p += 4; } if (p >= len) { break; } } // The fast path isn't available -- either we've read a // partial tuple, or the next four input bytes aren't all // data, or whatever. Fall back to the slower state // machine implementation. final int d = alphabet[input[p++] & 0xff]; switch (state) { case 0: if (d >= 0) { value = d; ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 1: if (d >= 0) { value = (value << 6) | d; ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 2: if (d >= 0) { value = (value << 6) | d; ++state; } else if (d == EQUALS) { // Emit the last (partial) output tuple; // expect exactly one more padding character. output[op++] = (byte) (value >> 4); state = 4; } else if (d != SKIP) { this.state = 6; return false; } break; case 3: if (d >= 0) { // Emit the output triple and return to state 0. value = (value << 6) | d; output[op+2] = (byte) value; output[op+1] = (byte) (value >> 8); output[op] = (byte) (value >> 16); op += 3; state = 0; } else if (d == EQUALS) { // Emit the last (partial) output tuple; // expect no further data or padding characters. output[op+1] = (byte) (value >> 2); output[op] = (byte) (value >> 10); op += 2; state = 5; } else if (d != SKIP) { this.state = 6; return false; } break; case 4: if (d == EQUALS) { ++state; } else if (d != SKIP) { this.state = 6; return false; } break; case 5: if (d != SKIP) { this.state = 6; return false; } break; } } if (!finish) { // We're out of input, but a future call could provide // more. this.state = state; this.value = value; this.op = op; return true; } // Done reading input. Now figure out where we are left in // the state machine and finish up. switch (state) { case 0: // Output length is a multiple of three. Fine. break; case 1: // Read one extra input byte, which isn't enough to // make another output byte. Illegal. this.state = 6; return false; case 2: // Read two extra input bytes, enough to emit 1 more // output byte. Fine. output[op++] = (byte) (value >> 4); break; case 3: // Read three extra input bytes, enough to emit 2 more // output bytes. Fine. output[op++] = (byte) (value >> 10); output[op++] = (byte) (value >> 2); break; case 4: // Read one padding '=' when we expected 2. Illegal. this.state = 6; return false; case 5: // Read all the padding '='s we expected and no more. // Fine. break; } this.state = state; this.op = op; return true; } } // -------------------------------------------------------- // encoding // -------------------------------------------------------- /** * Base64-encode the given data and return a newly allocated * String with the result. * * @param input the data to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static String encodeToString(final byte[] input, final int flags) { try { return new String(Base64.encode(input, flags), "US-ASCII"); } catch (final UnsupportedEncodingException e) { // US-ASCII is guaranteed to be available. throw new AssertionError(e); } } /** * Base64-encode the given data and return a newly allocated * String with the result. * * @param input the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static String encodeToString(final byte[] input, final int offset, final int len, final int flags) { try { return new String(Base64.encode(input, offset, len, flags), "US-ASCII"); } catch (final UnsupportedEncodingException e) { // US-ASCII is guaranteed to be available. throw new AssertionError(e); } } /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @param input the data to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static byte[] encode(final byte[] input, final int flags) { return Base64.encode(input, 0, input.length, flags); } /** * Base64-encode the given data and return a newly allocated * byte[] with the result. * * @param input the data to encode * @param offset the position within the input array at which to * start * @param len the number of bytes of input to encode * @param flags controls certain features of the encoded output. * Passing {@code DEFAULT} results in output that * adheres to RFC 2045. */ public static byte[] encode(final byte[] input, final int offset, final int len, final int flags) { final Encoder encoder = new Encoder(flags, null); // Compute the exact length of the array we will produce. int output_len = len / 3 * 4; // Account for the tail of the data and the padding bytes, if any. if (encoder.do_padding) { if (len % 3 > 0) { output_len += 4; } } else { switch (len % 3) { case 0: break; case 1: output_len += 2; break; case 2: output_len += 3; break; } } // Account for the newlines, if any. if (encoder.do_newline && len > 0) { output_len += (((len-1) / (3 * Encoder.LINE_GROUPS)) + 1) * (encoder.do_cr ? 2 : 1); } encoder.output = new byte[output_len]; encoder.process(input, offset, len, true); assert encoder.op == output_len; return encoder.output; } /* package */ static class Encoder extends Coder { /** * Emit a new line every this many output tuples. Corresponds to * a 76-character line length (the maximum allowable according to * <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>). */ public static final int LINE_GROUPS = 19; /** * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ private static final byte ENCODE[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; /** * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ private static final byte ENCODE_WEBSAFE[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', }; final private byte[] tail; /* package */ int tailLen; private int count; final public boolean do_padding; final public boolean do_newline; final public boolean do_cr; final private byte[] alphabet; public Encoder(final int flags, final byte[] output) { this.output = output; this.do_padding = (flags & NO_PADDING) == 0; this.do_newline = (flags & NO_WRAP) == 0; this.do_cr = (flags & CRLF) != 0; this.alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE; this.tail = new byte[2]; this.tailLen = 0; this.count = this.do_newline ? LINE_GROUPS : -1; } /** * @return an overestimate for the number of bytes {@code * len} bytes could encode to. */ @Override public int maxOutputSize(final int len) { return len * 8/5 + 10; } @Override public boolean process(final byte[] input, final int offset, int len, final boolean finish) { // Using local variables makes the encoder about 9% faster. final byte[] alphabet = this.alphabet; final byte[] output = this.output; int op = 0; int count = this.count; int p = offset; len += offset; int v = -1; // First we need to concatenate the tail of the previous call // with any input bytes available now and see if we can empty // the tail. switch (this.tailLen) { case 0: // There was no tail. break; case 1: if (p+2 <= len) { // A 1-byte tail with at least 2 bytes of // input available now. v = ((this.tail[0] & 0xff) << 16) | ((input[p++] & 0xff) << 8) | (input[p++] & 0xff); this.tailLen = 0; } break; case 2: if (p+1 <= len) { // A 2-byte tail with at least 1 byte of input. v = ((this.tail[0] & 0xff) << 16) | ((this.tail[1] & 0xff) << 8) | (input[p++] & 0xff); this.tailLen = 0; } break; } if (v != -1) { output[op++] = alphabet[(v >> 18) & 0x3f]; output[op++] = alphabet[(v >> 12) & 0x3f]; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (--count == 0) { if (this.do_cr) { output[op++] = '\r'; } output[op++] = '\n'; count = LINE_GROUPS; } } // At this point either there is no tail, or there are fewer // than 3 bytes of input available. // The main loop, turning 3 input bytes into 4 output bytes on // each iteration. while (p+3 <= len) { v = ((input[p] & 0xff) << 16) | ((input[p+1] & 0xff) << 8) | (input[p+2] & 0xff); output[op] = alphabet[(v >> 18) & 0x3f]; output[op+1] = alphabet[(v >> 12) & 0x3f]; output[op+2] = alphabet[(v >> 6) & 0x3f]; output[op+3] = alphabet[v & 0x3f]; p += 3; op += 4; if (--count == 0) { if (this.do_cr) { output[op++] = '\r'; } output[op++] = '\n'; count = LINE_GROUPS; } } if (finish) { // Finish up the tail of the input. Note that we need to // consume any bytes in tail before any bytes // remaining in input; there should be at most two bytes // total. if (p-this.tailLen == len-1) { int t = 0; v = ((this.tailLen > 0 ? this.tail[t++] : input[p++]) & 0xff) << 4; this.tailLen -= t; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (this.do_padding) { output[op++] = '='; output[op++] = '='; } if (this.do_newline) { if (this.do_cr) { output[op++] = '\r'; } output[op++] = '\n'; } } else if (p-this.tailLen == len-2) { int t = 0; v = (((this.tailLen > 1 ? this.tail[t++] : input[p++]) & 0xff) << 10) | (((this.tailLen > 0 ? this.tail[t++] : input[p++]) & 0xff) << 2); this.tailLen -= t; output[op++] = alphabet[(v >> 12) & 0x3f]; output[op++] = alphabet[(v >> 6) & 0x3f]; output[op++] = alphabet[v & 0x3f]; if (this.do_padding) { output[op++] = '='; } if (this.do_newline) { if (this.do_cr) { output[op++] = '\r'; } output[op++] = '\n'; } } else if (this.do_newline && op > 0 && count != LINE_GROUPS) { if (this.do_cr) { output[op++] = '\r'; } output[op++] = '\n'; } assert this.tailLen == 0; assert p == len; } else { // Save the leftovers in tail to be consumed on the next // call to encodeInternal. if (p == len-1) { this.tail[this.tailLen++] = input[p]; } else if (p == len-2) { this.tail[this.tailLen++] = input[p]; this.tail[this.tailLen++] = input[p+1]; } } this.op = op; this.count = count; return true; } } private Base64() { } // don't instantiate }
Java
package org.anddev.andengine.util.progress; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:52:44 - 03.01.2010 */ public interface ProgressCallable<T> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * Computes a result, or throws an exception if unable to do so. * @param pProgressListener * @return computed result * @throws Exception if unable to compute a result */ public T call(final IProgressListener pProgressListener) throws Exception; }
Java
package org.anddev.andengine.util.progress; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:07:35 - 09.07.2009 */ public class ProgressMonitor implements IProgressListener { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ProgressMonitor mParentProgressMonitor; private final IProgressListener mListener; private int mSubMonitorRangeFrom = 0; private int mSubMonitorRangeTo = 100; private int mProgress = 0; // =========================================================== // Constructors // =========================================================== public ProgressMonitor(final IProgressListener pListener) { this.mListener = pListener; this.mParentProgressMonitor = null; } public ProgressMonitor(final ProgressMonitor pParent){ this.mListener = null; this.mParentProgressMonitor = pParent; } // =========================================================== // Getter & Setter // =========================================================== public ProgressMonitor getParentProgressMonitor() { return this.mParentProgressMonitor; } public int getProgress() { return this.mProgress; } public void setSubMonitorRange(final int pSubMonitorRangeFrom, final int pSubMonitorRangeTo) { this.mSubMonitorRangeFrom = pSubMonitorRangeFrom; this.mSubMonitorRangeTo = pSubMonitorRangeTo; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== /** * @param pProgress between 0 and 100. */ @Override public void onProgressChanged(final int pProgress){ this.mProgress = pProgress; if(this.mParentProgressMonitor != null) { this.mParentProgressMonitor.onSubProgressChanged(pProgress); } else { this.mListener.onProgressChanged(pProgress); } } private void onSubProgressChanged(final int pSubProgress){ final int subRange = this.mSubMonitorRangeTo- this.mSubMonitorRangeFrom; final int subProgressInRange = this.mSubMonitorRangeFrom + (int)(subRange * pSubProgress / 100f); if(this.mParentProgressMonitor != null) { this.mParentProgressMonitor.onSubProgressChanged(subProgressInRange); }else{ this.mListener.onProgressChanged(subProgressInRange); } } }
Java
package org.anddev.andengine.util.progress; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:07:35 - 09.07.2009 */ public interface IProgressListener { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== /** * @param pProgress between 0 and 100. */ public void onProgressChanged(final int pProgress); }
Java
package org.anddev.andengine.util; import org.anddev.andengine.util.constants.TimeConstants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:48:49 - 04.04.2011 */ public class TimeUtils implements TimeConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static String formatSeconds(final int pSecondsTotal) { return formatSeconds(pSecondsTotal, new StringBuilder()); } public static String formatSeconds(final int pSecondsTotal, final StringBuilder pStringBuilder) { final int minutes = pSecondsTotal / SECONDSPERMINUTE; final int seconds = pSecondsTotal % SECONDSPERMINUTE; pStringBuilder.append(minutes); pStringBuilder.append(':'); if(seconds < 10) { pStringBuilder.append('0'); } pStringBuilder.append(seconds); return pStringBuilder.toString(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.app.Dialog; import android.view.WindowManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:04:09 - 12.05.2011 */ public class DialogUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static void keepScreenOn(final Dialog pDialog) { pDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.util.SparseArray; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:51:29 - 20.08.2010 * @param <T> */ public class Library<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final SparseArray<T> mItems; // =========================================================== // Constructors // =========================================================== public Library() { this.mItems = new SparseArray<T>(); } public Library(final int pInitialCapacity) { this.mItems = new SparseArray<T>(pInitialCapacity); } // =========================================================== // Getter & Setter // =========================================================== public void put(final int pID, final T pItem) { final T existingItem = this.mItems.get(pID); if(existingItem == null) { this.mItems.put(pID, pItem); } else { throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + existingItem.toString() + "'."); } } public void remove(final int pID) { this.mItems.remove(pID); } public T get(final int pID) { return this.mItems.get(pID); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:01:08 - 03.04.2010 */ public class StringUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static String padFront(final String pString, final char pPadChar, final int pLength) { final int padCount = pLength - pString.length(); if(padCount <= 0) { return pString; } else { final StringBuilder sb = new StringBuilder(); for(int i = padCount - 1; i >= 0; i--) { sb.append(pPadChar); } sb.append(pString); return sb.toString(); } } public static int countOccurrences(final String pString, final char pCharacter) { int count = 0; int lastOccurrence = pString.indexOf(pCharacter, 0); while (lastOccurrence != -1) { count++; lastOccurrence = pString.indexOf(pCharacter, lastOccurrence + 1); } return count; } /** * Split a String by a Character, i.e. Split lines by using '\n'.<br/> * Same behavior as <code>String.split("" + pCharacter);</code> . * * @param pString * @param pCharacter * @return */ public static String[] split(final String pString, final char pCharacter) { return StringUtils.split(pString, pCharacter, null); } /** * Split a String by a Character, i.e. Split lines by using '\n'.<br/> * Same behavior as <code>String.split("" + pCharacter);</code> . * * @param pString * @param pCharacter * @param pReuse tries to reuse the String[] if the length is the same as the length needed. * @return */ public static String[] split(final String pString, final char pCharacter, final String[] pReuse) { final int partCount = StringUtils.countOccurrences(pString, pCharacter) + 1; final boolean reuseable = pReuse != null && pReuse.length == partCount; final String[] out = (reuseable) ? pReuse : new String[partCount]; if(partCount == 0) { out[0] = pString; } else { int from = 0; int to; for (int i = 0; i < partCount - 1; i++) { to = pString.indexOf(pCharacter, from); out[i] = pString.substring(from, to); from = to + 1; } out[partCount - 1] = pString.substring(from, pString.length()); } return out; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.levelstats; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.SimplePreferences; import org.anddev.andengine.util.StreamUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.content.Context; import android.content.SharedPreferences; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:13:55 - 18.10.2010 */ public class LevelStatsDBConnector { // =========================================================== // Constants // =========================================================== private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID = "preferences.levelstatsdbconnector.playerid"; // =========================================================== // Fields // =========================================================== private final String mSecret; private final String mSubmitURL; private final int mPlayerID; // =========================================================== // Constructors // =========================================================== public LevelStatsDBConnector(final Context pContext, final String pSecret, final String pSubmitURL) { this.mSecret = pSecret; this.mSubmitURL = pSubmitURL; final SharedPreferences simplePreferences = SimplePreferences.getInstance(pContext); final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, -1); if(playerID != -1) { this.mPlayerID = playerID; } else { this.mPlayerID = MathUtils.random(1000000000, Integer.MAX_VALUE); SimplePreferences.getEditorInstance(pContext).putInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, this.mPlayerID).commit(); } } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed) { this.submitAsync(pLevelID, pSolved, pSecondsElapsed, null); } public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed, final Callback<Boolean> pCallback) { new Thread(new Runnable() { @Override public void run() { try{ /* Create a new HttpClient and Post Header. */ final HttpClient httpClient = new DefaultHttpClient(); final HttpPost httpPost = new HttpPost(LevelStatsDBConnector.this.mSubmitURL); /* Append POST data. */ final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5); nameValuePairs.add(new BasicNameValuePair("level_id", String.valueOf(pLevelID))); nameValuePairs.add(new BasicNameValuePair("solved", (pSolved) ? "1" : "0")); nameValuePairs.add(new BasicNameValuePair("secondsplayed", String.valueOf(pSecondsElapsed))); nameValuePairs.add(new BasicNameValuePair("player_id", String.valueOf(LevelStatsDBConnector.this.mPlayerID))); nameValuePairs.add(new BasicNameValuePair("secret", String.valueOf(LevelStatsDBConnector.this.mSecret))); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); /* Execute HTTP Post Request. */ final HttpResponse httpResponse = httpClient.execute(httpPost); final int statusCode = httpResponse.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK) { final String response = StreamUtils.readFully(httpResponse.getEntity().getContent()); if(response.equals("<success/>")) { if(pCallback != null) { pCallback.onCallback(true); } } else { if(pCallback != null) { pCallback.onCallback(false); } } } else { if(pCallback != null) { pCallback.onCallback(false); } } }catch(final IOException e) { Debug.e(e); if(pCallback != null) { pCallback.onCallback(false); } } } }).start(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:40:42 - 27.12.2010 */ public interface ParameterCallable<T> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void call(final T pParameter); }
Java
package org.anddev.andengine.util.path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:00:24 - 16.08.2010 */ public interface ITiledMap<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int getTileColumns(); public int getTileRows(); public void onTileVisitedByPathFinder(final int pTileColumn, int pTileRow); public boolean isTileBlocked(final T pEntity, final int pTileColumn, final int pTileRow); public float getStepCost(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); }
Java
package org.anddev.andengine.util.path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:19:11 - 17.08.2010 */ public enum Direction { // =========================================================== // Elements // =========================================================== UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mDeltaX; private final int mDeltaY; // =========================================================== // Constructors // =========================================================== private Direction(final int pDeltaX, final int pDeltaY) { this.mDeltaX = pDeltaX; this.mDeltaY = pDeltaY; } public static Direction fromDelta(final int pDeltaX, final int pDeltaY) { if(pDeltaX == 0) { if(pDeltaY == 1) { return DOWN; } else if(pDeltaY == -1) { return UP; } } else if (pDeltaY == 0) { if(pDeltaX == 1) { return RIGHT; } else if(pDeltaX == -1) { return LEFT; } } throw new IllegalArgumentException(); } // =========================================================== // Getter & Setter // =========================================================== public int getDeltaX() { return this.mDeltaX; } public int getDeltaY() { return this.mDeltaY; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path.astar; import java.util.ArrayList; import java.util.Collections; import org.anddev.andengine.util.path.IPathFinder; import org.anddev.andengine.util.path.ITiledMap; import org.anddev.andengine.util.path.Path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:16:17 - 16.08.2010 */ public class AStarPathFinder<T> implements IPathFinder<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ArrayList<Node> mVisitedNodes = new ArrayList<Node>(); private final ArrayList<Node> mOpenNodes = new ArrayList<Node>(); private final ITiledMap<T> mTiledMap; private final int mMaxSearchDepth; private final Node[][] mNodes; private final boolean mAllowDiagonalMovement; private final IAStarHeuristic<T> mAStarHeuristic; // =========================================================== // Constructors // =========================================================== public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement) { this(pTiledMap, pMaxSearchDepth, pAllowDiagonalMovement, new EuclideanHeuristic<T>()); } public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement, final IAStarHeuristic<T> pAStarHeuristic) { this.mAStarHeuristic = pAStarHeuristic; this.mTiledMap = pTiledMap; this.mMaxSearchDepth = pMaxSearchDepth; this.mAllowDiagonalMovement = pAllowDiagonalMovement; this.mNodes = new Node[pTiledMap.getTileRows()][pTiledMap.getTileColumns()]; final Node[][] nodes = this.mNodes; for(int x = pTiledMap.getTileColumns() - 1; x >= 0; x--) { for(int y = pTiledMap.getTileRows() - 1; y >= 0; y--) { nodes[y][x] = new Node(x, y); } } } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { final ITiledMap<T> tiledMap = this.mTiledMap; if(tiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow)) { return null; } /* Drag some fields to local variables. */ final ArrayList<Node> openNodes = this.mOpenNodes; final ArrayList<Node> visitedNodes = this.mVisitedNodes; final Node[][] nodes = this.mNodes; final Node fromNode = nodes[pFromTileRow][pFromTileColumn]; final Node toNode = nodes[pToTileRow][pToTileColumn]; final IAStarHeuristic<T> aStarHeuristic = this.mAStarHeuristic; final boolean allowDiagonalMovement = this.mAllowDiagonalMovement; final int maxSearchDepth = this.mMaxSearchDepth; /* Initialize algorithm. */ fromNode.mCost = 0; fromNode.mDepth = 0; toNode.mParent = null; visitedNodes.clear(); openNodes.clear(); openNodes.add(fromNode); int currentDepth = 0; while(currentDepth < maxSearchDepth && !openNodes.isEmpty()) { /* The first Node in the open list is the one with the lowest cost. */ final Node current = openNodes.remove(0); if(current == toNode) { break; } visitedNodes.add(current); /* Loop over all neighbors of this tile. */ for(int dX = -1; dX <= 1; dX++) { for(int dY = -1; dY <= 1; dY++) { if((dX == 0) && (dY == 0)) { continue; } if(!allowDiagonalMovement) { if((dX != 0) && (dY != 0)) { continue; } } final int neighborTileColumn = dX + current.mTileColumn; final int neighborTileRow = dY + current.mTileRow; if(!this.isTileBlocked(pEntity, pFromTileColumn, pFromTileRow, neighborTileColumn, neighborTileRow)) { final float neighborCost = current.mCost + tiledMap.getStepCost(pEntity, current.mTileColumn, current.mTileRow, neighborTileColumn, neighborTileRow); final Node neighbor = nodes[neighborTileRow][neighborTileColumn]; tiledMap.onTileVisitedByPathFinder(neighborTileColumn, neighborTileRow); /* Re-evaluate if there is a better path. */ if(neighborCost < neighbor.mCost) { // TODO Is this ever possible with AStar ?? if(openNodes.contains(neighbor)) { openNodes.remove(neighbor); } if(visitedNodes.contains(neighbor)) { visitedNodes.remove(neighbor); } } if(!openNodes.contains(neighbor) && !(visitedNodes.contains(neighbor))) { neighbor.mCost = neighborCost; if(neighbor.mCost <= pMaxCost) { neighbor.mExpectedRestCost = aStarHeuristic.getExpectedRestCost(tiledMap, pEntity, neighborTileColumn, neighborTileRow, pToTileColumn, pToTileRow); currentDepth = Math.max(currentDepth, neighbor.setParent(current)); openNodes.add(neighbor); /* Ensure always the node with the lowest cost+heuristic * will be used next, simply by sorting. */ Collections.sort(openNodes); } } } } } } /* Check if a path was found. */ if(toNode.mParent == null) { return null; } /* Traceback path. */ final Path path = new Path(); Node tmp = nodes[pToTileRow][pToTileColumn]; while(tmp != fromNode) { path.prepend(tmp.mTileColumn, tmp.mTileRow); tmp = tmp.mParent; } path.prepend(pFromTileColumn, pFromTileRow); return path; } // =========================================================== // Methods // =========================================================== protected boolean isTileBlocked(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { if((pToTileColumn < 0) || (pToTileRow < 0) || (pToTileColumn >= this.mTiledMap.getTileColumns()) || (pToTileRow >= this.mTiledMap.getTileRows())) { return true; } else if((pFromTileColumn == pToTileColumn) && (pFromTileRow == pToTileRow)) { return true; } return this.mTiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow); } // =========================================================== // Inner and Anonymous Classes // =========================================================== private static class Node implements Comparable<Node> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== Node mParent; int mDepth; final int mTileColumn; final int mTileRow; float mCost; float mExpectedRestCost; // =========================================================== // Constructors // =========================================================== public Node(final int pTileColumn, final int pTileRow) { this.mTileColumn = pTileColumn; this.mTileRow = pTileRow; } // =========================================================== // Getter & Setter // =========================================================== public int setParent(final Node parent) { this.mDepth = parent.mDepth + 1; this.mParent = parent; return this.mDepth; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int compareTo(final Node pOther) { final float totalCost = this.mExpectedRestCost + this.mCost; final float totalCostOther = pOther.mExpectedRestCost + pOther.mCost; if (totalCost < totalCostOther) { return -1; } else if (totalCost > totalCostOther) { return 1; } else { return 0; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ public class EuclideanHeuristic<T> implements IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getExpectedRestCost(final ITiledMap<T> pTileMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { final float dX = pTileToX - pTileFromX; final float dY = pTileToY - pTileFromY; return FloatMath.sqrt(dX * dX + dY * dY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ public class NullHeuristic<T> implements IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { return 0; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ public class ManhattanHeuristic<T> implements IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { return Math.abs(pTileFromX - pTileToX) + Math.abs(pTileToX - pTileToY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:59:20 - 16.08.2010 */ public interface IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); }
Java
package org.anddev.andengine.util.path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:57:13 - 16.08.2010 */ public interface IPathFinder<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); }
Java
package org.anddev.andengine.util.path; import java.util.ArrayList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:00:24 - 16.08.2010 */ public class Path { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ArrayList<Step> mSteps = new ArrayList<Step>(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public int getLength() { return this.mSteps.size(); } public Step getStep(final int pIndex) { return this.mSteps.get(pIndex); } public Direction getDirectionToPreviousStep(final int pIndex) { if(pIndex == 0) { return null; } else { final int dX = this.getTileColumn(pIndex - 1) - this.getTileColumn(pIndex); final int dY = this.getTileRow(pIndex - 1) - this.getTileRow(pIndex); return Direction.fromDelta(dX, dY); } } public Direction getDirectionToNextStep(final int pIndex) { if(pIndex == this.getLength() - 1) { return null; } else { final int dX = this.getTileColumn(pIndex + 1) - this.getTileColumn(pIndex); final int dY = this.getTileRow(pIndex + 1) - this.getTileRow(pIndex); return Direction.fromDelta(dX, dY); } } public int getTileColumn(final int pIndex) { return this.getStep(pIndex).getTileColumn(); } public int getTileRow(final int pIndex) { return this.getStep(pIndex).getTileRow(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void append(final int pTileColumn, final int pTileRow) { this.append(new Step(pTileColumn, pTileRow)); } public void append(final Step pStep) { this.mSteps.add(pStep); } public void prepend(final int pTileColumn, final int pTileRow) { this.prepend(new Step(pTileColumn, pTileRow)); } public void prepend(final Step pStep) { this.mSteps.add(0, pStep); } public boolean contains(final int pTileColumn, final int pTileRow) { final ArrayList<Step> steps = this.mSteps; for(int i = steps.size() - 1; i >= 0; i--) { final Step step = steps.get(i); if(step.getTileColumn() == pTileColumn && step.getTileRow() == pTileRow) { return true; } } return false; } public int getFromTileRow() { return this.getTileRow(0); } public int getFromTileColumn() { return this.getTileColumn(0); } public int getToTileRow() { return this.getTileRow(this.mSteps.size() - 1); } public int getToTileColumn() { return this.getTileColumn(this.mSteps.size() - 1); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public class Step { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mTileColumn; private final int mTileRow; // =========================================================== // Constructors // =========================================================== public Step(final int pTileColumn, final int pTileRow) { this.mTileColumn = pTileColumn; this.mTileRow = pTileRow; } // =========================================================== // Getter & Setter // =========================================================== public int getTileColumn() { return this.mTileColumn; } public int getTileRow() { return this.mTileRow; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int hashCode() { return this.mTileColumn << 16 + this.mTileRow; } @Override public boolean equals(final Object pOther) { if(this == pOther) { return true; } if(pOther == null) { return false; } if(this.getClass() != pOther.getClass()) { return false; } final Step other = (Step) pOther; if(this.mTileColumn != other.mTileColumn) { return false; } if(this.mTileRow != other.mTileRow) { return false; } return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.util; import java.util.Arrays; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:54:24 - 07.11.2010 */ public class MultiKey<K> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final K[] mKeys; private final int mCachedHashCode; // =========================================================== // Constructors // =========================================================== public MultiKey(final K... pKeys) { this.mKeys = pKeys; this.mCachedHashCode = MultiKey.hash(pKeys); } // =========================================================== // Getter & Setter // =========================================================== public K[] getKeys() { return this.mKeys; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean equals(final Object pOther) { if(pOther == this) { return true; } if(pOther instanceof MultiKey<?>) { final MultiKey<?> otherMultiKey = (MultiKey<?>) pOther; return Arrays.equals(this.mKeys, otherMultiKey.mKeys); } return false; } public static int hash(final Object ... pKeys) { int hashCode = 0; for(final Object key : pKeys) { if(key != null) { hashCode ^= key.hashCode(); } } return hashCode; } @Override public int hashCode() { return this.mCachedHashCode; } @Override public String toString() { return "MultiKey" + Arrays.asList(this.mKeys).toString(); } // =========================================================== // Methods // =========================================================== public K getKey(final int pIndex) { return this.mKeys[pIndex]; } public int size() { return this.mKeys.length; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 23:02:47 - 21.08.2010 */ public abstract class PoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== Pool<? extends PoolItem> mParent; boolean mRecycled = true; // =========================================================== // Constructors // =========================================================== public Pool<? extends PoolItem> getParent() { return this.mParent; } // =========================================================== // Getter & Setter // =========================================================== public boolean isRecycled() { return this.mRecycled; } public boolean isFromPool(final Pool<? extends PoolItem> pPool) { return pPool == this.mParent; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== protected void onRecycle() { } protected void onObtain() { } public void recycle() { if(this.mParent == null) { throw new IllegalStateException("Item already recycled!"); } this.mParent.recycle(this); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; import org.anddev.andengine.entity.IEntity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 00:53:22 - 28.08.2010 */ public class EntityDetachRunnablePoolItem extends RunnablePoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected IEntity mEntity; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public void setEntity(final IEntity pEntity) { this.mEntity = pEntity; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void run() { this.mEntity.detachSelf(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:46:50 - 27.08.2010 */ public abstract class RunnablePoolItem extends PoolItem implements Runnable { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 23:00:21 - 21.08.2010 * @param <T> */ public abstract class Pool<T extends PoolItem> extends GenericPool<T>{ // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public Pool() { super(); } public Pool(final int pInitialSize) { super(pInitialSize); } public Pool(final int pInitialSize, final int pGrowth) { super(pInitialSize, pGrowth); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected T onHandleAllocatePoolItem() { final T poolItem = super.onHandleAllocatePoolItem(); poolItem.mParent = this; return poolItem; } @Override protected void onHandleObtainItem(final T pPoolItem) { pPoolItem.mRecycled = false; pPoolItem.onObtain(); } @Override protected void onHandleRecycleItem(final T pPoolItem) { pPoolItem.onRecycle(); pPoolItem.mRecycled = true; } @Override public synchronized void recyclePoolItem(final T pPoolItem) { if(pPoolItem.mParent == null) { throw new IllegalArgumentException("PoolItem not assigned to a pool!"); } else if(!pPoolItem.isFromPool(this)) { throw new IllegalArgumentException("PoolItem from another pool!"); } else if(pPoolItem.isRecycled()) { throw new IllegalArgumentException("PoolItem already recycled!"); } super.recyclePoolItem(pPoolItem); } // =========================================================== // Methods // =========================================================== public synchronized boolean ownsPoolItem(final T pPoolItem) { return pPoolItem.mParent == this; } @SuppressWarnings("unchecked") void recycle(final PoolItem pPoolItem) { this.recyclePoolItem((T) pPoolItem); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:16:25 - 31.08.2010 */ public class EntityDetachRunnablePoolUpdateHandler extends RunnablePoolUpdateHandler<EntityDetachRunnablePoolItem> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected EntityDetachRunnablePoolItem onAllocatePoolItem() { return new EntityDetachRunnablePoolItem(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; import android.util.SparseArray; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:13:26 - 02.03.2011 */ public class MultiPool<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final SparseArray<GenericPool<T>> mPools = new SparseArray<GenericPool<T>>(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void registerPool(final int pID, final GenericPool<T> pPool) { this.mPools.put(pID, pPool); } public T obtainPoolItem(final int pID) { final GenericPool<T> pool = this.mPools.get(pID); if(pool == null) { return null; } else { return pool.obtainPoolItem(); } } public void recyclePoolItem(final int pID, final T pItem) { final GenericPool<T> pool = this.mPools.get(pID); if(pool != null) { pool.recyclePoolItem(pItem); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; import java.util.Collections; import java.util.Stack; import org.anddev.andengine.util.Debug; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 22:19:55 - 31.08.2010 * @param <T> */ public abstract class GenericPool<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Stack<T> mAvailableItems = new Stack<T>(); private int mUnrecycledCount; private final int mGrowth; // =========================================================== // Constructors // =========================================================== public GenericPool() { this(0); } public GenericPool(final int pInitialSize) { this(pInitialSize, 1); } public GenericPool(final int pInitialSize, final int pGrowth) { if(pGrowth < 0) { throw new IllegalArgumentException("pGrowth must be at least 0!"); } this.mGrowth = pGrowth; if(pInitialSize > 0) { this.batchAllocatePoolItems(pInitialSize); } } // =========================================================== // Getter & Setter // =========================================================== public synchronized int getUnrecycledCount() { return this.mUnrecycledCount; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract T onAllocatePoolItem(); // =========================================================== // Methods // =========================================================== /** * @param pItem every item passes this method just before it gets recycled. */ protected void onHandleRecycleItem(final T pItem) { } protected T onHandleAllocatePoolItem() { return this.onAllocatePoolItem(); } /** * @param pItem every item that was just obtained from the pool, passes this method. */ protected void onHandleObtainItem(final T pItem) { } public synchronized void batchAllocatePoolItems(final int pCount) { final Stack<T> availableItems = this.mAvailableItems; for(int i = pCount - 1; i >= 0; i--) { availableItems.push(this.onHandleAllocatePoolItem()); } } public synchronized T obtainPoolItem() { final T item; if(this.mAvailableItems.size() > 0) { item = this.mAvailableItems.pop(); } else { if(this.mGrowth == 1) { item = this.onHandleAllocatePoolItem(); } else { this.batchAllocatePoolItems(this.mGrowth); item = this.mAvailableItems.pop(); } Debug.i(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledCount + " item not yet recycled. Allocated " + this.mGrowth + " more."); } this.onHandleObtainItem(item); this.mUnrecycledCount++; return item; } public synchronized void recyclePoolItem(final T pItem) { if(pItem == null) { throw new IllegalArgumentException("Cannot recycle null item!"); } this.onHandleRecycleItem(pItem); this.mAvailableItems.push(pItem); this.mUnrecycledCount--; if(this.mUnrecycledCount < 0) { Debug.e("More items recycled than obtained!"); } } public synchronized void shufflePoolItems() { Collections.shuffle(this.mAvailableItems); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 23:03:58 - 21.08.2010 * @param <T> */ public abstract class RunnablePoolUpdateHandler<T extends RunnablePoolItem> extends PoolUpdateHandler<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public RunnablePoolUpdateHandler() { } public RunnablePoolUpdateHandler(final int pInitialPoolSize) { super(pInitialPoolSize); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected abstract T onAllocatePoolItem(); @Override protected void onHandlePoolItem(final T pRunnablePoolItem) { pRunnablePoolItem.run(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java